初识OpenCV-Python - 003:Mouse as a paint-brush

Posted august2019

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初识OpenCV-Python - 003:Mouse as a paint-brush相关的知识,希望对你有一定的参考价值。

此次学习了如何在OpenCV中使用鼠标事件。主要使用cv2.setMouseCallback()函数来调用鼠标事件。

首先,鼠标有如下事件:

>>> import cv2
>>>events = [i for i in dir(cv2) if ‘EVENT‘ in i]
>>>print(events)
[‘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‘]

然后使用鼠标事件画图code:

import cv2
import numpy as np

drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press ‘m‘ to toggle to curve
ix,iy = -1,-1

# mouse callback function
def draw_circle(event,x,y,flags,param): #draw_circle函数需要5个函数,所以即使这里并没有使用到flags和param,我们还是要加上它
global ix,iy,drawing,mode

if event == cv2.EVENT_LBUTTONDOWN: #如果按下了鼠标,那么将drawing设置为True,从而开始画图
drawing = True
ix,iy = x,y

elif event == cv2.EVENT_MOUSEMOVE: #如果移动鼠标,并且鼠标是按下的状态,那么就开始画图,如果mode是True,那么画矩形,否则画圆形
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)

elif event == cv2.EVENT_LBUTTONUP: #如果释放鼠标左键,那么不是画图状态
drawing = False

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‘): #按下m改变画图类型
mode = not mode
elif k == 27: #按下Esc退出程序
break

code结果:
技术图片

 

 

以上是关于初识OpenCV-Python - 003:Mouse as a paint-brush的主要内容,如果未能解决你的问题,请参考以下文章

初识OpenCV-Python - 010: 精致边缘探测

初识OpenCV-Python - 002: Drawing functions

初识OpenCV-Python - 005: 识别视频中的蓝色

初识OpenCV-Python - 004: Trackbar as the color palette

初识OpenCV-Python - 003:Mouse as a paint-brush

[OpenCV-Python] OpenCV 中的图像处理 部分 IV (四)