想要让 YOLOv8 与 OpenCV 一起快速运行吗?本指南切入正题,向您展示如何轻松设置、下载模型和运行实时对象检测。
第 1 步:设置您的环境
首先,创建一个虚拟环境并安装必要的库。
# Create and activate a virtual environment
python -m venv yolov8_opencv_env
# On Windows: yolov8_opencv_envScriptsactivate
# On macOS/Linux: source yolov8_opencv_env/bin/activate
# Install libraries
pip install opencv-python numpy ultralytics
第 2 步:下载 YOLOv8 模型
ultralytics库可以毫不费力地处理模型下载。我们将使用 yolov8n.pt(nano) 模型来实现速度和准确性的良好平衡。
from ultralytics import YOLO
# This downloads yolov8n.pt if you don't have it
model = YOLO('yolov8n.pt')
第 3 步:编写检测脚本
创建一个名为detect_objects.py的文件并粘贴以下代码。此脚本将从您的网络摄像头中抓取帧,运行 YOLOv8 推理并显示结果。
import cv2
from ultralytics import YOLO
import numpy as np
def main():
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Open the default webcam (0 for built-in, or specify video file path)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open video stream.")
return
class_names = model.names # Get class names (e.g., 'person', 'car')
while True:
ret, frame = cap.read()
if not ret:
print("End of stream or error reading frame.")
break
# Run YOLOv8 inference on the frame
results = model(frame, conf=0.5) # conf=0.5 means 50% confidence threshold
# Process and draw detections
for r in results:
boxes = r.boxes.xyxy.cpu().numpy()
confidences = r.boxes.conf.cpu().numpy()
class_ids = r.boxes.cls.cpu().numpy()
for box, conf, class_id in zip(boxes, confidences, class_ids):
x1, y1, x2, y2 = map(int, box)
label = f"{class_names[int(class_id)]}: {conf:.2f}"
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Green rectangle
cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Green text
cv2.imshow('YOLOv8 Object Detection', frame)
# Press 'q' to quit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
第 4 步:运行脚本
最后,从终端执行您的脚本:
python detect_objects.py
将弹出一个窗口,显示带有实时对象检测的网络摄像头源。按 'q' 关闭它。
提高性能的快速提示
- 模型大小:最快。为了提高准确性,请尝试 或 ,但预计速度会变慢。yolov8n.ptyolov8s.ptyolov8m.pt
- GPU:如果您使用 PyTorch 设置了 NVIDIA GPU 和 CUDA,则会自动使用它来进行更快的推理。ultralytics
- 置信度:调整以更改检测灵敏度。conf=0.5model(frame, conf=0.5)
就是这样!您已成功使用 YOLOv8 和 OpenCV 实现实时对象检测。
阅读全文
2643