官方示例:模型预测与Ultralytics YOLO
你可以在官网找到这样一个推理示例,但是这里没有设置显卡。
这里提供一个用于可以设置显卡进行批量推理的示例
import os
import cv2
from ultralytics import YOLO
from ultralytics.utils.torch_utils import select_device
# 初始化
weights = "./train/weights/best.pt"
yolo_model = YOLO(weights).to(select_device(device="3"))
test_path = "./testimgs"
res_path = "./resimgs"
os.makedirs(res_path, exist_ok=True)
for imgname in os.listdir(test_path):
img = cv2.imread(os.path.join(test_path, imgname))
results = yolo_model(img) # Track only person class
# Process results list
for result in results:
boxes = result.boxes # Boxes object for bounding box outputs
masks = result.masks # Masks object for segmentation masks outputs
keypoints = result.keypoints # Keypoints object for pose outputs
probs = result.probs # Probs object for classification outputs
obb = result.obb # Oriented boxes object for OBB outputs
result.save(filename=os.path.join(res_path, imgname.replace(".jpg","_res.jpg"))) # save to disk