用鼠标单击轮廓,但是只能找到1个轮廓?

问题描述

我需要用户用鼠标在给定图像中以特定顺序在轮廓内部进行选择(这与整个代码的另一部分有关)。

下面的代码可以正确识别9个轮廓。问题在于,单击代码时,代码看到的唯一轮廓是左上角的数字8(请参见下图),无论单击任何其他轮廓都将被忽略。

那么这是怎么回事?

代码的测试图像(虽然是黑白的)是3通道jpg

enter image description here

显示的窗口,

enter image description here

import cv2

def mouse_call_back(event,x,y,flags,param):  
    if event == cv2.cv2.EVENT_LBUTTONDOWN:
        for i in range(0,len(contours)):         
            r = cv2.pointpolygonTest(contours[i],(y,x),False)
            print(r)
            if r > 0:
                print("Selected contour ",i)


dots            = cv2.imread('dots.jpg',cv2.IMREAD_COLOR)
dots_cpy        = cv2.cvtColor(dots,cv2.COLOR_BGR2GRAY)
(threshold,bw) = cv2.threshold(dots_cpy,127,255,cv2.THRESH_BINARY)
contours,hier  = cv2.findContours(bw,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
contours        = contours[0:-1] # takes out contour bounding the whole image
      
cv2.namedWindow("res")
cv2.drawContours(dots,contours,-1,(0,0),3)
for idx,c in enumerate(contours):  # numbers the contours
    x = int(sum(c[:,0]) / len(c))
    y = int(sum(c[:,1]) / len(c))
    cv2.putText(dots,str(idx),(x,y),cv2.FONT_HERShey_SIMPLEX,1,255),2)
cv2.imshow("res",dots)
cv2.setMouseCallback('res',mouse_call_back)
 
cv2.waitKey()

EDIT :: SOLUTION

r = cv2.pointpolygonTest(contours[i],False)行中插入了xy,它应该是r = cv2.pointpolygonTest(contours[i],False)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)