OpenCV python findContours错误的结果

问题描述

我正在尝试使用python和OpenCV查找图像中白色区域的坐标。 使用erode => threshold => findContours,这应该是一个简单的任务。

这是我的代码

th_er = cv2.erode(th,np.ones((15,15),np.uint8))
th_er = cv2.bitwise_not(th_er)

contours,_ = cv2.findContours(th_er,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    cv2.rectangle(th_er,(x,y),(x + w,y + h),(100,100,100),5)

cv2.imshow('il',th_er)
cv2.waitKey()

我的问题是“ findContours”返回的结果很奇怪,如图像here所示。

那么,有人遇到此问题或知道任何可能的解决方法吗?

here是原始图像。

解决方法

img = cv2.imread('try.jpg',0) # (200,1427)
img2 = cv2.imread('try.jpg',-1) # (200,1427,4)

# gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) # <-- you can use this to convert into grayscale image and then feed it to cv2.erode(img2,.....)
th_er = cv2.erode(img,np.ones((15,15),np.uint8))
th_er = cv2.bitwise_not(th_er)

contours,_ = cv2.findContours(th_er,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    cv2.rectangle(img2,(x,y),(x + w,y + h),(200,100,100),5)
plt.figure(figsize=(15,20))

plt.imshow(img2)
plt.show()

enter image description here

编辑:

现在工作正常。

th_er1 = 255-cv2.bitwise_not(th_er)正如我说的,对象应为白色,背景应为黑色。反之亦然。减去255,它现在将是正确的格式。

# img = cv2.imread('try.png',1427)
img = cv2.imread('try.png') # (200,4)

gray = cv2.cvtColor(img,.....)
_,th = cv2.threshold(gray,127,255,cv2.THRESH_BINARY+ cv2.THRESH_OTSU) 
th_er = cv2.erode(th,np.uint8))
th_er1 = 255-cv2.bitwise_not(th_er) # <----- here

contours,_ = cv2.findContours(th_er1,h = cv2.boundingRect(cntr)
    cv2.rectangle(img,20))

plt.imshow(img)
plt.show()

enter image description here