本跟踪程序核心为OpenCV里BackgroundSubtractorMOG2()类。该类通过对当前帧和背景模板的每个像素做减法,来区分前景和背景物体。这一算法只适用于背景相对固定的情况,如固定摄像头。对于跟踪小车这种需要实时更新背景的情况不适用
1 Tacker类:标记并更新获取到的目标
import math
class EuclideanDistTracker:
def __init__(self):
# Store the center positions of the objects
self.center_points = {
}
# Keep the count of the IDs
# each time a new object id detected, the count will increase by one
self.id_count = 0
# record IDs of objects tracked
# @param: the rectangular frame that captures an object
# @return: objects boxes and ids
def update(self, objects_rect):
# Objects boxes and ids
objects_bbs_ids = []
# Get center point of new object
# time complexity O(N^2)
for rect in objects_rect:
# find the center of the object
x, y, w, h = rect
cx = (x + x + w) // 2
cy = (y + y + h) // 2
# Find out if that object was detected already
same_object_detected = False
# search the objects stored for the same object
for id, pt in self.center_points.items():
distance = math.hypot(cx - pt[0], cy - pt[1])
# if the distance between two objects detected are very close, we consider
# them to be one object
if distance < 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
# New object is detected we assign the ID to that object
if same_object_detected is False:
self.center_p