Skip to content Skip to sidebar Skip to footer

How To Save Mouse Position In Variable Using Opencv And Python?

I'm using Python and OpenCV for some vision application. I need to save mouse position in variables and I don't know how. I can get the current mouse position to print in window, b

Solution 1:

Below is a small modified version of code from : http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html#mouse-handling

import cv2
import numpy as np

ix,iy = -1,-1# mouse callback functiondefdraw_circle(event,x,y,flags,param):
    global ix,iy
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)
        ix,iy = x,y

# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(20) & 0xFFif k == 27:
        breakelif k == ord('a'):
        print ix,iy
cv2.destroyAllWindows()

It stores the mouse position in global variables ix,iy. Every time you double-click, it changes the value to new location. Press a to print the new value.

Solution 2:

Avoid global variables by storing as class members:

import cv2
import numpy as np  



classCoordinateStore:
    def__init__(self):
        self.points = []

    defselect_point(self,event,x,y,flags,param):
            if event == cv2.EVENT_LBUTTONDBLCLK:
                cv2.circle(img,(x,y),3,(255,0,0),-1)
                self.points.append((x,y))


#instantiate class
coordinateStore1 = CoordinateStore()


# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',coordinateStore1.select_point)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(20) & 0xFFif k == 27:
        break
cv2.destroyAllWindows()


print"Selected Coordinates: "for i in coordinateStore1.points:
    print i 

Solution 3:

You can try this Code:

def mousePosition(event,x,y,flags,param):

    ifevent == cv2.EVENT_MOUSEMOVE:
        print x,y
        param = (x,y)

cv2.setMouseCallback('Drawing spline',mousePosition,param)

Post a Comment for "How To Save Mouse Position In Variable Using Opencv And Python?"