如何使用 OpenCV 和 Python 将鼠标位置保存在变量中? [英] How to save mouse position in variable using OpenCV and Python?

查看:47
本文介绍了如何使用 OpenCV 和 Python 将鼠标位置保存在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Python 和 OpenCV 用于某些视觉应用程序.我需要将鼠标位置保存在变量中,但我不知道如何.我可以获取当前鼠标位置在窗口中打印,但不能将其保存到变量中.

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.

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

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)

推荐答案

下面是一个小的修改版本的代码: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html#mouse-handling

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

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

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.

这篇关于如何使用 OpenCV 和 Python 将鼠标位置保存在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