from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # pretrained YOLOv8n model
# Run batched inference on a list of images
results = model(['im1.jpg', 'im2.jpg']) # return a list of Results objects
# Process results list
for result in results:
boxes = result.boxes # Boxes object for bbox 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
print(masks )
從API我們可以得知,若我們使用的是yolo-seg,則吐回的座標資訊可參考這個返回值
完整預測結果轉標記的程式範例
設定folder_path到images的資料夾,label會放到相對應的labels資料夾下
from ultralytics import YOLO
from PIL import Image
import cv2
import os
# 資料夾路徑
folder_path = './datasets/coco8-seg/images/train'
images = []
# 確保資料夾存在
if not os.path.exists(folder_path):
print("資料夾不存在")
else:
# 取得資料夾內所有檔案
file_list = os.listdir(folder_path)
# 遍歷每個檔案
for filename in file_list:
# 確保檔案是圖片檔案(可根據您的需求調整)
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
# 構建完整的檔案路徑
file_path = os.path.join(folder_path, filename)
images.append(file_path)
# Load a model
model = YOLO('yolov8n-seg.pt') # pretrained YOLOv8n model
# Run batched inference on a list of images
results = model(images) # return a list of Results objects
# Show the results
for r in results:
formatted_string = ""
if r is not None and r.masks is not None:
for i in range(len(r.masks.xyn)):
mask = r.masks.xyn[i]
cls = int(r.boxes.cls[i].item())
formatted_rows = []
formatted_rows.append(cls)
for row in mask:
formatted_rows.append(row[0])
formatted_rows.append(row[1])
formatted_string = ((formatted_string + '\n') if formatted_string != "" else "") + " ".join(str(x) for x in formatted_rows)
with open(r.path.replace('.jpg', '.txt').replace('images', 'labels'), "a") as file:
file.write(formatted_string)
Collecting package metadata (current_repodata.json): failed CondaSSLError: OpenSSL appears to be unavailable on this machine. OpenSSL is required to download and install packages. Exception: HTTPSConnectionPool(host=’conda.anaconda.org’, port=443): Max retries exceeded with url: /conda-forge/win-64/current_repodata.json (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”))