2017-03-05 35 views
0

我正在研究一个程序,以查找在我制作的部分卡住的碎片。到目前为止,我已经能够获得一个干净的部分和一个芯片的一部分,并减去两个图像,留下二者之间的差异作为二进制图像。我不明白的是如何检测二进制图像中的这个项目。到目前为止,我使用了SimpleBlobDetector函数,但我必须对图像进行模糊处理才能使其工作,我担心它不能用于较小的碎片。我希望能够在没有大量模糊的情况下检测原稿。任何帮助,将不胜感激。代码和图像如下。Opencv二进制项目检测

import cv2 
import numpy as np 

#Load Images 
tempImg = cv2.imread('images/partchip.jpg') 
lineImg = cv2.imread('images/partnochip.jpg') 

#Crop Images 
cropTemp = tempImg[460:589, 647:875] 
cropLine = lineImg[460:589, 647:875] 

#Gray Scale 
grayTemp = cv2.cvtColor(cropTemp,cv2.COLOR_BGR2GRAY) 
grayLine = cv2.cvtColor(cropLine,cv2.COLOR_BGR2GRAY) 

#Subtract Images 
holder = cv2.absdiff(grayTemp,grayLine) 

#THreshold Subtracted Image 
th, imgDiff = cv2.threshold(holder, 160, 255, cv2.THRESH_BINARY_INV) 

#Blur Image 
#blur = imgDiff 
blur = cv2.blur(imgDiff,(20,20)) 

#Detect Blobs 
detector = cv2.SimpleBlobDetector_create() 
blob = detector.detect(blur) 


imgkeypoints = cv2.drawKeypoints(blur, blob, np.array([]), (0,255,0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) 
originalWithPoints=cv2.drawKeypoints(cropTemp, blob, np.array([]), (0,255,0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) 

cv2.namedWindow("Template", cv2.WINDOW_NORMAL) 
cv2.namedWindow("Line", cv2.WINDOW_NORMAL) 
cv2.namedWindow("Difference", cv2.WINDOW_NORMAL) 

cv2.resizeWindow("Template", 500, 300) 
cv2.resizeWindow("Line", 500, 300) 
cv2.resizeWindow("Difference", 500, 300) 


cv2.imshow('Template',originalWithPoints) 
cv2.imshow('Line',cropLine) 
cv2.imshow('Difference',imgkeypoints) 


cv2.waitKey(0) 
cv2.destroyAllWindows() 

Part with chip Part with No Chip

+0

你能上传正在使用的图像吗? –

+0

只是,他们链接下面的代码 – shark38j

+0

但你似乎没有(视觉)之间的差异,你已经上传的两幅图片 – ZdaR

回答

1

我用你的代码,以查找异常。我在imgDiff二值图像上获得了具有最大面积的轮廓。使用该功能,我可以将它与一个矩形绑定。

enter image description here

我希望这是你在找什么....

编辑:

注:

我曾与下面的代码一起解释的过程:使用cv2.bitwise_not(imgDiff)反转您的imgDiff,因为如果对象是白色,则会找到轮廓。

#---Finding the contours present in 'imgDiff'--- 
_, contours,hierarchy = cv2.findContours(imgDiff,2,1) 

ff = 0 #----to determine which contour to select--- 
area = 0 #----to determine the maximum area--- 
for i in range(len(contours)): 
    if(cv2.contourArea(contours[i]) > area): 
     area = cv2.contourArea(contours[i]) 
     ff = i 

#---Bounding the contour having largest area--- 
x,y,w,h = cv2.boundingRect(contours[ff]) 
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) 
cv2.imshow('fin.jpg',img) 
+0

Jeru,你可以为此发布代码吗?这正是我想要做的,但我不知道如何找到最大的区域。再次感谢!!! – shark38j