如何获取目标进出计数?代码打印结果为None但界面可显示数值
解决目标进出计数获取问题
你的问题出在对LineZoneAnnotator.annotate方法的理解上:这个方法的作用是在传入的帧上绘制计数文本,它的返回值是None,所以你打印line_counter得到的是None。而真正的进出计数数据,是保存在你初始化的line_zone实例中的。
修改方案
把打印line_counter的代码,替换为直接访问line_zone的in_count和out_count属性:
# 替换原来的 print(line_counter) print(f"进入数量: {line_zone.in_count}, 离开数量: {line_zone.out_count}")
完整修改后的核心代码片段
for result in results: frame = result.orig_img detections = sv.Detections.from_yolov8(result) if result.boxes is not None and result.boxes.id is not None: detections.tracker_id = result.boxes.id.cpu().numpy().astype(int) detections = detections[detections.class_id != 0] labels = [ f"#{detection[3]} {model.names[detection[2]]} {detection[1]: 0.2f}" for detection in detections ] frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels) line_zone.trigger(detections=detections) # 这里只需要调用annotate绘制,不需要接收返回值 line_annotator.annotate(frame=frame, line_counter=line_zone) # 直接从line_zone获取计数 print(f"进入: {line_zone.in_count}, 离开: {line_zone.out_count}") cv2.imshow("yolov8", frame) if (cv2.waitKey(30) == 27): break
原理说明
LineZone类负责跟踪和统计目标穿越线条的数量,in_count是从线条一侧到另一侧的进入数,out_count是反向的离开数。LineZoneAnnotator类只负责可视化,把line_zone中的计数绘制到帧上,不会返回计数数据。
后续要把计数存入数据库时,直接读取line_zone.in_count和line_zone.out_count的值即可。
内容的提问来源于stack exchange,提问作者Daljit Singh
相关产品推荐
相关产品推荐

