OpenCV:检测鼠标点击图片的位置

use*_*127 3 mouse opencv python-2.7

我有以下代码,其中仅使用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()
Run Code Online (Sandbox Code Playgroud)

当窗口中显示照片后,我想在控制台(终端)上单击图片时显示鼠标的位置。我不知道如何执行此操作。有什么帮助吗?

GPP*_*PPK 11

这是鼠标回调函数的示例,该函数捕获双击的左键

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
Run Code Online (Sandbox Code Playgroud)

然后,您需要将该功能绑定到捕获鼠标单击的窗口

img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
Run Code Online (Sandbox Code Playgroud)

然后,在无限的处理循环中(或任何您想要的)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(20) & 0xFF
    if k == 27:
        break
    elif k == ord('a'):
        print mouseX,mouseY
Run Code Online (Sandbox Code Playgroud)

该代码的作用是什么?

它将鼠标位置存储在全局变量中mouseX,并且mouseY每次在将要创建的黑色窗口中双击时。

elif k == ord('a'):
    print mouseX,mouseY
Run Code Online (Sandbox Code Playgroud)

每次按a按钮将打印当前存储的鼠标单击位置。


这里输入代码“借来的”


smh*_*smh 7

下面是我的实现:

无需存储点击位置,只显示它:

def onMouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
       # draw circle here (etc...)
       print('x = %d, y = %d'%(x, y))
cv2.setMouseCallback('WindowName', onMouse)
Run Code Online (Sandbox Code Playgroud)

如果您想使用代码其他地方的位置,您可以使用以下方式获取坐标:

posList = []
def onMouse(event, x, y, flags, param):
   global posList
   if event == cv2.EVENT_LBUTTONDOWN:
        posList.append((x, y))
cv2.setMouseCallback('WindowName', onMouse)
posNp = np.array(posList)     # convert to NumPy for later use
Run Code Online (Sandbox Code Playgroud)


小智 5

import cv2

cv2.imshow("image", img)
cv2.namedWindow('image')
cv2.setMouseCallback('image', on_click)

def on_click(event, x, y, p1, p2):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(lastImage, (x, y), 3, (255, 0, 0), -1)
Run Code Online (Sandbox Code Playgroud)