【问题标题】:Opencv: detect mouse position clicking over a pictureOpencv:检测鼠标点击图片的位置
【发布时间】:2015-04-04 07:23:30
【问题描述】:

我有这段代码,我只是在其中使用 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()

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

【问题讨论】:

  • @berak 这不是同一个问题,我是 python 和 opencv 的初学者
  • 再去那里,打印出所有值,然后看看..

标签: python-2.7 opencv mouse


【解决方案1】:

如果有人想要一个基于多进程的 GUI 来绘制点并拖动以移动它们,这里有一个 single file script

【讨论】:

    【解决方案2】:

    下面是我的实现:

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

    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
    

    【讨论】:

      【解决方案3】:

      如果您想通过在 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)
      

      【讨论】:

        【解决方案4】:

        这里是一个鼠标回调函数示例,捕获左键双击

        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)
        

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

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

        这段代码有什么作用?

        它将鼠标位置存储在全局变量mouseXmouseY中,每次在黑色窗口内双击并按a键将被创建。

        elif k == ord('a'):
            print mouseX,mouseY
        

        每次按下 a 按钮时都会打印当前存储的鼠标点击位置。


        代码“借用”here.

        【讨论】:

        • @MasoudPourbozorg 按退出键
        • 还有@MasoudPourbozorg 我提供了一个指向我从中获取代码的源的链接,因为它为我的答案提供了更多额外的细节,以及原始代码作者的归属以及细节,例如任何潜在的许可问题。
        • @GPPK 感谢您提供链接,但我无法打开它。因此,我建议更新链接或完全删除它。请检查源链接。
        • 在第一个代码块中,在global mouseX,mouseY 行中,您可能还想添加img。否则您将无法将其传递给cv2.circle(img,(x,y),100,(255,0,0),-1)
        • 这真的很有帮助。建议编辑:双击图片,按字母a,系统会打印鼠标坐标。
        【解决方案5】:

        这是基于类的 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)
        

        【讨论】:

          【解决方案6】:

          您可以通过执行各种鼠标点击事件来检测鼠标点击图片的位置。

          在执行鼠标点击事件时,您只需记住一件事,无论您使用 cv2.imshowcv2,您都必须在所有位置使用相同的窗口名称.namedWindow

          我在下面的stackoverflow帖子中给出了使用python 3.x和opencv的工作代码: https://stackoverflow.com/a/60445099/11493115

          您可以参考上面的链接以获得更好的解释。

          代码:

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

          【讨论】:

            【解决方案7】:
            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)
            

            【讨论】:

            • 欢迎来到 SO。除了您共享的代码之外,请您解释为什么这是答案。
            【解决方案8】:

            我已将 PyIgnition 库从 Pygame 移植到 opencv2。在https://github.com/bunkahle/particlescv2 找到代码 还有几个例子介绍了如何使用 Python 的粒子引擎。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-06-13
              • 1970-01-01
              • 1970-01-01
              • 2018-11-06
              • 2011-11-08
              • 2020-04-18
              • 2014-10-19
              • 2021-09-06
              相关资源
              最近更新 更多