发现轮廓不正确

时间:2020-02-11 23:12:50

标签: python opencv

我有一个问题要找到我使用过的findcontour图像的轮廓,我做错了吗?

Here's my result but its not accurate.

Here's the image I've used

gs = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gs, (3,3),0)
ret_otsu,im_bw_otsu = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

kernel = np.ones((50,50),np.uint8)
closing = cv2.morphologyEx(im_bw_otsu, cv2.MORPH_CLOSE, kernel)
_, contours, hierarchy = cv2.findContours(closing,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

plottedContour = cv2.drawContours(gs,contours,-1,(0,255,0),2)
cv2.imshow('CONTOUR',plottedContour)

2 个答案:

答案 0 :(得分:1)

您可能希望查看其他轮廓,

cv2.drawContours(gs,contours,-1,(0,255,0),2)
cv2.drawContours(gs,contours,0,(0,255,0),2)
cv2.drawContours(gs,contours,1,(0,255,0),2)
cv2.drawContours(gs,contours,2,(0,255,0),2)
...

答案 1 :(得分:1)

该想法是在假定香蕉是图像中主要对象的前提下,获得用于最大轮廓的二值图像滤波器。在这里,我们可以使用cv2.rectangle绘制矩形或使用cv2.drawContours绘制轮廓。 (可选)我们也可以使用Numpy切片来裁剪ROI。

绘制矩形

enter image description here

绘制轮廓

enter image description here

提取的投资回报率

enter image description here

代码

import cv2

# Load image, grayscale, blur, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)

for c in cnts:
    # Crop ROI
    x,y,w,h = cv2.boundingRect(c)
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite('ROI.png', ROI)

    # Draw rectangle
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)

    # Draw contours
    # cv2.drawContours(image, [c], -1, (36,255,12), 2)
    break

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
相关问题