Opencv:检测鼠标在图片上点击的位置 [英] Opencv: detect mouse position clicking over a picture
问题描述
我有这个代码,我只是在其中使用 OpenCV 显示图像:
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?
推荐答案
这里是一个鼠标回调函数示例,捕获左键双击
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
这段代码有什么作用?
它将鼠标位置存储在全局变量 mouseX
&mouseY
每次在黑色窗口内双击并按下将创建的 a 键.
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
每次按下 a 按钮时都会打印当前存储的鼠标点击位置.
will print the current stored mouse click location every time you press the a button.
代码借用"来自这里.
这篇关于Opencv:检测鼠标在图片上点击的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!