目标追踪中如何避免车辆过线时的前帧重复结果记录
解决车辆过线重复记录问题的方案
核心思路是利用ByteTrack生成的唯一跟踪ID,维护一个已计数的ID集合,确保同一辆车只被记录一次:
- 在Camera类中新增集合,存储已经完成过线计数的车辆ID
- 触发过线检测时,先检查当前车辆的跟踪ID是否已在集合中,未存在才执行记录操作
- 视频循环播放时重置集合,避免后续循环的车辆被误判为已计数
修改后的代码
第一步:添加已计数ID集合
在Camera类中新增类变量:
class Camera(BaseCamera): """ OpenCV video stream """ video_source = 0 start, end = Point(0, 500), Point(1280, 500) detector = Detector() tracker = ByteTrack() line_zone = LineZone(start=start, end=end) annotator = LineZoneAnnotator() counted_ids = set() # 新增:存储已计数的车辆跟踪ID
第二步:修改视频循环逻辑
在视频回到第一帧时,清空已计数集合:
# Loop back if not ret: camera.set(cv2.CAP_PROP_POS_FRAMES, 0) cls.counted_ids.clear() # 重置已计数ID,适配视频循环场景 continue
第三步:过滤重复过线记录
在触发过线检测时,判断跟踪ID是否已被记录:
result=cls.line_zone.trigger(detections) if result is not None and len(result)>=3: track_id = result[2] if track_id not in cls.counted_ids: # 这里替换成你的结果存储逻辑(比如写入数据库/文件) print(track_id) cls.counted_ids.add(track_id)
完整修改后的Camera类代码
class Camera(BaseCamera): """ OpenCV video stream """ video_source = 0 start, end = Point(0, 500), Point(1280, 500) detector = Detector() tracker = ByteTrack() line_zone = LineZone(start=start, end=end) annotator = LineZoneAnnotator() counted_ids = set() # 存储已计数的车辆跟踪ID def __init__(self, enable_detection: bool = False): video_source = os.environ.get("VIDEO_SOURCE") try: video_source = int(video_source) except Exception as exp: # pylint: disable=broad-except if not video_source: raise EnvironmentError("Cannot open the video source!") from exp finally: Camera.set_video_source(video_source) super().__init__() self.enable_detection = enable_detection @staticmethod def set_video_source(source): """Set video source""" Camera.video_source = source @classmethod def frames(cls): """ Get video frame """ camera = cv2.VideoCapture(Camera.video_source) if not camera.isOpened(): raise RuntimeError("Could not start camera.") while True: # read current frame ret, img = camera.read() # Loop back if not ret: camera.set(cv2.CAP_PROP_POS_FRAMES, 0) cls.counted_ids.clear() # 重置已计数ID集合 continue # Object detection results = cls.detector(image=img) selected_classes = [2, 3] tensorflow_results = results.detections cls.annotator.annotate(img, cls.line_zone) if not tensorflow_results: yield cv2.imencode(".jpg", img)[1].tobytes() continue detections = Detections.from_tensorflow(tensorflow_results=tensorflow_results) detections = cls.tracker.update_with_detections(detections=detections) detections = detections[np.isin(detections.class_id, selected_classes)] result=cls.line_zone.trigger(detections) if result is not None and len(result)>=3: track_id = result[2] if track_id not in cls.counted_ids: # 替换为你的结果存储逻辑 print(track_id) cls.counted_ids.add(track_id) img = visualize(image=img, detections=detections) # encode as a jpeg image and return it yield cv2.imencode(".jpg", img)[1].tobytes()
内容的提问来源于stack exchange,提问作者SARON RAVUTH
相关产品推荐
相关产品推荐

