Ask Your Question
1

Clicking contours with mouse but only 1 contour can be found? [closed]

asked 2020-10-22 10:38:54 -0600

Dr Bwts gravatar image

updated 2020-10-22 11:34:27 -0600

I need the user to select inside the contours with a mouse, in a given image, in a specific order (this is to do with another part of the overall code).

The code (below) correctly identifies 9 contours. The problem is that the only contour the code sees when the mouse is clicked is the top left dot, number 8 (see image below) & no matter what other contour is clicked within, they will be ignored.

So what's up here?

The test image for the code, although black & white, is a 3 channel jpg,

image description

Displayed window,

image description

My code,

import cv2

def mouse_call_back(event, x, y, flags, param):  
    if event == 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()
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by supra56
close date 2020-10-22 23:19:27.750588

1 answer

Sort by ยป oldest newest most voted
2

answered 2020-10-22 11:43:22 -0600

you need to change (y, x) to (x, y)

r = cv2.pointPolygonTest(contours[i], (y, x), False)

to

r = cv2.pointPolygonTest(contours[i], (x, y), False)
edit flag offensive delete link more

Comments

1

Awwww yes, thankyou that has been bugging me all day!

Dr Bwts gravatar imageDr Bwts ( 2020-10-22 12:42:00 -0600 )edit

It had tested by me.

supra56 gravatar imagesupra56 ( 2020-10-22 23:20:18 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-10-22 10:38:54 -0600

Seen: 942 times

Last updated: Oct 22 '20