道路分割与车辆检测:
首先实例化模型,分别是分割模型和检测模型,分别使用分割数据集和visdrone数据集训练
model1 = YOLO('roadseg.pt') # 分割模型
model2 = YOLO('visdrone.pt') # 目标检测模型
接着对视频或者摄像头进行输入
video_path = "nx-fraction.mp4"
cap = cv2.VideoCapture(video_path)
success, test_frame = cap.read()
video_height, video_width = test_frame.shape[:2]
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
# 在初始化部分添加视频写入器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('seg-det.mp4', fourcc, 30.0, (video_width, video_height))
之后创建检测循环,对每一帧交替使用分割模型和检测模型,并使用yolo的绘画功能先再原始帧上绘画分割掩码,再将覆盖掩膜的图像绘画检测框。最后可视化和保存
while cap.isOpened():
success, frame = cap.read()
if not success:
break
annotated_frame=frame.copy()
results1=model1.track(source=annotated_frame,
imgsz=1280,
project='runs/track',
name='exp',
save=False,
show=False,
iou=0
, conf=0
)
results2=model2.track(source=annotated_frame,
imgsz=1280,
project='runs/track',
name='exp',
save=False,
show=False,
iou=0
, conf=0
)
# 修改后的可视化流程
annotated_frame1=results1[0].plot(
img=annotated_frame,
conf=False, # 显示置信度
boxes=True,
)
annotated_frame2=results2[0].plot(
img=annotated_frame1,
conf=False, # 显示置信度
boxes=True)
# 显示并保存处理后的帧
cv2.imshow('Tracking', annotated_frame2)
out.write(annotated_frame2) # 写入帧到视频文件
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
out.release() # 释放视频写入器
cv2.destroyAllWindows()
效果如下: