鼠标事件:
首先创建一个鼠标回调函数,当鼠标事件发生时触发执行。鼠标事件可以是与鼠标相关的任何事,如left-button down, left-button up, left-button double-click等对每个鼠标事件,它都会给出发生时坐标(x,y)。有了这些事件和坐标,可以通过鼠标对图像进行各种处理。
列出所有的可行事件
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']
'''
创建鼠标回调函数有特定格式,不同的回调函数只有功能不同。
示例一:下列假设我们的鼠标事件双击时是画个圆,且显示出位置坐标。
# -*- coding: utf-8 -*-
import cv2
import numpy as np
# mouse callback function
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img, (x,y), 10, (200,230,180,0.1),-1)
cv2.putText(img, '(' + str(x) + ',' + str(y) + ')',org=(x+10,y+10),fontFace=cv2.FONT_HERSHEY_SIMPLEX,fontScale=0.3,color=(0,0,255))
# create a image, a window and bing the function to window
img = cv2.imread('../image/girl001.png')
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.setMouseCallback('image', draw_circle)
while True:
cv2.imshow('image', img)
if cv2.waitKey(30) & 0xFF == 27:
break
cv2.destroyAllWindows()
示例而:拖动鼠标画图
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 drawing(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing is True:
if mode is 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
if mode is True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
img = cv2.imread('../image/girl001.png')
cv2.namedWindow('image')
cv2.setMouseCallback('image',drawing)
while True:
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()