点击下方“深度学习爱好者”,选择加"星标"或“置顶”
conda create -n person-tracker python==3.10
conda activate person-tracker
pip install ultralytics
from ultralytics import YOLO
from datetime import datetime
import os
class PersonTracker:
def __init__(self, model_path, result_dir='results/', tracker_config="bytetrack.yaml", conf=0.5, device='cuda:0',
iou=0.5, img_size=(720, 1080)):
self.model = YOLO(model_path)
self.result_dir = result_dir
self.tracker_config = tracker_config
self.conf = conf
self.device = device
self.iou = iou
self.img_size = img_size
def create_result_file(self):
folder_name = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
result_file_path = os.path.join(self.result_dir, folder_name + ".txt")
os.makedirs(self.result_dir, exist_ok=True)
with open(result_file_path, 'w') as file:
file.write(folder_name + "\n")
return result_file_path
def detect_and_track(self, source, show=True, logger=None):
result_file = self.create_result_file()
person_count = 0
previous_person_count = 0
results = self.model.track(
source, show=show, stream=True, tracker=self.tracker_config, conf=self.conf,
device=self.device, iou=self.iou, stream_buffer=True, classes=[0], imgsz=self.img_size
)
for i, result in enumerate(results):
boxes = result.boxes
try:
id_count = boxes.id.int().tolist()
max_id = max(id_count)
if max_id > person_count:
person_count = max_id
if person_count != previous_person_count:
previous_person_count = person_count
with open(result_file, 'a') as filewrite:
filewrite.write(f"Person count: {person_count}\n")
if logger:
logger.info(f"Person count: {person_count}")
except Exception as e:
pass
if __name__ == '__main__':
source = "path/to/your/video.mp4"
tracker = PersonTracker(model_path='path/to/yolov8_model.pt')
tracker.detect_and_track(source=source)
if __name__ == '__main__':
source = 0 # Use 0 for the default webcam
tracker = PersonTracker(model_path='path/to/yolov8_model.pt')
tracker.detect_and_track(source=source)
if __name__ == '__main__':
source = 'rtsp://username:password@ip_address:port/path'
tracker = PersonTracker(model_path='path/to/yolov8_model.pt')
tracker.detect_and_track(source=source)
下载1:Pytoch常用函数手册 在「深度学习爱好者」公众号后台回复:Pytorch常用函数手册,即可下载全网第一份Pytorch常用函数手册,涵盖Tensors介绍、基础函数介绍、数据处理函数、优化函数、CUDA编程、多线程处理等十四章章内容。 下载2:Python视觉实战项目52讲 在「小白学视觉」公众号后台回复:Python视觉实战项目,即可下载包括图像分割、口罩检测、车道线检测、车辆计数、添加眼线、车牌识别、字符识别、情绪检测、文本内容提取、面部识别等31个视觉实战项目,助力快速学校计算机视觉。 交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~