コンテンツにスキップ

Pythonの使用方法

Ultralytics YOLO Python Usageドキュメントへようこそ!このガイドは、物体検出セグメンテーション、および分類のために、Ultralytics YOLOをPythonプロジェクトにシームレスに統合できるように設計されています。ここでは、事前トレーニング済みのモデルをロードして使用する方法、新しいモデルをトレーニングする方法、および画像で予測を実行する方法を学びます。使いやすいPythonインターフェースは、YOLOをPythonプロジェクトに組み込みたいと考えている人にとって貴重なリソースであり、高度な物体検出機能を迅速に実装できます。さあ、始めましょう!



見る: Ultralytics YOLOの習得:python

たとえば、ユーザーはモデルをロードし、トレーニングし、検証セットでパフォーマンスを評価し、わずか数行のコードでONNX 形式にエクスポートすることもできます。

Python

from ultralytics import YOLO

# Create a new YOLO model from scratch
model = YOLO("yolo11n.yaml")

# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolo11n.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")

トレーニング

トレーニングモードは、カスタムデータセットでYOLOモデルをトレーニングするために使用されます。このモードでは、モデルは指定されたデータセットとハイパーパラメータを使用してトレーニングされます。トレーニングプロセスでは、モデルのパラメータを最適化して、画像内のオブジェクトのクラスと場所を正確に予測できるようにします。

トレーニング

from ultralytics import YOLO

model = YOLO("yolo11n.pt")  # pass any model type
results = model.train(epochs=5)
from ultralytics import YOLO

model = YOLO("yolo11n.yaml")
results = model.train(data="coco8.yaml", epochs=5)
model = YOLO("last.pt")
results = model.train(resume=True)

学習例

Val

Valモードは、トレーニング後のYOLOモデルを検証するために使用されます。このモードでは、モデルは検証セットで評価され、その精度と汎化性能を測定します。このモードは、モデルのハイパーパラメータを調整して、そのパフォーマンスを向上させるために使用できます。

Val

from ultralytics import YOLO

# Load a YOLO model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate on training data
model.val()
from ultralytics import YOLO

# Load a YOLO model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate on separate data
model.val(data="path/to/separate/data.yaml")

Valの例

予測

Predictモードは、トレーニング済みのYOLOモデルを使用して、新しい画像またはビデオで予測を行うために使用されます。このモードでは、モデルはチェックポイントファイルからロードされ、ユーザーは推論を実行するために画像またはビデオを提供できます。モデルは、入力画像またはビデオ内のオブジェクトのクラスと場所を予測します。

予測

import cv2
from PIL import Image

from ultralytics import YOLO

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()

予測の例

エクスポート

エクスポートモードは、YOLOモデルをデプロイメントに使用できる形式にエクスポートするために使用されます。このモードでは、モデルは他のソフトウェアアプリケーションまたはハードウェアデバイスで使用できる形式に変換されます。このモードは、モデルを本番環境にデプロイする場合に役立ちます。

エクスポート

公式のYOLOモデルを、動的なバッチサイズと画像サイズでONNXにエクスポートします。

from ultralytics import YOLO

model = YOLO("yolo11n.pt")
model.export(format="onnx", dynamic=True)

公式のYOLOモデルをエクスポート TensorRT オン device=0 CUDAデバイスでの高速化のため。

from ultralytics import YOLO

model = YOLO("yolo11n.pt")
model.export(format="engine", device=0)

エクスポートの例

追跡

トラックモードは、YOLOモデルを使用してリアルタイムでオブジェクトを追跡するために使用されます。このモードでは、モデルはチェックポイントファイルからロードされ、ユーザーはライブビデオストリームを提供してリアルタイムのオブジェクト追跡を実行できます。このモードは、監視システムや自動運転車などのアプリケーションに役立ちます。

追跡

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n.pt")  # load an official detection model
model = YOLO("yolo11n-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")

追跡の例

ベンチマーク

ベンチマークモード は、YOLOのさまざまなエクスポート形式の速度と精度をプロファイルするために使用されます。ベンチマークは、エクスポートされた形式のサイズ、そのに関する情報を提供します。 mAP50-95 メトリクス(物体検出およびセグメンテーションの場合)または accuracy_top5 ONNXなどのさまざまなエクスポート形式における、分類のメトリクスと画像1枚あたりの推論時間(ミリ秒) OpenVINO、TensorRTなどがあります。この情報は、速度と精度の要件に基づいて、特定のユースケースに最適なエクスポート形式をユーザーが選択するのに役立ちます。

