鼠标事件类型 OpenCV 支持多种鼠标事件类型,常见的包括:
cv2.EVENT_LBUTTONDOWN:左键按下
cv2.EVENT_RBUTTONDOWN:右键按下
cv2.EVENT_MBUTTONDOWN:中键按下
cv2.EVENT_LBUTTONUP:左键释放
cv2.EVENT_RBUTTONUP:右键释放
cv2.EVENT_MBUTTONUP:中键释放
cv2.EVENT_MOUSEMOVE:鼠标移动
cv2.EVENT_LBUTTONDBLCLK:左键双击
cv2.EVENT_RBUTTONDBLCLK:右键双击
cv2.EVENT_MBUTTONDBLCLK:中键双击
代码
实现点击鼠标左键不放移动可以画图,点击c键盘去掉恢复
import cv2
import numpy as np# 定义全局变量
drawing = False
ix, iy = -1, -1# 定义鼠标回调函数
def mouse_callback(event, x, y, flags, param):global drawing, ix, iyif event == cv2.EVENT_LBUTTONDOWN:drawing = Trueix, iy = x, yelif event == cv2.EVENT_MOUSEMOVE:if drawing:cv2.line(img, (ix, iy), (x, y), (0, 123, 255), 2) # 使用 BGR 颜色格式,红色为 (0, 0, 255)ix, iy = x, yelif event == cv2.EVENT_LBUTTONUP:drawing = Falsecv2.line(img, (ix, iy), (x, y), (0, 133, 255), 2) # 使用 BGR 颜色格式,红色为 (0, 0, 255)# 创建一个纯白底图
img = np.ones((512, 512, 3), np.uint8) * 255 # 创建一个纯白图像# 创建一个窗口
cv2.namedWindow('Image')# 设置鼠标回调函数
cv2.setMouseCallback('Image', mouse_callback)# 显示图像并等待用户交互
while True:cv2.imshow('Image', img)key = cv2.waitKey(1) & 0xFFif key == 27: # 按下 ESC 键退出breakelif key == ord('c'): # 'c'键清除画布img = np.ones((480, 640, 3), dtype=np.uint8) * 255# 保存图像
cv2.imwrite('output_image.jpg', img)cv2.destroyAllWindows()