OpenCV杂谈_08
一. 需要做的前期准备
- 环境配置:
Python版本:3.9.0
功能包:opencv-python(4.5.2.52)、math(自带)
- 一段提前录制好的用于物体检测、追踪的视频(要求:摄像头是保持静止不动的)
- 一个用的顺手的IDE(本人推荐Pycharm)
二. 源码如下
- main.py 文件
import cv2
from tracker import *
tracker = EuclideanDistTracker()
cap = cv2.VideoCapture("highway.mp4")
object_detector = cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=40)
while True:
ret, frame = cap.read()
height, width, _ =frame.shape
print(height, width)
roi = frame[340: 720, 500: 800]
mask = object_detector.apply(roi)
_, mask = cv2.threshold(mask, 254, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
detections = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100:
x, y, w, h = cv2.boundingRect(cnt)
detections.append([x, y, w, h])
boxer_ids = tracker.update(detections)
for box_id in boxer_ids:
x, y, w, h, id = box_id
cv2.putText(roi, "Obj" + str(id), (x, y - 15), cv2.FONT_ITALIC, 0.7, (255, 0, 0), 2)
cv2.rectangle(roi, (x, y), (x + w, y + h), (0, 255, 0), 2)
print(detections)
cv2.imshow("Frame", frame)
key = cv2.waitKey(30)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
- tracker.py文件
import math
class EuclideanDistTracker:
def __init__(self):
self.center_points = {
}
self.id_count = 0
def update(self, objects_rect):
objects_bbs_ids = []
for rect in objects_rect:
x, y, w, h = rect
cx = (x + x + w) // 2
cy = (y + y + h) // 2
same_object_detected = False
for id, pt in self.center_points.items():
dist = math.hypot(cx - pt[0], cy - pt[1])
if dist < 25:
self.center_points[id] = (cx, cy)
print(self.center_points)
objects_bbs_ids.append([x, y, w, h, id])
same_object_detected = True
break
if same_object_detected is False:
self.center_points[self.id_count] = (cx, cy)
objects_bbs_ids.append([x, y, w, h, self.id_count])
self.id_count += 1
new_center_points = {
}
for obj_bb_id in objects_bbs_ids:
_, _, _, _, object_id = obj_bb_id
center = self.center_points[object_id]
new_center_points[object_id] = center
self.center_points = new_center_points.copy()
return objects_bbs_ids
三. 结果展示
四. 感悟与分享
- 可以看出来由于物体的检测方法是根据视频中谁在运动而进行挑选的,因此在准确度上有些许问题且无法获得物体的分类信息,而且为了减少计算量而设置了ROI区域,而并非是全画面的物体检测与追踪。未来如果想实现相对高精度的检测与追踪,则需要调用Cascade文件来进行物体检测,从而实现较高精度的且附带分类信息的识别、追踪结果。
- 参考课程及推荐:https://www.youtube.com/watch?v=O3b8lVF93jU(内容为英文,且需要)
如有问题,敬请指正。欢迎转载,但请注明出处。