yolov8+deepsort实现目标跟踪
一、yolov8训练行人数据集
使用官方提供的项目代码和widerperon数据集
二、deepsort进行跟踪
将deep_sort_pytorch项目文件添加到yolov8项目根目录中,添加训练权重文件,测试视频等,创建detect.py文件对行人视频进行跟踪
部分代码如下:
def process_frame(frame):
results = model(frame)
bbox_xyxy = []
confidences = []
oids = []
for result in results:
boxes = result.boxes.xyxy.cpu().numpy()
scores = result.boxes.conf.cpu().numpy()
classes = result.boxes.cls.cpu().numpy()
bbox_xyxy.extend(boxes)
confidences.extend(scores)
oids.extend(classes)
names = ['person']
# Placeholder for the detection results
bbox_xyxy = np.array(bbox_xyxy)
confidences = np.array(confidences)
oids = np.array(oids)
xywh_bboxs = [xyxy_to_xywh(*bbox) for bbox in bbox_xyxy]
xywh_bboxs = np.array(xywh_bboxs)
detections = deepsort.update(xywh_bboxs, confidences, oids, frame)
if len(detections) > 0:
bbox_xyxy = detections[:, :4]
identities = detections[:, -2]
object_id = detections[:, -1]
frame = draw_boxes(frame, bbox_xyxy, names, object_id, identities)
return frame
def main(video_source):
init_tracker()
cap = cv2.VideoCapture(video_source)
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Define the codec and create VideoWriter object
out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (width, height))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame = process_frame(frame)
out.write(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
model = YOLO('./runs/train/weights/best.pt')
video_source = 'datasets/people.mp4'
main(video_source)
参考:https://github.com/MuhammadMoinFaisal/YOLOv8-DeepSORT-Object-Tracking