Simen Morken
Simen Morken

Reputation: 35

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?

Upvotes: 1

Views: 1230

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207530

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()

Upvotes: 4

Related Questions