1.前期准备
训练好的文件best_right.pt
GUCEE谷客HD98摄像头
conda环境配置好yolov8环境,并且安装opencv库
2.
import cv2 # 导入OpenCV库 from ultralytics import YOLO # 导入YOLO模型 import time # 导入时间模块 # 使用已经训练好的YOLO模型'best_right.pt' modle = YOLO('best_right.pt') # 打开摄像头 cap = cv2.VideoCapture(0) # 更改数字,切换不同的摄像头 while cap.isOpened(): # 循环直到摄像头关闭 success, frame = cap.read() # 读取摄像头中的帧 if success: # 如果读取成功 # 使用YOLO模型对帧进行推理 results = modle(frame) # 在帧上绘制检测结果 annotated_frame = results[0].plot() # 在窗口中显示带有检测结果的帧 cv2.imshow("YOLOv8 Inference:", annotated_frame) # 检查按键是否为 'q',若是则退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break else: # 如果读取失败 break # 退出循环 cap.release() # 释放摄像头资源 cv2.destroyAllWindows() # 关闭所有OpenCV窗口
3.效果