Posted on

YOLOv8使用範例

建模的範例

先用下面指令安裝好所需的套件

pip install ultralytics

然後在Roloflow下載要訓練的素材集,選擇YOLOv8

把裡面的資料(含data.yaml)解壓縮在同層資料夾下,如圖

接著直接執行下面的程式,yolov8會自動下載所需要的yolov8.yamlyolov8n.pt

import multiprocessing
import os
from ultralytics import YOLO
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'

def my_function():
    model = YOLO('yolov8.yaml').load("yolov8n.pt")
    # Train the model
    model.train(data='./data.yaml', epochs=300, imgsz=640)
    model.val(data="./data.yaml")

if __name__ == '__main__':
    multiprocessing.freeze_support()  # Optional, if you're freezing the script
    my_function()

這時候會出現錯誤如下,因為資料集放在哪邊也是剛剛才自動下載的,所以我們要打開一下這個設定檔案,設定一下我們的資料集的正確位置(datasets_dir)

看到這些訊息就代表成功的開始建模型囉!

模型使用範例

重點是在這行

model = YOLO('best.pt')

這行在載入我們建好的模型

results = model(image, show=False, verbose=False)

model這個預測方法有很多可控制的參數,例如要不要直接秀出圖片、要不要存圖片等等

YOLOv8非常貼心的是在於說,其吐出的物件如result,只要print這個物件,就會有非常詳細的結構和屬性意義教學,在開發上非常的方便

import VideoStream
import cv2
import numpy as np
from ultralytics import YOLO


videostream = VideoStream.VideoStream((1280, 720), 30, 0).start()
cam_quit = 0
model = YOLO('best.pt')
# 繪製邊框和標籤
def detect(image):
    results = model(image, show=False, verbose=False)
    # Show the results
    result = list(results)[0]
    for i in range(len(result.boxes)):
        r = result[i].boxes
        cls = int(r.cls[0].item())
        xywh = r.xywh[0].tolist()
        x_center, y_center, width, height = [int(x) for x in xywh[:4]]
        if width < 100 and height < 100:
            x1 = int(x_center - (width / 2))
            y1 = int(y_center - (height / 2))
            x2 = x1 + width
            y2 = y1 + height
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 3)
            cv2.putText(image, result.names[cls], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 1, cv2.LINE_AA) 

while cam_quit == 0:
    imageSource = videostream.read()
    imageSource = cv2.resize(imageSource, (960, 540))
    detect(imageSource)
    cv2.imshow("image", imageSource)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        cam_quit = 1

videostream.stop()
cv2.destroyAllWindows()