Python 2.7 Opencv:检测鼠标在图片上单击的位置
我有一段代码,其中我使用OpenCV简单地显示了一幅图像:Python 2.7 Opencv:检测鼠标在图片上单击的位置,python-2.7,opencv,mouse,Python 2.7,Opencv,Mouse,我有一段代码,其中我使用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)
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()
当窗口显示有照片时,我想在控制台(终端)上显示鼠标单击图片时的位置。我不知道该怎么做。有什么帮助吗?这里是一个鼠标回调函数示例,它捕获了左键双击
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
然后需要将该函数绑定到一个窗口,该窗口将捕获鼠标单击
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
然后,在一个无限处理循环中(或任何您想要的)
此代码的作用是什么?
每当您在黑色窗口内双击并按下将创建的a键时,它将鼠标位置存储在全局变量mouseX
&mouseY
elif k == ord('a'):
print mouseX,mouseY
将在每次按下a按钮时打印当前存储的鼠标单击位置
下面的代码“借用”是我的实现: 无需存储点击位置,只需显示:
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)
如果要使用代码中其他位置的位置,可以使用以下方法获取坐标:
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
我已经将PyIgnition库从Pygame移植到opencv2。在以下位置查找代码:
还有几个关于如何使用Python粒子引擎的示例。您可以通过执行各种鼠标单击事件来检测鼠标在图片上的位置
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)
在执行鼠标单击事件时,您只需记住一件事,即无论您在哪里使用cv2.imshow或cv2.namedWindow
我在下面的stackoverflow文章中给出了使用python 3.x和opencv的工作代码:
您可以参考上面的链接以获得更好的解释
代码:
import cv2
import numpy as np
#This will display all the available mouse click events
events = [i for i in dir(cv2) if 'EVENT' in i]
print(events)
#This variable we use to store the pixel location
refPt = []
#click event function
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print(x,",",y)
refPt.append([x,y])
font = cv2.FONT_HERSHEY_SIMPLEX
strXY = str(x)+", "+str(y)
cv2.putText(img, strXY, (x,y), font, 0.5, (255,255,0), 2)
cv2.imshow("image", img)
if event == cv2.EVENT_RBUTTONDOWN:
blue = img[y, x, 0]
green = img[y, x, 1]
red = img[y, x, 2]
font = cv2.FONT_HERSHEY_SIMPLEX
strBGR = str(blue)+", "+str(green)+","+str(red)
cv2.putText(img, strBGR, (x,y), font, 0.5, (0,255,255), 2)
cv2.imshow("image", img)
#Here, you need to change the image name and it's path according to your directory
img = cv2.imread("D:/pictures/abc.jpg")
cv2.imshow("image", img)
#calling the mouse click event
cv2.setMouseCallback("image", click_event)
cv2.waitKey(0)
cv2.destroyAllWindows()
下面是OpenCV鼠标回调的基于类的实现,用于获取图像上的点
import cv2
import numpy as np
#events = [i for i in dir(cv2) if 'EVENT' in i]
#print (events)
class MousePts:
def __init__(self,windowname,img):
self.windowname = windowname
self.img1 = img.copy()
self.img = self.img1.copy()
cv2.namedWindow(windowname,cv2.WINDOW_NORMAL)
cv2.imshow(windowname,img)
self.curr_pt = []
self.point = []
def select_point(self,event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
self.point.append([x,y])
#print(self.point)
cv2.circle(self.img,(x,y),5,(0,255,0),-1)
elif event == cv2.EVENT_MOUSEMOVE:
self.curr_pt = [x,y]
#print(self.point)
def getpt(self,count=1,img=None):
if img is not None:
self.img = img
else:
self.img = self.img1.copy()
cv2.namedWindow(self.windowname,cv2.WINDOW_NORMAL)
cv2.imshow(self.windowname,self.img)
cv2.setMouseCallback(self.windowname,self.select_point)
self.point = []
while(1):
cv2.imshow(self.windowname,self.img)
k = cv2.waitKey(20) & 0xFF
if k == 27 or len(self.point)>=count:
break
#print(self.point)
cv2.setMouseCallback(self.windowname, lambda *args : None)
#cv2.destroyAllWindows()
return self.point, self.img
if __name__=='__main__':
img = np.zeros((512,512,3), np.uint8)
windowname = 'image'
coordinateStore = MousePts(windowname,img)
pts,img = coordinateStore.getpt(3)
print(pts)
pts,img = coordinateStore.getpt(3,img)
print(pts)
cv2.imshow(windowname,img)
cv2.waitKey(0)
如果您想在Python 3中通过将鼠标悬停在图像上获得坐标,可以尝试以下方法:
import numpy as np
import cv2 as cv
import os
import sys
# Reduce the size of image by this number to show completely in screen
descalingFactor = 2
# mouse callback function, which will print the coordinates in console
def print_coord(event,x,y,flags,param):
if event == cv.EVENT_MOUSEMOVE:
print(f'{x*descalingFactor, y*descalingFactor}\r', end="")
img = cv.imread(cv.samples.findFile('TestImage.png'))
imgheight, imgwidth = img.shape[:2]
resizedImg = cv.resize(img,(int(imgwidth/descalingFactor), int(imgheight/descalingFactor)), interpolation = cv.INTER_AREA)
cv.namedWindow('Get Coordinates')
cv.setMouseCallback('Get Coordinates',print_coord)
cv.imshow('Get Coordinates',resizedImg)
cv.waitKey(0)
昨天你问了,现在你不知道如何实现鼠标处理程序?@berak这不是同一个问题,我是python和OpenCVI的初学者,再去那里,打印出所有的值,请参阅..@MasoudPourbozorg按escape键还有@MasoudPourbozorg我提供了一个指向我获取代码的源代码的链接,因为它为我的答案提供了更多的额外细节,以及原始代码作者的归属,以及任何潜在的许可问题等细节。@GPPK感谢提供链接,但我很抱歉无法打开它。因此,我建议更新链接或将其全部删除。请检查源代码链接。在第一个代码块的
global mouseX行中,mouseY
您可能还需要添加img
。否则您将无法将其传递给cv2.circle(img,(x,y),100,(255,0,0),-1)这非常有用。建议编辑:如果双击图像,然后按字母a
,系统将打印鼠标坐标。欢迎使用。请你解释一下为什么这是除了你分享的代码之外的答案。
import numpy as np
import cv2 as cv
import os
import sys
# Reduce the size of image by this number to show completely in screen
descalingFactor = 2
# mouse callback function, which will print the coordinates in console
def print_coord(event,x,y,flags,param):
if event == cv.EVENT_MOUSEMOVE:
print(f'{x*descalingFactor, y*descalingFactor}\r', end="")
img = cv.imread(cv.samples.findFile('TestImage.png'))
imgheight, imgwidth = img.shape[:2]
resizedImg = cv.resize(img,(int(imgwidth/descalingFactor), int(imgheight/descalingFactor)), interpolation = cv.INTER_AREA)
cv.namedWindow('Get Coordinates')
cv.setMouseCallback('Get Coordinates',print_coord)
cv.imshow('Get Coordinates',resizedImg)
cv.waitKey(0)