opencv mouse callback isn't being triggered

Viewed 856

Take a look at this function:

def showImage(im):
    def printColor(event, x, y, flag, params):
        if event == cv2.EVENT_LBUTTONDOWN:
            print(im[x,y])
            sys.exit(1)

    tag = "image"
    cv2.setMouseCallback(tag, printColor)
    cv2.imshow(tag, im)
    while True:
        if 'q' == chr(cv2.waitKey() & 255):
            cv2.destroyAllWindows()
            break

It's supposed to display an image and print the pixel at mouse position when clicked. But for some reason the callback isn't being triggered. How can I get this code working?

1 Answers

For setMouseCallback to work you will need to create window object first.

This can be done either by calling imshow before setting mouse callback, or by creating it with cv2.namedWindow()

Related