1 # Author:Winter Liu is coming! 2 import cv2 as cv 3 import numpy as np 4 5 6 # 鼠标回调函数,当发生鼠标事件,调用此函数,传递5个参数 7 def draw_demo(event, x, y, flags, params): 8 # 左键、右键、左键双击 9 # 对应圆、矩形、椭圆形 10 if event == cv.EVENT_FLAG_LBUTTON: 11 cv.circle(image, (x, y), 20, (0, 0, 255), -1) 12 elif event == cv.EVENT_FLAG_RBUTTON: 13 cv.rectangle(image, (x, y), (x+20, y+20), (0, 255, 0), 2) 14 elif event == cv.EVENT_LBUTTONDBLCLK: 15 cv.ellipse(image, (x, y), (50, 30), 45, 0, 360, (255, 0, 0), 2) 16 17 18 # 查看OpenCV中可识别事件 19 events = [i for i in dir(cv) if 'EVENT' in i] 20 for e in events: 21 print(e) 22 # 使用numpy创建纯色图形,全白(全黑) 23 image = (np.ones((512, 512, 3), np.uint8))*255 24 # image = np.zeros((512, 512, 3), np.uint8) 25 cv.namedWindow("PIC") 26 # 设置鼠标回调 27 cv.setMouseCallback('PIC', draw_demo) 28 29 while 1: 30 cv.imshow("PIC", image) 31 if cv.waitKey(20) == 27: 32 break 33 cv.destroyAllWindows()