git:https://github.com/linyi0604/Computer-Vision
1 # coding:utf8
2
3 import cv2
4
5
6 """
7 在窗口显示摄像头帧
8
9 namedWindow() 指定窗口名
10 imshow() 创建窗口
11 DestroyWindow() 销毁所有窗口
12 waitKey() 获取键盘输入
13 setMouseCallback() 获取鼠标输入
14
15 """
16 """
17 opencv窗口只有调用waitKey()后才能实时更新
18 waitKey() 只有窗口创建后才能捕获键盘
19 """
20
21 clicked = False
22
23
24 def onMouse(event, x, y, flags, param):
25 global clicked
26 if event == cv2.EVENT_LBUTTONUP:
27 clicked = True
28
29
30 cameraCapture = cv2.VideoCapture(0) # 传入摄像头设备的索引
31 cv2.namedWindow("MyWindow") # 设置窗口名称
32 cv2.setMouseCallback("MyWindow", onMouse) # 传入窗口名称和响应捕获的函数
33 """
34 setMouseCallback() 第二个参数接收一个回调函数
35 回调事件可以取值如下:
36 cv2.EVENT_MOUSEMOVE 鼠标移动
37 cv2.EVENT_LBUTTONDOWN 左按键按下
38 cv2.EVENT_RBUTTONDOWN 右按键按下
39 cv2.EVENT_MBUTTONDOWN 中间键按下
40 cv2.EVENT_LBUTTONDBLCLK 双击左键
41 cv2.EVENT_RBUTTONDBLCLK 双击右键
42 cv2.EVENT_MBUTTONDBLCLK 双击中间
43
44 鼠标回调的标志参数可能是以下事件的桉位组合:
45 cv2.EVENT_FLAG_LBUTTON 按下鼠标左键
46 cv2.EVENT_FLAG_RBUTTON 按下鼠标右键
47 cv2.EVENT_FLAG_MBUTTON 按下中间
48 cv2.EVENT_FLAG_CTRLKEY 按下ctrl键
49 cv2.EVENT_FLAG_SHITKEY 按下shift键
50 cv2.EVENT_FLAG_ALTKEY 按下alt键
51 """
52
53 print("点击窗口或者按键停止")
54
55 success, frame = cameraCapture.read()
56 while success and cv2.waitKey(1) == -1 and not clicked:
57 cv2.imshow("MyWindow", frame)
58 success, frame = cameraCapture.read()
59
60 cv2.destroyAllWindows()
61 cameraCapture.release()