close

YOLOv8 從圖片到即時檢測的完整教學與比較

本篇教學將從 YOLOv8 單張圖片檢測開始,逐步擴展到多張圖片、影片檢測,最後介紹 PC CAM(網路攝影機)和 PyCamera2 模組的即時檢測應用。

---

1. 單張圖片目標檢測

以下程式碼用於檢測單張圖片中的目標,並保存帶有檢測結果的圖片。

from ultralytics import YOLO
import cv2

# 加載 YOLO 模型
model = YOLO('yolov8n.pt')  # 使用 Nano 模型(輕量快速)

# 圖片路徑
image_path = 'image.jpg'

# 推理
results = model(image_path)

# 可視化檢測結果
annotated_image = results[0].plot()

# 保存檢測結果
cv2.imwrite('detected_image.jpg', annotated_image)
print("檢測完成,結果已保存至 'detected_image.jpg'")

用途:適用於單圖片測試或模型效果驗證。

---

2. 多張圖片目標檢測

批量處理多張圖片,對每張圖片進行檢測並保存結果。

from ultralytics import YOLO
import cv2

# 加載 YOLO 模型
model = YOLO('yolov8n.pt')

# 多張圖片路徑
image_paths = ['image1.jpg', 'image2.jpg', 'image3.jpg']

# 批量處理圖片
for image_path in image_paths:
    results = model(image_path)
    annotated_image = results[0].plot()
    output_path = f'detected_{image_path}'
    cv2.imwrite(output_path, annotated_image)
    print(f"檢測完成,結果已保存至 {output_path}")

用途:適用於批量圖片資料處理,例如整個圖片資料集的檢測。

---

3. 影片目標檢測

以下程式碼用於處理整段影片,並生成包含檢測結果的新影片文件。

from ultralytics import YOLO
import cv2

# 加載 YOLO 模型
model = YOLO('yolov8n.pt')

# 影片路徑
video_path = 'input_video.mp4'
output_path = 'output_video.avi'

# 打開影片
cap = cv2.VideoCapture(video_path)

# 獲取影片資訊
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 初始化影片寫入器
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))

# 逐幀處理
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    results = model(frame)
    annotated_frame = results[0].plot()
    out.write(annotated_frame)

cap.release()
out.release()
cv2.destroyAllWindows()
print(f"影片檢測完成,結果已保存至 {output_path}")

用途:適用於分析影片內容,例如交通監控或運動分析。

---

4. PC CAM 即時目標檢測

即時使用 PC 的攝影機進行目標檢測,並在 OpenCV 視窗中顯示結果。

from ultralytics import YOLO
import cv2

# 加載 YOLO 模型
model = YOLO('yolov8n.pt')

# 開啟攝影機
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    results = model(frame)
    annotated_frame = results[0].plot()
    cv2.imshow("YOLOv8 Real-Time Detection", annotated_frame)

    # 按下 'q' 鍵退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

用途:適用於即時目標檢測,例如安全監控或互動場景。

---

5. PyCamera2 即時目標檢測

針對 Raspberry Pi 的相機模組,可使用 PyCamera2 實現即時目標偵測。

from picamera2 import Picamera2
from ultralytics import YOLO
import cv2

# 初始化 YOLO 模型
model = YOLO('yolov8n.pt')

# 初始化 PiCamera2
picam2 = Picamera2()
config = picam2.create_preview_configuration(main={"format": "RGB888", "size": (640, 480)})
picam2.configure(config)
picam2.start()

try:
    while True:
        frame = picam2.capture_array()
        results = model(frame)
        annotated_frame = results[0].plot()
        cv2.imshow("YOLOv8 Real-Time Detection", annotated_frame)

        # 按下 'q' 鍵退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

except KeyboardInterrupt:
    print("程式已中止")
finally:
    picam2.stop()
    cv2.destroyAllWindows()

用途:適用於嵌入式設備,例如智慧家庭或移動設備上的即時目標檢測。

---

6. 功能比較

功能 輸入形式 輸出形式 應用場景
單張圖片檢測 單張圖片 標註後的圖片 單圖片測試、模型驗證
多張圖片檢測 多張圖片(路徑列表) 多張標註後的圖片 批量圖片資料處理
影片檢測 影片文件 標註後的新影片 影片分析,例如交通監控
PC CAM 即時檢測 攝影機畫面 即時顯示 安全監控、互動應用
PyCamera2 即時檢測 Raspberry Pi 相機模組畫面 即時顯示 智慧家庭、嵌入式應用

---

7. 注意事項

pip install ultralytics opencv-python
  • 確保安裝 YOLOv8 和相關套件:
  • 若處理速度較慢,可降低解析度或使用輕量級模型(如 yolov8n.pt)。
  • 使用 PyCamera2 時,需確保 Raspberry Pi 已正確安裝相關驅動。

結語

本教學涵蓋從單張圖片檢測到即時目標檢測的多種應用場景,您可以根據需求選擇合適的實現方式。如果有其他問題或需要進一步指導,歡迎留言交流!

arrow
arrow
    創作者介紹
    創作者 liusming 的頭像
    liusming

    劉老師的跨域創想工坊

    liusming 發表在 痞客邦 留言(2) 人氣()