cv2.setMouseCallback
时间: 2024-04-13 21:21:26 浏览: 118
openCV中cvSetMouseCallback的使用示例
4星 · 用户满意度95%
cv2.setMouseCallback()是OpenCV中的一个函数,用于设置鼠标回调函数。它的语法如下:
```python
cv2.setMouseCallback(windowName, onMouse, param=None)
```
其中,windowName是窗口名称,onMouse是鼠标事件的回调函数,param是传递给回调函数的可选参数。
鼠标事件包括:
- cv2.EVENT_MOUSEMOVE 鼠标移动事件
- cv2.EVENT_LBUTTONDOWN 左键按下事件
- cv2.EVENT_RBUTTONDOWN 右键按下事件
- cv2.EVENT_MBUTTONDOWN 中键按下事件
- cv2.EVENT_LBUTTONUP 左键释放事件
- cv2.EVENT_RBUTTONUP 右键释放事件
- cv2.EVENT_MBUTTONUP 中键释放事件
- cv2.EVENT_LBUTTONDBLCLK 左键双击事件
- cv2.EVENT_RBUTTONDBLCLK 右键双击事件
- cv2.EVENT_MBUTTONDBLCLK 中键双击事件
以下是一个使用cv2.setMouseCallback()函数绘制矩形的例子:
```python
import cv2
def draw_rectangle(event, x, y, flags, param):
global pt1, pt2, top_left_clicked, bottom_right_clicked
if event == cv2.EVENT_LBUTTONDOWN:
if top_left_clicked and bottom_right_clicked:
pt1 = (0, 0)
pt2 = (0, 0)
top_left_clicked = False
bottom_right_clicked = False
if not top_left_clicked:
pt1 = (x, y)
top_left_clicked = True
elif not bottom_right_clicked:
pt2 = (x, y)
bottom_right_clicked = True
if top_left_clicked and bottom_right_clicked:
cv2.rectangle(param, pt1, pt2, (0, 255, 0), 3)
pt1 = (0, 0)
pt2 = (0, 0)
top_left_clicked = False
bottom_right_clicked = False
cap = cv2.VideoCapture(0)
cv2.namedWindow('Test')
cv2.setMouseCallback('Test', draw_rectangle)
while True:
ret, frame = cap.read()
if top_left_clicked and bottom_right_clicked:
cv2.rectangle(frame, pt1, pt2, (0, 255, 0), 3)
cv2.imshow('Test', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
阅读全文