Search code examples
pythonopencvclickcoordinates

Click image 1 time, get position and destroy window OpenCv


Is there a simple way to open an image using OpenCv, and keep it open until it is clicked, then return the pixel coordinate and destroy the image, almost like using WaitKey() just with a return, and click as trigger?


Solution

  • This should do what you want:

    #!/usr/bin/env python3
    
    import cv2
    import numpy as np
    
    def onClick(event,x,y,flags,param):
        """Called whenever user left clicks"""
        global Running
        if event == cv2.EVENT_LBUTTONDOWN:
            print(f'I saw you click at {x},{y}')
            Running = False
    
    # Create window
    wname = "Funky Image"
    cv2.namedWindow(winname=wname)
    cv2.setMouseCallback(wname, onClick)
    
    # Load an image
    img = cv2.imread('image.jpg')
    
    Running = True
    while Running:
    
        cv2.imshow(wname,img)
        cv2.waitKey(1)
    
    cv2.destroyAllWindows()