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,
Displayed window,
My code,
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()