Python 使用方法
YOLOv8 Python 使用法ドキュメントへようこそ!このガイドは、オブジェクト検出、セグメンテーション、分類を行うPython プロジェクトにYOLOv8 をシームレスに統合するためのものです。ここでは、事前に学習させたモデルをロードして使用する方法、新しいモデルを学習させる方法、画像に対して予測を実行する方法について説明します。使いやすいPython インタフェースは、YOLOv8 をPython プロジェクトに組み込もうとする人にとって貴重なリソースであり、高度な物体検出機能を素早く実装することができます。さっそく始めましょう!
見るんだ: MasteringUltralytics YOLOv8 :Python
例えば、数行のコードだけで、モデルをロードし、訓練し、検証セットで性能を評価し、ONNX フォーマットにエクスポートすることもできる。
Python
from ultralytics import YOLO
# Create a new YOLO model from scratch
model = YOLO('yolov8n.yaml')
# Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')
# Train the model using the 'coco8.yaml' dataset for 3 epochs
results = model.train(data='coco8.yaml', epochs=3)
# Evaluate the model's performance on the validation set
results = model.val()
# Perform object detection on an image using the model
results = model('https://ultralytics.com/images/bus.jpg')
# Export the model to ONNX format
success = model.export(format='onnx')
電車
Trainモードは、カスタムデータセットでYOLOv8 モデルの学習に使用します。このモードでは、指定されたデータセットとハイパーパラメータを使用してモデルがトレーニングされます。学習プロセスでは、画像内のオブジェクトのクラスと位置を正確に予測できるように、モデルのパラメータを最適化します。
電車
バル
Valモードは、YOLOv8 モデルが学習された後の検証に使用される。このモードでは、モデルの精度と汎化性能を測定するために、モデルが検証集合で評価される。このモードは、モデルの性能を向上させるために、モデルのハイパーパラメータを調整するために使用できます。
バル
予測する
Predict(予測)モードは、新しい画像やビデオに対して学習されたYOLOv8 モデルを使用して予測を行うために使用されます。このモードでは、モデルはチェックポイントファイルからロードされ、ユーザーは推論を実行するために画像やビデオを提供することができます。モデルは、入力画像またはビデオ内のオブジェクトのクラスと位置を予測します。
予測する
from ultralytics import YOLO
from PIL import Image
import cv2
model = YOLO("model.pt")
# accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam
results = model.predict(source="0")
results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments
# from PIL
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True) # save plotted images
# from ndarray
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels
# from list of PIL/ndarray
results = model.predict(source=[im1, im2])
# results would be a list of Results object including all the predictions by default
# but be careful as it could occupy a lot memory when there're many images,
# especially the task is segmentation.
# 1. return as a list
results = model.predict(source="folder")
# results would be a generator which is more friendly to memory by setting stream=True
# 2. return as a generator
results = model.predict(source=0, stream=True)
for result in results:
# Detection
result.boxes.xyxy # box with xyxy format, (N, 4)
result.boxes.xywh # box with xywh format, (N, 4)
result.boxes.xyxyn # box with xyxy format but normalized, (N, 4)
result.boxes.xywhn # box with xywh format but normalized, (N, 4)
result.boxes.conf # confidence score, (N, 1)
result.boxes.cls # cls, (N, 1)
# Segmentation
result.masks.data # masks, (N, H, W)
result.masks.xy # x,y segments (pixels), List[segment] * N
result.masks.xyn # x,y segments (normalized), List[segment] * N
# Classification
result.probs # cls prob, (num_class, )
# Each result is composed of torch.Tensor by default,
# in which you can easily use following functionality:
result = result.cuda()
result = result.cpu()
result = result.to("cpu")
result = result.numpy()
輸出
エクスポートモードは、YOLOv8 のモデルを配備に使用できる形式にエクスポートするために使用します。このモードでは、モデルは他のソフトウェア・アプリケーションやハードウェア・デバイスで使用できる形式に変換されます。このモードは、モデルを本番環境に配備する際に便利です。
輸出
YOLOv8n 公式モデルをONNX に、バッチサイズと画像サイズをダイナミックに指定してエクスポート。
トラック
トラックモードは、YOLOv8 モデルを使ってリアルタイムでオブジェクトを追跡するために使用されます。このモードでは、モデルはチェックポイントファイルからロードされ、ユーザーはライブビデオストリームを提供してリアルタイムのオブジェクトトラッキングを実行することができます。このモードは、監視システムや自動運転車などのアプリケーションに便利です。
トラック
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # load an official detection model
model = YOLO('yolov8n-seg.pt') # load an official segmentation model
model = YOLO('path/to/best.pt') # load a custom model
# Track with the model
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")
ベンチマーク
ベンチマークモードは、YOLOv8 の様々なエクスポートフォーマットの速度と精度のプロファイリングに使用されます。ベンチマークは、エクスポートされたフォーマットのサイズ、その mAP50-95
メトリクス(オブジェクト検出とセグメンテーション用)または accuracy_top5
メトリックス(分類用)、およびONNX,OpenVINO,TensorRT などの様々なエクスポート・フォーマットにおける画像ごとの推論時間(ミリ秒)。この情報は、ユーザーが速度と精度の要件に基づいて、特定のユースケースに最適なエクスポート形式を選択するのに役立ちます。
ベンチマーク
エクスプローラー
エクスプローラAPIは、高度なセマンティック検索、ベクトル類似度検索、SQL検索などの機能を使ってデータセットを探索することができる。また、LLMのパワーを活用することで、自然言語を使用したコンテンツに基づく画像の検索も可能になりました。エクスプローラAPIでは、独自のデータセット探索ノートブックやスクリプトを作成し、データセットに対する洞察を得ることができる。
エクスプローラーを使ったセマンティック検索
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data='coco8.yaml', model='yolov8n.pt')
exp.create_embeddings_table()
similar = exp.get_similar(img='https://ultralytics.com/images/bus.jpg', limit=10)
print(similar.head())
# Search using multiple indices
similar = exp.get_similar(
img=['https://ultralytics.com/images/bus.jpg',
'https://ultralytics.com/images/bus.jpg'],
limit=10
)
print(similar.head())
from ultralytics import Explorer
# create an Explorer object
exp = Explorer(data='coco8.yaml', model='yolov8n.pt')
exp.create_embeddings_table()
similar = exp.get_similar(idx=1, limit=10)
print(similar.head())
# Search using multiple indices
similar = exp.get_similar(idx=[1,10], limit=10)
print(similar.head())
トレーナーの活用
YOLO
モデルクラスはトレーナークラスの高レベルラッパーです。それぞれのYOLO タスクは BaseTrainer
.
検出トレーナーの例
```python
from ultralytics.models.yolo import DetectionTrainer, DetectionValidator, DetectionPredictor
# trainer
trainer = DetectionTrainer(overrides={})
trainer.train()
trained_model = trainer.best
# Validator
val = DetectionValidator(args=...)
val(model=trained_model)
# predictor
pred = DetectionPredictor(overrides={})
pred(source=SOURCE, model=trained_model)
# resume from last weight
overrides["resume"] = trainer.last
trainer = detect.DetectionTrainer(overrides=overrides)
```
カスタムタスクをサポートしたり、研究開発のアイデアを探求したりするために、トレーナーを簡単にカスタマイズすることができます。カスタマイズの詳細 Trainers
, Validators
そして Predictors
をカスタマイズセクションでプロジェクトのニーズに合わせて変更することができます。
作成日:2023-11-12 更新日:2024-04-18
著者:Glenn-Jocher(9),AyushExel(1),RizwanMunawar(1),Laughing-q(1),maianumerosky(1)