python-opencv画出一点运动轨迹
时间: 2023-09-05 12:13:35 浏览: 186
可以通过以下步骤实现:
1. 导入需要的库:
```python
import cv2
import numpy as np
```
2. 创建一个窗口,读取第一帧图像并转为灰度图:
```python
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
```
3. 定义需要用到的变量:
```python
# 运动轨迹
trajectory = []
# Shi-Tomasi角点检测参数
feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)
# Lucas-Kanade光流参数
lk_params = dict(winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
# 随机颜色
color = np.random.randint(0, 255, (100, 3))
```
4. 进行主要的算法流程:
```python
while True:
# 读取并转换当前帧为灰度图
ret, frame = cap.read()
gray_next = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 计算光流
p1, st, err = cv2.calcOpticalFlowPyrLK(gray, gray_next, np.array(pts, np.float32), None, **lk_params)
# 选取好的匹配点
good_new = p1[st == 1]
good_old = pts[st == 1]
# 绘制轨迹
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
trajectory.append([a, b])
mask = cv2.line(mask, (a, b), (c, d), color[i].tolist(), 2)
frame = cv2.circle(frame, (a, b), 5, color[i].tolist(), -1)
# 把运动轨迹画在图像上,并显示
img = cv2.add(frame, mask)
cv2.imshow('frame', img)
# 更新上一帧图像及特征点位置
gray = gray_next.copy()
pts = good_new.reshape(-1, 1, 2)
# 退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
以上就是使用Python-OpenCV画出一点运动轨迹的代码实现。
阅读全文