个性化阅读
专注于IT技术分析

OpenCV鼠标事件

点击下载

本文概述

鼠标作为画笔

OpenCV提供了一种将鼠标用作画笔或绘图工具的工具。每当窗口屏幕上发生任何鼠标事件时, 它都可以绘制任何内容。鼠标事件可以按下鼠标左键, 按下鼠标左键, 双击等等。它为我们提供了每个鼠标事件的坐标(x, y)。通过使用这些坐标, 我们可以绘制所需的任何内容。要获取所有可用事件的列表, 请在终端中运行以下代码:

import cv2
mouse_events = [j for j in dir(cv2) if 'EVENT' in j]
print(mouse_events)

上面的代码将返回OpenCV支持的所有鼠标事件的列表。

输出

['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']

画圆

要在窗口屏幕上画一个圆, 我们首先需要使用cv2.setMouseCallback()函数创建一个鼠标回调函数。它具有一种特定格式, 在任何地方都相同。通过双击绘制一个圆, 可以方便我们的鼠标回调函数。考虑以下程序:

import cv2
import numpy as np
# Creating mouse callback function
def draw_circle(event, x, y, flags, param):
    if(event == cv2.EVENT_LBUTTONDBLCLK):
        	cv2.circle(img, (x, y), 100, (255, 255, 0), -1)
# Creating 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)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()
OpenCV鼠标事件

在上面的代码中, 我们首先创建了一个黑色窗口, 其中发生了鼠标事件。当我们双击黑色窗口时, 它将在回调draw_circle()函数中定义一个圆圈。

绘制矩形和曲线

我们可以在窗口屏幕上绘制任何形状。就像在Paint应用程序中一样, 我们通过拖动鼠标来绘制矩形或圆形(取决于我们选择的模型)。我们以创建两个部分的回调函数为例。第一部分是绘制矩形, 另一部分是绘制圆形。让我们看一下给定的示例, 以更具体的方式理解它:

import cv2
import numpy as np
draw = False # true if the mouse is pressed. Press m to shift into curve mode.
mode = True # if True, draw rectangle.
a, b = -1, -1
# mouse callback function
def draw_circle(event, x, y, flags, param):
    global a, b, draw, mode
    if(event == cv2.EVENT_LBUTTONDOWN):
        draw = True
        a, b = x, y
    elif (event == cv2.EVENT_MOUSEMOVE):
        if draw == True:
            if mode == True:
                cv2.rectangle(img, (a, b), (x, y), (0, 255, 0), -1)
            else:
                cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
    elif(event == cv2.EVENT_LBUTTONUP):
        draw = False
        if mode == True:
            cv2.rectangle(img, (a, b), (x, y), (0, 255, 0), -1)
        else:
            cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
# We bind the keyboard key m to toggle between rectangle and circle.
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(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif(k == 27):
        break
cv2.destroyAllWindows()

输出

OpenCV鼠标事件

在上面的程序中, 我们创建了两个鼠标回调函数。它与OpenCV窗口绑定。在while循环中, 我们为键” m”设置了键盘绑定, 以在矩形和曲线之间切换。


赞(0)
未经允许不得转载:srcmini » OpenCV鼠标事件

评论 抢沙发

评论前必须登录!