我正在制作一个程序来查找卡在我制作的部件中的碎片。到目前为止,我已经能够采用干净的部件和带有芯片的部件并减去两个图像,将两者之间的任何差异留作二进制图像。我不明白的是如何在二进制图像中检测这个项目。到目前为止,我使用了SimpleBlobDetector函数,但我必须模糊图像以使其工作,我担心它不会使用较小的碎片。我希望能够在没有广泛模糊的情况下检测到原始图像。任何帮助,将不胜感激。代码和图片如下。
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()
答案 0 :(得分:1)
我用你的代码找到异常。我获得了imgDiff
二进制图像上具有最大面积的轮廓。使用它我能够用矩形绑定它。
我希望这就是你要找的......
修改强>
我已经解释了该程序以及下面的代码:
注意:使用imgDiff
反转cv2.bitwise_not(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)