opencv 用鼠标点击轮廓,但只能找到1个轮廓?

o0lyfsai  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(191)

我需要用户用鼠标在给定的图像中以特定的顺序选择轮廓内部(这是整个代码的另一部分)。
代码(下图)正确识别了9条轮廓线。问题是,当鼠标点击时,代码看到的唯一轮廓线是左上角的点,数字8(见下图)&无论点击其中的其他轮廓线,它们都会被忽略。
上面是什么?
代码的测试图像虽然是白色的,但却是3通道jpg

显示窗口,

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, 255, 0), 3)
for idx, c in enumerate(contours):  # numbers the contours
    x = int(sum(c[:,0,0]) / len(c))
    y = int(sum(c[:,0,1]) / len(c))
    cv2.putText(dots, str(idx), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.imshow("res", dots)
cv2.setMouseCallback('res', mouse_call_back)
 
cv2.waitKey()
i7uaboj4

i7uaboj41#

r = cv2.pointPolygonTest(contours[i], (y, x), False)这一行把xy调换了位置,应该是r = cv2.pointPolygonTest(contours[i], (x, y), False)
该答案被发布为CC BY-SA 4.0下OP DrBwts使用鼠标点击轮廓但只能找到1个轮廓问题的edit

相关问题