2017-06-17 185 views
0

我有兩個二進制圖像,我試圖檢測它們中的白色斑點的輪廓(拼貼右側的粉色輪廓是輪廓結果)。cv2.findContours無法檢測輪廓

cv2.contourFind()爲Contour1工作的罰款:

Contour1 Image & Result

但輪廓2它的行事怪異:

Contour2 Image & Result

下面是函數調用它

#Convert Image to grayscale 
img = cv2.imread(file_name) 
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV) 

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) 
dilated = cv2.dilate(mask, kernel, iterations=2) 
image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 

for contour in contours: 
    [x, y, w, h] = cv2.boundingRect(contour) 
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2) 

使用此contours變量我圍繞找到的點繪製矩形。 我不明白它爲什麼適用於Contour1,但在Contour2看起來非常相似時失敗。

+1

請編輯您的問題提供了[最小的,完整的,和可覈查的示例](https://stackoverflow.com/help/mcve)。 –

+0

完成,@AlexanderReynolds –

+0

每個圖像的「輪廓」中有多少個輪廓? –

回答

1

錯誤:二進制圖像在輪廓2中有一個薄的白色邊框,但不在輪廓1(我的壞!)。因爲我問外部輪廓,cv2.RETR_EXTERNAL

image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 

的輪廓2只有最外面的框檢測的,所以它沒有一個孩子得到了繪製。但是在Contour1中,二值圖像周圍沒有白色邊框,因此檢測到內部白色斑點。

解決方案:使用cv2.RETR_LISTcv2.RETR_CCOMP