Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencv: detect mouse position clicking over a picture

Tags:

I have this code in which I simply display an image using OpenCV:

    import numpy as np 
    import cv2

    class LoadImage:
        def loadImage(self):
            self.img=cv2.imread('photo.png')
            cv2.imshow('Test',self.img)

            self.pressedkey=cv2.waitKey(0)

            # Wait for ESC key to exit
            if self.pressedkey==27:
                cv2.destroyAllWindows()

    # Start of the main program here        
    if __name__=="__main__":
        LI=LoadImage()
        LI.loadImage()

Once the window displayed with the photo in it, I want to display on the console (terminal) the position of the mouse when I click over the picture. I have no idea how to perform this. Any help please?

like image 311
user4519127 Avatar asked Feb 04 '15 16:02

user4519127


2 Answers

Here is an example mouse callback function, that captures the left button double-click

def draw_circle(event,x,y,flags,param):
    global mouseX,mouseY
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)
        mouseX,mouseY = x,y

You then need to bind that function to a window that will capture the mouse click

img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

then, in a infinite processing loop (or whatever you want)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(20) & 0xFF
    if k == 27:
        break
    elif k == ord('a'):
        print mouseX,mouseY

What Does This Code Do?

It stores the mouse position in global variables mouseX & mouseY every time you double click inside the black window and press the a key that will be created.

elif k == ord('a'):
    print mouseX,mouseY

will print the current stored mouse click location every time you press the a button.


Code "Borrowed" from here.

like image 93
GPPK Avatar answered Sep 28 '22 08:09

GPPK


Below is my implementation:

No need to store the click position, ONLY display it:

def onMouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
       # draw circle here (etc...)
       print('x = %d, y = %d'%(x, y))
cv2.setMouseCallback('WindowName', onMouse)

If you want to use the positions in other places of your code, you can use below way to obtain the coordinates:

posList = []
def onMouse(event, x, y, flags, param):
   global posList
   if event == cv2.EVENT_LBUTTONDOWN:
        posList.append((x, y))
cv2.setMouseCallback('WindowName', onMouse)
posNp = np.array(posList)     # convert to NumPy for later use
like image 29
smh Avatar answered Sep 28 '22 08:09

smh