Python openCV目标跟踪
时间: 2023-06-23 14:09:15 浏览: 124
OpenCV是一个开源计算机视觉库,可以处理图像和视频数据。在OpenCV中实现目标跟踪可以使用光流法和卡尔曼滤波器等算法,但最常用的算法是基于背景减法的方法。
背景减法的基本思想是先对视频帧中的背景进行建模,然后将当前帧和背景模型进行比较,从而得出前景物体的位置信息。下面是一个简单的基于背景减法的目标跟踪示例:
```python
import cv2
# 读取视频
cap = cv2.VideoCapture('test.mp4')
# 定义背景减法器
backSub = cv2.createBackgroundSubtractorMOG2()
while True:
# 读取视频帧
ret, frame = cap.read()
# 背景减法
fgMask = backSub.apply(frame)
# 消除噪声
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel)
# 寻找轮廓
contours, hierarchy = cv2.findContours(fgMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制矩形框
for c in contours:
x, y, w, h = cv2.boundingRect(c)
if w > 50 and h > 50:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('frame', frame)
cv2.imshow('mask', fgMask)
# 按下q键退出
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
上述代码中,使用`cv2.createBackgroundSubtractorMOG2()`函数创建了一个背景减法器,然后在每个视频帧中调用该背景减法器的`apply()`方法,得到前景掩码。接着,通过腐蚀和膨胀等形态学操作消除噪声,并使用`cv2.findContours()`函数寻找前景物体的轮廓。最后,通过`cv2.rectangle()`函数绘制矩形框来标注前景物体的位置。
这只是一个简单的示例,实际应用中可能需要采用更复杂的方法来提高目标跟踪的准确性和鲁棒性。
阅读全文
相关推荐


















