想要讓 YOLOv8 與 OpenCV 一起快速運(yùn)行嗎?本指南切入正題,向您展示如何輕松設(shè)置、下載模型和運(yùn)行實(shí)時對象檢測。
第 1 步:設(shè)置您的環(huán)境
首先,創(chuàng)建一個虛擬環(huán)境并安裝必要的庫。
# 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庫可以毫不費(fèi)力地處理模型下載。我們將使用 yolov8n.pt(nano) 模型來實(shí)現(xiàn)速度和準(zhǔn)確性的良好平衡。
from ultralytics import YOLO
# This downloads yolov8n.pt if you don't have it
model = YOLO('yolov8n.pt')
第 3 步:編寫檢測腳本
創(chuàng)建一個名為detect_objects.py的文件并粘貼以下代碼。此腳本將從您的網(wǎng)絡(luò)攝像頭中抓取幀,運(yùn)行 YOLOv8 推理并顯示結(jié)果。
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 步:運(yùn)行腳本?
最后,從終端執(zhí)行您的腳本:
python detect_objects.py
將彈出一個窗口,顯示帶有實(shí)時對象檢測的網(wǎng)絡(luò)攝像頭源。按 'q' 關(guān)閉它。
提高性能的快速提示
- 模型大小:最快。為了提高準(zhǔn)確性,請嘗試 或 ,但預(yù)計速度會變慢。yolov8n.ptyolov8s.ptyolov8m.pt
- GPU:如果您使用 PyTorch 設(shè)置了 NVIDIA GPU 和 CUDA,則會自動使用它來進(jìn)行更快的推理。ultralytics
- 置信度:調(diào)整以更改檢測靈敏度。conf=0.5model(frame, conf=0.5)
就是這樣!您已成功使用 YOLOv8 和 OpenCV 實(shí)現(xiàn)實(shí)時對象檢測。
閱讀全文