如何使用OpenCV和Python在变量中保存鼠标位置



我使用Python和OpenCV的一些视觉应用程序。我需要在变量中保存鼠标位置,我不知道如何保存。我可以得到当前的鼠标位置打印在窗口,但不能保存到变量。

我的问题类似于这个,只有我在python中工作:OpenCV鼠标回调函数返回值

我这样定义我的函数(用于打印鼠标位置):

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

我在程序中这样使用它:

cv2.setMouseCallback('Drawing spline',mousePosition)

下面是来自: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()

将鼠标位置存储在全局变量ix,iy中。每次双击时,它都会将值更改为新位置。按a打印新值

通过存储为类成员来避免全局变量:

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 

你可以试试下面的代码:

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

相关内容

  • 没有找到相关文章

最新更新