yolov8 区域计数
- 1. 基础
- 2. 计数功能
- 2.1 计数模块
- 2.2 判断模块
- 3. 主代码
- 4. 实验结果
- 5. 源码
1. 基础
本项目是在 Windows+YOLOV8环境配置 的基础上实现的,测距原理可见上边文章
2. 计数功能
2.1 计数模块
在指定区域内计数模块
def count_objects_in_region(boxes, region_points):"""在指定区域内计数物体"""count = 0for box in boxes:x_center, y_center, width, height = boxcenter_point = (int(x_center), int(y_center))if is_inside_region(center_point, region_points):count += 1return count
2.2 判断模块
def is_inside_region(point, region_points):"""判断点是否在指定区域内"""return cv2.pointPolygonTest(np.array(region_points), point, False) >= 0
3. 主代码
import cv2
import numpy as np
from ultralytics import YOLOdef is_inside_region(point, region_points):"""判断点是否在指定区域内"""return cv2.pointPolygonTest(np.array(region_points), point, False) >= 0def count_objects_in_region(boxes, region_points):"""在指定区域内计数物体"""count = 0for box in boxes:x_center, y_center, width, height = boxcenter_point = (int(x_center), int(y_center))if is_inside_region(center_point, region_points):count += 1return countdef detect():model = YOLO("yolov8n.pt")cv2.namedWindow('Speed Estimation', cv2.WINDOW_NORMAL)cv2.resizeWindow('Speed Estimation', 1280, 360) # 设置宽高cap = cv2.VideoCapture('ultralytics/assets/a3.mp4')out_video = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), 30, (2560, 720))region_points = [(20, 20), (20, 600), (1200, 600), (1200, 20)]region_points_np = np.array(region_points)assert cap.isOpened(), "Error reading video file"while cap.isOpened():success, im0 = cap.read()if not success:print("Video frame is empty or video processing has been successfully completed.")breaktracks = model.track(im0, persist=True,classes=[2])annotated_frame = tracks[0].plot()boxes = tracks[0].boxes.xywh.cpu()object_count = count_objects_in_region(boxes, region_points)cv2.polylines(annotated_frame, [region_points_np], isClosed=True, color=(255, 0, 0), thickness=2)print(object_count)cv2.imshow("Speed Estimation", annotated_frame)out_video.write(annotated_frame)if cv2.waitKey(1) == ord('q'):breakout_video.release()cap.release()cv2.destroyAllWindows()
if __name__ == '__main__':detect()
4. 实验结果
本实验现在仅设置计数某一种类别的数目,对于多类别的计数后续会更新
5. 源码
可以去 Windows+YOLOV8环境配置 下载源码,然后把上边主代码贴进去运行即可