ベンチマーク

公式のYOLOモデルをすべてのエクスポート形式でベンチマークします。

from ultralytics.utils.benchmarks import benchmark

# Benchmark
benchmark(model="yolo11n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)

ベンチマークの例

トレーナーの使用

The YOLO model classは、Trainerクラスの高レベルラッパーとして機能します。各YOLOタスクには独自のトレーナーがあり、以下を継承します。 BaseTrainerこのアーキテクチャにより、柔軟性とカスタマイズ性が向上します。 機械学習ワークフロー.

検出トレーナーの例

from ultralytics.models.yolo import DetectionPredictor, DetectionTrainer, DetectionValidator

# 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 = DetectionTrainer(overrides=overrides)

カスタムタスクをサポートしたり、研究開発のアイデアを検討したりするために、Trainerを簡単にカスタマイズできます。Ultralytics YOLOのモジュール設計により、斬新なコンピュータビジョンタスクに取り組んでいる場合でも、パフォーマンスを向上させるために既存のモデルを微調整している場合でも、特定のニーズに合わせてフレームワークを適合させることができます。

カスタマイズチュートリアル

よくある質問

オブジェクト検出のためにYOLOをpythonプロジェクトに統合するにはどうすればよいですか?

Ultralytics YOLOをpythonプロジェクトに統合するのは簡単です。事前トレーニング済みのモデルをロードするか、新しいモデルを最初からトレーニングできます。開始方法は次のとおりです。

from ultralytics import YOLO

# Load a pretrained YOLO model
model = YOLO("yolo11n.pt")

# Perform object detection on an image
results = model("https://ultralytics.com/images/bus.jpg")

# Visualize the results
for result in results:
    result.show()

より詳細な例については、Predict Modeセクションを参照してください。

YOLOで利用できるさまざまなモードは何ですか?

Ultralytics YOLOは、さまざまな機械学習ワークフローに対応するためのさまざまなモードを提供します。これには以下が含まれます。

  • Train: カスタムデータセットを使用してモデルをトレーニングします。
  • Val: 検証セットでモデルのパフォーマンスを検証します。
  • Predict(予測):新しい画像またはビデオストリームで予測を行います。
  • Export: モデルを ONNX や TensorRT などのさまざまな形式にエクスポートします。
  • Track: ビデオストリーム内のリアルタイムオブジェクト追跡。
  • ベンチマーク: さまざまな構成におけるベンチマークモデルのパフォーマンス。

各モードは、モデルの開発とデプロイメントのさまざまな段階で包括的な機能を提供するように設計されています。

カスタムデータセットを使用して、カスタムYOLOモデルをトレーニングするにはどうすればよいですか?

カスタムYOLOモデルを学習させるには、データセットとその他のハイパーパラメータを指定する必要があります。簡単な例を次に示します。

from ultralytics import YOLO

# Load the YOLO model
model = YOLO("yolo11n.yaml")

# Train the model with custom dataset
model.train(data="path/to/your/dataset.yaml", epochs=10)

トレーニングの詳細と使用例へのハイパーリンクについては、Train Modeページをご覧ください。

デプロイメント用にYOLOモデルをエクスポートするにはどうすればよいですか?

YOLOモデルをデプロイに適した形式でエクスポートすることは、以下を使用すると簡単です。 export 関数。たとえば、モデルをONNX形式にエクスポートできます。

from ultralytics import YOLO

# Load the YOLO model
model = YOLO("yolo11n.pt")

# Export the model to ONNX format
model.export(format="onnx")

さまざまなエクスポートオプションについては、エクスポートモードのドキュメントを参照してください。

異なるデータセットでYOLOモデルを検証できますか?

はい、異なるデータセットでYOLOモデルを検証することは可能です。トレーニング後、検証モードを使用してパフォーマンスを評価できます。

from ultralytics import YOLO

# Load a YOLO model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate the model on a different dataset
model.val(data="path/to/separate/data.yaml")

詳細な例と使用方法については、Val Modeページをご確認ください。



📅 1年前に作成 ✏️ 5ヶ月前に更新

コメント