10

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, but can't save it to variable.

My problem is similar to this one only I work in python: OpenCV Return value from mouse callback function

I define my function like this (for printing mouse position):

def mousePosition(event,x,y,flags,param):
    if event == cv2.EVENT_MOUSEMOVE:
        print x,y

I use it in my program like this:

cv2.setMouseCallback('Drawing spline',mousePosition)
1
  • what is the problem? what is the output? what is your expectation ?
    – Hadi
    May 11, 2014 at 18:56

3 Answers 3

17

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 function
def draw_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) & 0xFF
    if k == 27:
        break
    elif 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.

6
  • Thank you. Haven't thought of using global variables. I thought they shouldn't be used. Does it stand for Python too?
    – page47250
    May 11, 2014 at 19:23
  • 1
    I use them whenever I absolutely need them. Never thought much about 'protocols' :) May 12, 2014 at 2:21
  • 2
    If you want to avoid globals and you write functional style Python, you can use local ix and iy variables and capture them in draw_circle in a closure by making it a local function (Python uses pass-by-reference). If you use an object-oriented style, you you can encapsulate ix and iy in a class as members and make the draw_circle a method on an instance of that class.
    – mjul
    May 12, 2014 at 21:44
  • @mjul : +1 - I think it would be really great if you could make this comment to an answer (with examples) and share it here (Personally me too like to see different approaches). Then people can select whatever approach they like. You can use the same example in my answer and show how it can be done without globals by the two methods you mentioned. May 13, 2014 at 4:35
  • why the parameters in def draw_circle(event,x,y,flags,param): are never used but the program works ?
    – user3522371
    Feb 3, 2015 at 15:57
11

Avoid global variables by storing as class members:

import cv2
import numpy as np  



class CoordinateStore:
    def __init__(self):
        self.points = []

    def select_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) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()


print "Selected Coordinates: "
for i in coordinateStore1.points:
    print i 
1
  • This is a really clever way to avoid globals, which everyone uses for these kinds of mouse callbacks in open cv. I wonder what the downside of using objects versus globals are, specifically for this kind of use case, as you scale up to more complicated projects.
    – eric
    May 15, 2020 at 15:50
3

You can try this Code:

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.