コンテンツへスキップ

によるモデル予測Ultralytics YOLO

Ultralytics YOLO エコシステムと統合

はじめに

In the world of machine learning and computer vision, the process of making sense out of visual data is called 'inference' or 'prediction'. Ultralytics YOLO11 offers a powerful feature known as predict mode that is tailored for high-performance, real-time inference on a wide range of data sources.



見るんだ: How to Extract the Outputs from Ultralytics YOLO Model for Custom Projects.

実世界での応用

製造業スポーツ安全性
車両予備品検出サッカー選手検出落下検知
車両予備品検出サッカー選手検出落下検知

なぜ推論にUltralytics YOLO を使うのか?

Here's why you should consider YOLO11's predict mode for your various inference needs:

  • 汎用性:画像、ビデオ、ライブストリームでさえも推論が可能。
  • Performance: Engineered for real-time, high-speed processing without sacrificing accuracy.
  • 使いやすさ:直感的なPython およびCLI インターフェースにより、迅速な展開とテストが可能。
  • 高いカスタマイズ性:様々な設定やパラメータにより、特定の要件に応じてモデルの推論動作を調整することができます。

予測モードの主な特徴

YOLO11's predict mode is designed to be robust and versatile, featuring:

  • 複数のデータソースの互換性:データが個々の画像、画像集、ビデオファイル、またはリアルタイムのビデオストリームのいずれであっても、予測モードでカバーできます。
  • ストリーミング・モード: のメモリ効率に優れたジェネレーターを生成するには、ストリーミング機能を使う。 Results オブジェクトを使用します。これを有効にするには stream=True をプレディクターの呼び出しメソッドに追加する。
  • バッチ処理:複数の画像やビデオフレームを一括して処理できるため、推論時間がさらに短縮される。
  • 統合が容易:柔軟なAPIにより、既存のデータパイプラインや他のソフトウェアコンポーネントと簡単に統合できます。

Ultralytics YOLO のPython リストを返す。 Results Python オブジェクトを生成する。 Results オブジェクトが stream=True は推論中にモデルに渡される:

予測する

from ultralytics import YOLO

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

# Run batched inference on a list of images
results = model(["image1.jpg", "image2.jpg"])  # return a list of Results objects

# 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.show()  # display to screen
    result.save(filename="result.jpg")  # save to disk
from ultralytics import YOLO

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

# Run batched inference on a list of images
results = model(["image1.jpg", "image2.jpg"], stream=True)  # return a generator of Results objects

# Process results generator
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.show()  # display to screen
    result.save(filename="result.jpg")  # save to disk

推論ソース

YOLO11 can process different types of input sources for inference, as shown in the table below. The sources include static images, video streams, and various data formats. The table also indicates whether each source can be used in streaming mode with the argument stream=True ✅.ストリーミングモードは、すべてのフレームをメモリにロードする代わりに、結果のジェネレーターを作成するので、ビデオやライブストリームを処理するのに有益です。

チップ

用途 stream=True 長い動画や大きなデータセットを処理する際に、メモリを効率的に管理する。いつ stream=Falseこの場合、すべてのフレームまたはデータポイントの結果がメモリに保存されるため、大きな入力に対してすぐに加算され、メモリ不足エラーが発生する可能性がある。これに対して stream=True ジェネレーターを使用し、現在のフレームまたはデータポイントの結果のみをメモリに保持することで、メモリ消費を大幅に削減し、メモリ不足の問題を防ぎます。

ソースタイプ備考
イメージ'image.jpg'str または Path単一の画像ファイル。
URL'https://ultralytics.com/images/bus.jpg'str画像へのURL。
スクリーンショット'screen'strスクリーンショットを撮る。
ピルImage.open('image.jpg')PIL.ImageRGBチャンネルのHWCフォーマット。
オープンCVcv2.imread('image.jpg')np.ndarrayBGRチャンネル付きHWCフォーマット uint8 (0-255).
ナンピーnp.zeros((640,1280,3))np.ndarrayBGRチャンネル付きHWCフォーマット uint8 (0-255).
torchtorch.zeros(16,3,320,640)torch.TensorRGBチャンネルを持つBCHWフォーマット float32 (0.0-1.0).
シーエスブイ'sources.csv'str または Path画像、ビデオ、またはディレクトリへのパスを含むCSVファイル。
ビデオ'video.mp4'str または PathMP4、AVIなどのビデオファイル。
ディレクトリ'path/'str または Path画像または動画を含むディレクトリへのパス。
グロブ'path/*.jpg'str複数のファイルにマッチするグロブ・パターン。複数のファイルにマッチさせるには * 文字をワイルドカードとして使用する。
ユーチューブ'https://youtu.be/LNwODJXcvt4'strYouTubeビデオのURL。
ストリーム'rtsp://example.com/media.mp4'strRTSP、RTMP、TCPなどのストリーミング・プロトコルのURL、またはIPアドレス。
マルチストリーム'list.streams'str または Path*.streams テキストファイルで、1行につき1つのストリームURL、つまりバッチサイズ8で8つのストリームが実行される。
webcam ✅0intIndex of the connected camera device to run inference on.

以下に、各ソース・タイプを使用するためのコード例を示します:

予測ソース

画像ファイルに対して推論を実行する。

from ultralytics import YOLO

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

# Define path to the image file
source = "path/to/image.jpg"

# Run inference on the source
results = model(source)  # list of Results objects

現在の画面の内容をスクリーンショットとして推論を実行する。

from ultralytics import YOLO

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

# Define current screenshot as source
source = "screen"

# Run inference on the source
results = model(source)  # list of Results objects

URLを介してリモートでホストされている画像やビデオで推論を実行します。

from ultralytics import YOLO

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

# Define remote image or video URL
source = "https://ultralytics.com/images/bus.jpg"

# Run inference on the source
results = model(source)  # list of Results objects

Python Imaging Library (PIL)で開いた画像に対して推論を実行する。

from PIL import Image

from ultralytics import YOLO

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

# Open an image using PIL
source = Image.open("path/to/image.jpg")

# Run inference on the source
results = model(source)  # list of Results objects

OpenCVで読み込んだ画像に対して推論を実行する。

import cv2

from ultralytics import YOLO

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

# Read an image using OpenCV
source = cv2.imread("path/to/image.jpg")

# Run inference on the source
results = model(source)  # list of Results objects

numpyの配列として表現された画像に対して推論を実行する。

import numpy as np

from ultralytics import YOLO

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

# Create a random numpy array of HWC shape (640, 640, 3) with values in range [0, 255] and type uint8
source = np.random.randint(low=0, high=255, size=(640, 640, 3), dtype="uint8")

# Run inference on the source
results = model(source)  # list of Results objects

Run inference on an image represented as a PyTorch tensor.

import torch

from ultralytics import YOLO

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

# Create a random torch tensor of BCHW shape (1, 3, 640, 640) with values in range [0, 1] and type float32
source = torch.rand(1, 3, 640, 640, dtype=torch.float32)

# Run inference on the source
results = model(source)  # list of Results objects

CSVファイルにリストされた画像、URL、ビデオ、ディレクトリのコレクションに対して推論を実行します。

from ultralytics import YOLO

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

# Define a path to a CSV file with images, URLs, videos and directories
source = "path/to/file.csv"

# Run inference on the source
results = model(source)  # list of Results objects

ビデオファイルで推論を実行する。を使用して stream=Trueを使えば、結果オブジェクトのジェネレーターを作成してメモリ使用量を減らすことができる。

from ultralytics import YOLO

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

# Define path to video file
source = "path/to/video.mp4"

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

ディレクトリ内のすべての画像と動画に対して推論を実行する。サブディレクトリ内の画像や動画もキャプチャするには、グロブパターンを使う。 path/to/dir/**/*.

from ultralytics import YOLO

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

# Define path to directory containing images and videos for inference
source = "path/to/dir"

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

というグロブ表現にマッチするすべての画像と動画に対して推論を実行する。 * の文字がある。

from ultralytics import YOLO

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

# Define a glob search for all JPG files in a directory
source = "path/to/dir/*.jpg"

# OR define a recursive glob search for all JPG files including subdirectories
source = "path/to/dir/**/*.jpg"

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

YouTubeの動画で推論を実行。を使うことで stream=Trueまた、Resultsオブジェクトのジェネレーターを作成すれば、長い動画のメモリ使用量を減らすことができる。

from ultralytics import YOLO

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

# Define source as YouTube video URL
source = "https://youtu.be/LNwODJXcvt4"

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

Use the stream mode to run inference on live video streams using RTSP, RTMP, TCP, or IP address protocols. If a single stream is provided, the model runs inference with a batch size of 1. For multiple streams, a .streams text file can be used to perform batched inference, where the batch size is determined by the number of streams provided (e.g., batch-size 8 for 8 streams).

from ultralytics import YOLO

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

# Single stream with batch-size 1 inference
source = "rtsp://example.com/media.mp4"  # RTSP, RTMP, TCP, or IP streaming address

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

For single stream usage, the batch size is set to 1 by default, allowing efficient real-time processing of the video feed.

To handle multiple video streams simultaneously, use a .streams text file containing the streaming sources. The model will run batched inference where the batch size equals the number of streams. This setup enables efficient processing of multiple feeds concurrently.

from ultralytics import YOLO

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

# Multiple streams with batched inference (e.g., batch-size 8 for 8 streams)
source = "path/to/list.streams"  # *.streams text file with one streaming address per line

# Run inference on the source
results = model(source, stream=True)  # generator of Results objects

.streams text file:

rtsp://example.com/media1.mp4
rtsp://example.com/media2.mp4
rtmp://example2.com/live
tcp://192.168.1.100:554
...

Each row in the file represents a streaming source, allowing you to monitor and perform inference on several video streams at once.

You can run inference on a connected camera device by passing the index of that particular camera to source.

from ultralytics import YOLO

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

# Run inference on the source
results = model(source=0, stream=True)  # generator of Results objects

推論

model.predict() は、推論時にデフォルトを上書きするために渡すことができる複数の引数を受け付ける:

from ultralytics import YOLO

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

# Run inference on 'bus.jpg' with arguments
model.predict("bus.jpg", save=True, imgsz=320, conf=0.5)

推論引数:

議論タイプデフォルト説明
sourcestr'ultralytics/assets'Specifies the data source for inference. Can be an image path, video file, directory, URL, or device ID for live feeds. Supports a wide range of formats and sources, enabling flexible application across different types of input.
conffloat0.25検出の最小信頼度しきい値を設定します。この閾値以下の信頼度で検出されたオブジェクトは無視されます。この値を調整することで、誤検出を減らすことができます。
ioufloat0.7Intersection Over Union (IoU) threshold for Non-Maximum Suppression (NMS). Lower values result in fewer detections by eliminating overlapping boxes, useful for reducing duplicates.
imgszint or tuple640推論のための画像サイズを定義する。単一の整数値 640 for square resizing or a (height, width) tuple. Proper sizing can improve detection accuracy and processing speed.
halfboolFalseEnables half-precision (FP16) inference, which can speed up model inference on supported GPUs with minimal impact on accuracy.
devicestrNone推論を行うデバイスを指定する(例. cpu, cuda:0 または 0).CPU 、特定のGPU 、またはモデル実行のための他のコンピュート・デバイスを選択することができます。
max_detint300画像あたりの最大検出数。1回の推論でモデルが検出できるオブジェクトの総数を制限し、密集したシーンでの過剰な出力を防ぎます。
vid_strideint1ビデオ入力のフレームストライド。時間的な解像度を犠牲にして処理を高速化するために、ビデオのフレームをスキップできるようにする。1の値はすべてのフレームを処理し、それ以上の値はフレームをスキップする。
stream_bufferboolFalseDetermines whether to queue incoming frames for video streams. If False, old frames get dropped to accomodate new frames (optimized for real-time applications). If `True', queues new frames in a buffer, ensuring no frames get skipped, but will cause latency if inference FPS is lower than stream FPS.
visualizeboolFalse推論中にモデルの特徴を可視化し、モデルが何を「見て」いるのかを知ることができます。デバッグやモデルの解釈に役立ちます。
augmentboolFalse予測に対するテスト時間拡張(TTA)を可能にし、推論速度を犠牲にすることで検出のロバスト性を向上させる可能性がある。
agnostic_nmsboolFalse異なるクラスのオーバーラップしたボックスをマージする、クラスにとらわれない非最大抑制(NMS)を有効にします。クラスの重複が一般的なマルチクラス検出シナリオで有用。
classeslist[int]Noneクラス ID のセットに予測をフィルタリングします。指定されたクラスに属する検出のみが返されます。複数クラスの検出タスクで、関連するオブジェクトに焦点を当てるのに便利です。
retina_masksboolFalseモデルに高解像度のセグメンテーションマスクがあれば、それを使用する。これにより、セグメンテーションタスクのマスク品質が向上し、より細かいディテールが得られます。
embedlist[int]NoneSpecifies the layers from which to extract feature vectors or embeddings. Useful for downstream tasks like clustering or similarity search.

可視化の引数:

議論タイプデフォルト説明
showboolFalseもし True注釈付きの画像やビデオをウィンドウに表示します。開発中やテスト中の即時の視覚的フィードバックに便利です。
saveboolFalse または TrueEnables saving of the annotated images or videos to file. Useful for documentation, further analysis, or sharing results. Defaults to True when using CLI & False when used in Python.
save_framesboolFalse動画を処理する際、個々のフレームを画像として保存します。特定のフレームを抽出したり、フレームごとの詳細な分析に便利です。
save_txtboolFalse検出結果をテキストファイルに保存します。 [class] [x_center] [y_center] [width] [height] [confidence].他の分析ツールとの統合に便利。
save_confboolFalse保存されたテキストファイルに信頼度スコアが含まれます。後処理や分析に利用できる詳細な情報が強化されます。
save_cropboolFalse検出画像をトリミングして保存します。データセットの補強や分析、特定の対象物に特化したデータセットの作成に便利です。
show_labelsboolTrue視覚出力に各検出のラベルを表示。検出されたオブジェクトを即座に理解できます。
show_confboolTrue各検出の信頼スコアがラベルと一緒に表示されます。各検出に対するモデルの確信度を示します。
show_boxesboolTrue検出されたオブジェクトの周囲にバウンディングボックスを描画します。画像やビデオフレーム内のオブジェクトを視覚的に識別し、位置を特定するために不可欠です。
line_widthNone または intNoneバウンディングボックスの線幅を指定します。もし None画像サイズに応じて、線幅が自動的に調整されます。視覚的にわかりやすくカスタマイズできます。

画像とビデオのフォーマット

YOLO11 supports various image and video formats, as specified in ultralytics/data/utils.py. See the tables below for the valid suffixes and example predict commands.

画像

以下の表は、有効なUltralytics 画像フォーマットを示しています。

HEIC images are supported for inference only, not for training.

画像の接尾辞予測コマンドの例参考
.bmpyolo predict source=image.bmpMicrosoft BMPファイル形式
.dngyolo predict source=image.dngアドビDNG
.jpegyolo predict source=image.jpegジェイペグ
.jpgyolo predict source=image.jpgジェイペグ
.mpoyolo predict source=image.mpoマルチピクチャーオブジェクト
.pngyolo predict source=image.pngポータブル・ネットワーク・グラフィックス
.tifyolo predict source=image.tifタグ画像ファイル形式
.tiffyolo predict source=image.tiffタグ画像ファイル形式
.webpyolo predict source=image.webpウェブピー
.pfmyolo predict source=image.pfmポータブル・フロートマップ
.HEICyolo predict source=image.HEICHigh Efficiency Image Format

ビデオ

以下の表には、有効なUltralytics ビデオフォーマットが記載されています。

ビデオの接尾辞予測コマンドの例参考
.asfyolo predict source=video.asfアドバンスト・システムズ・フォーマット
.aviyolo predict source=video.aviオーディオ・ビデオ・インターリーブ
.gifyolo predict source=video.gifグラフィックス交換フォーマット
.m4vyolo predict source=video.m4vMPEG-4パート14
.mkvyolo predict source=video.mkvマトロスカ
.movyolo predict source=video.movQuickTimeファイルフォーマット
.mp4yolo predict source=video.mp4MPEG-4 Part 14 - Wikipedia
.mpegyolo predict source=video.mpegMPEG-1パート2
.mpgyolo predict source=video.mpgMPEG-1パート2
.tsyolo predict source=video.tsMPEGトランスポートストリーム
.wmvyolo predict source=video.wmvウィンドウズ・メディア・ビデオ
.webmyolo predict source=video.webmWebMプロジェクト

結果を出す

すべてUltralytics predict() のリストを返す。 Results オブジェクトがある:

結果

from ultralytics import YOLO

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

# Run inference on an image
results = model("bus.jpg")  # list of 1 Results object
results = model(["bus.jpg", "zidane.jpg"])  # list of 2 Results objects

Results オブジェクトは以下の属性を持つ:

属性タイプ説明
orig_imgnumpy.ndarraynumpy 配列としての元画像。
orig_shapetuple元の画像の形状を (height, width) フォーマットで表したもの。
boxesBoxes, optional検出バウンディングボックスを含むBoxesオブジェクト。
masksMasks, optional検出マスクを含むMasksオブジェクト。
probsProbs, optional分類タスクの各クラスの確率を含む Probs オブジェクト。
keypointsKeypoints, optional各オブジェクトの検出されたキーポイントを含むキーポイントオブジェクト。
obbOBB, optional指向バウンディングボックスを含む OBB オブジェクト。
speeddict前処理、推論、後処理の速度を画像ごとにミリ秒単位で表した辞書。
namesdictクラス名の辞書。
pathstr画像ファイルのパス。

Results オブジェクトには以下のメソッドがある:

方法リターン・タイプ説明
update()None結果オブジェクトのボックス、マスク、probs属性を更新する。
cpu()ResultsCPU 、すべてのテンソルを含むResultsオブジェクトのコピーを返す。
numpy()Resultsすべてのテンソルをnumpy配列としてResultsオブジェクトのコピーを返す。
cuda()ResultsGPU 、すべてのテンソルを含むResultsオブジェクトのコピーを返す。
to()Results指定されたデバイスとdtypeのテンソルを持つResultsオブジェクトのコピーを返す。
new()Results同じ画像、パス、名前を持つ新しいResultsオブジェクトを返す。
plot()numpy.ndarray検出結果をプロットする。注釈付き画像のnumpy配列を返します。
show()None注釈付きの結果を画面に表示する。
save()None注釈付き結果をファイルに保存
verbose()str各タスクのログ文字列を返す。
save_txt()None予測値をtxtファイルに保存する。
save_crop()Noneトリミングした予測値を保存する save_dir/cls/file_name.jpg.
tojson()strオブジェクトをJSON形式に変換する。

詳細は Results クラス文書.

ボックス

Boxes オブジェクトは、バウンディング・ボックスのインデックス付け、操作、異なるフォーマットへの変換に使用できる。

ボックス

from ultralytics import YOLO

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

# Run inference on an image
results = model("bus.jpg")  # results list

# View results
for r in results:
    print(r.boxes)  # print the Boxes object containing the detection bounding boxes

以下はその表である。 Boxes クラスのメソッドとプロパティの名前、型、説明:

名称タイプ説明
cpu()方法オブジェクトをCPU メモリに移動する。
numpy()方法オブジェクトをnumpy配列に変換します。
cuda()方法オブジェクトをCUDA メモリに移動する。
to()方法オブジェクトを指定されたデバイスに移動する。
xyxyプロパティtorch.Tensor)xyxy フォーマットでボックスを返す。
confプロパティtorch.Tensor)ボックスの信頼値を返す。
clsプロパティtorch.Tensor)ボックスのクラス値を返す。
idプロパティtorch.Tensor)ボックスのトラックIDを返す(利用可能な場合)。
xywhプロパティtorch.Tensor)xywh フォーマットでボックスを返す。
xyxynプロパティtorch.Tensor)元の画像サイズで正規化した xyxy 形式のボックスを返す。
xywhnプロパティtorch.Tensor)元の画像サイズで正規化した xywh 形式のボックスを返す。

詳細は Boxes クラス文書.

マスク

Masks オブジェクトを使用して、マスクのインデックス付け、操作、セグメントへの変換を行うことができます。

マスク

from ultralytics import YOLO

# Load a pretrained YOLO11n-seg Segment model
model = YOLO("yolo11n-seg.pt")

# Run inference on an image
results = model("bus.jpg")  # results list

# View results
for r in results:
    print(r.masks)  # print the Masks object containing the detected instance masks

以下はその表である。 Masks クラスのメソッドとプロパティの名前、型、説明:

名称タイプ説明
cpu()方法CPU メモリ上のマスクtensor を返す。
numpy()方法マスクtensor を numpy の配列として返します。
cuda()方法GPU メモリ上のマスクtensor を返す。
to()方法指定されたデバイスと dtype を持つマスクtensor を返す。
xynプロパティtorch.Tensor)正規化されたセグメントのリスト。
xyプロパティtorch.Tensor)テンソルとして表現されたピクセル座標のセグメントのリスト。

詳細は Masks クラス文書.

キーポイント

Keypoints オブジェクトは、座標のインデックス付け、操作、正規化に使用できる。

キーポイント

from ultralytics import YOLO

# Load a pretrained YOLO11n-pose Pose model
model = YOLO("yolo11n-pose.pt")

# Run inference on an image
results = model("bus.jpg")  # results list

# View results
for r in results:
    print(r.keypoints)  # print the Keypoints object containing the detected keypoints

以下はその表である。 Keypoints クラスのメソッドとプロパティの名前、型、説明:

名称タイプ説明
cpu()方法CPU メモリ上のtensor キーポイントを返す。
numpy()方法キーポイントtensor を numpy の配列として返す。
cuda()方法GPU メモリ上のtensor キーポイントを返す。
to()方法指定されたデバイスと dtype を持つキーポイントtensor を返す。
xynプロパティtorch.Tensor)テンソルとして表現された正規化キーポイントのリスト。
xyプロパティtorch.Tensor)テンソルとして表現されたピクセル座標のキーポイントのリスト。
confプロパティtorch.Tensor)キーポイントの信頼値があればそれを返し、なければ None。

詳細は Keypoints クラス文書.

問題

Probs オブジェクトを使用することができます。 top1 そして top5 分類の指標と得点。

問題

from ultralytics import YOLO

# Load a pretrained YOLO11n-cls Classify model
model = YOLO("yolo11n-cls.pt")

# Run inference on an image
results = model("bus.jpg")  # results list

# View results
for r in results:
    print(r.probs)  # print the Probs object containing the detected class probabilities

のメソッドとプロパティを表にまとめた。 Probs クラスである:

名称タイプ説明
cpu()方法CPU メモリ上の probstensor のコピーを返す。
numpy()方法probstensor のコピーを numpy 配列として返す。
cuda()方法GPU メモリ上の probstensor のコピーを返す。
to()方法指定されたデバイスと dtype を持つ probstensor のコピーを返す。
top1プロパティint)トップ1クラスのインデックス。
top5プロパティlist[int])上位5クラスの指標。
top1confプロパティtorch.Tensor)トップ1クラスの自信。
top5confプロパティtorch.Tensor)トップ5クラスのコンフィデンス

詳細は Probs クラス文書.

OBB

OBB オブジェクトを使用して、インデックスを作成したり、バウンディングボックスを操作したり、異なるフォーマットに変換したりすることができる。

OBB

from ultralytics import YOLO

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

# Run inference on an image
results = model("bus.jpg")  # results list

# View results
for r in results:
    print(r.obb)  # print the OBB object containing the oriented detection bounding boxes

以下はその表である。 OBB クラスのメソッドとプロパティの名前、型、説明:

名称タイプ説明
cpu()方法オブジェクトをCPU メモリに移動する。
numpy()方法オブジェクトをnumpy配列に変換します。
cuda()方法オブジェクトをCUDA メモリに移動する。
to()方法オブジェクトを指定されたデバイスに移動する。
confプロパティtorch.Tensor)ボックスの信頼値を返す。
clsプロパティtorch.Tensor)ボックスのクラス値を返す。
idプロパティtorch.Tensor)ボックスのトラックIDを返す(利用可能な場合)。
xyxyプロパティtorch.Tensor)水平ボックスをxyxy形式で返す。
xywhrプロパティtorch.Tensor)回転したボックスを xywhr フォーマットで返す。
xyxyxyxyプロパティtorch.Tensor)回転したボックスをxyxyxy形式で返す。
xyxyxyxynプロパティtorch.Tensor)画像サイズで正規化した xyxyxy 形式の回転ボックスを返す。

詳細は OBB クラス文書.

結果のプロット

について plot() メソッド Results オブジェクトは、検出されたオブジェクト(バウンディングボックス、マスク、キーポイント、確率など)を元の画像に重ねることで、予測の視覚化を容易にします。このメソッドは、注釈付き画像をNumPyの配列として返すので、表示や保存が簡単にできます。

プロット

from PIL import Image

from ultralytics import YOLO

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

# Run inference on 'bus.jpg'
results = model(["bus.jpg", "zidane.jpg"])  # results list

# Visualize the results
for i, r in enumerate(results):
    # Plot results image
    im_bgr = r.plot()  # BGR-order numpy array
    im_rgb = Image.fromarray(im_bgr[..., ::-1])  # RGB-order PIL image

    # Show results to screen (in supported environments)
    r.show()

    # Save results to disk
    r.save(filename=f"results{i}.jpg")

plot() メソッド・パラメーター

について plot() メソッドは、出力をカスタマイズするためのさまざまな引数をサポートしている:

議論タイプ説明デフォルト
confbool検出信頼度スコアを含める。True
line_widthfloatバウンディングボックスの線幅。以下の場合、画像サイズに合わせて拡大縮小します。 None.None
font_sizefloatテキストのフォントサイズ。もし None.None
fontstrテキスト注釈のフォント名。'Arial.ttf'
pilbool画像をPIL Imageオブジェクトとして返す。False
imgnumpy.ndarrayプロット用の代替画像。もし None.None
im_gputorch.TensorGPU-高速マスクプロット用加速画像。形状:(1, 3, 640, 640)。None
kpt_radiusint描画されるキーポイントの半径。5
kpt_lineboolキーポイントを線で結ぶ。True
labelsbool注釈にクラス・ラベルを含める。True
boxesbool画像にバウンディングボックスを重ねる。True
masksbool画像にマスクを重ねる。True
probsbool分類確率を含める。True
showboolデフォルトの画像ビューアを使用して、注釈付き画像を直接表示します。False
saveboolで指定したファイルに注釈画像を保存する。 filename.False
filenamestr注釈付き画像を保存するファイルのパスと名前。 saveTrue.None
color_modestrインスタンス」や「クラス」など、カラーモードを指定する。'class'

スレッドセーフ推論

推論中にスレッドセーフを確保することは、複数のYOLO モデルを異なるスレッドで並行して実行する場合に非常に重要です。スレッドセーフ推論は、各スレッドの予測が分離され、互いに干渉しないことを保証し、競合状態を回避し、一貫性のある信頼性の高い出力を保証します。

マルチスレッドのアプリケーションでYOLO モデルを使用する場合、競合を防ぐために、スレッドごとに別々のモデルオブジェクトをインスタンス化するか、スレッドローカルストレージを採用することが重要です:

スレッドセーフ推論

スレッドセーフな推論のために、各スレッド内で単一のモデルをインスタンス化する:

from threading import Thread

from ultralytics import YOLO


def thread_safe_predict(model, image_path):
    """Performs thread-safe prediction on an image using a locally instantiated YOLO model."""
    model = YOLO(model)
    results = model.predict(image_path)
    # Process results


# Starting threads that each have their own model instance
Thread(target=thread_safe_predict, args=("yolo11n.pt", "image1.jpg")).start()
Thread(target=thread_safe_predict, args=("yolo11n.pt", "image2.jpg")).start()

YOLO モデルによるスレッドセーフ推論の詳細とステップバイステップの手順については、YOLO スレッドセーフ推論ガイドを参照してください。このガイドでは、よくある落とし穴を避け、マルチスレッド推論をスムーズに実行するために必要な情報を提供します。

ストリーミング・ソース for-ループ

以下はOpenCVを使ったPython スクリプトである。cv2) and YOLO to run inference on video frames. This script assumes you have already installed the necessary packages (opencv-python そして ultralytics).

ストリーミング・フォー・ループ

import cv2

from ultralytics import YOLO

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

# Open the video file
video_path = "path/to/your/video/file.mp4"
cap = cv2.VideoCapture(video_path)

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLO inference on the frame
        results = model(frame)

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Display the annotated frame
        cv2.imshow("YOLO Inference", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()

このスクリプトはビデオの各フレームに対して予測を実行し、結果を視覚化してウィンドウに表示する。ループは'q'を押すことで終了できる。

よくあるご質問

What is Ultralytics YOLO and its predict mode for real-time inference?

Ultralytics YOLO is a state-of-the-art model for real-time object detection, segmentation, and classification. Its predict mode allows users to perform high-speed inference on various data sources such as images, videos, and live streams. Designed for performance and versatility, it also offers batch processing and streaming modes. For more details on its features, check out the Ultralytics YOLO predict mode.

How can I run inference using Ultralytics YOLO on different data sources?

Ultralytics YOLO can process a wide range of data sources, including individual images, videos, directories, URLs, and streams. You can specify the data source in the model.predict() を呼び出す。例えば 'image.jpg' ローカル・イメージまたは 'https://ultralytics.com/images/bus.jpg' をURLに使用する。様々な 推論ソース を参照してください。

How do I optimize YOLO inference speed and memory usage?

推論速度を最適化し、メモリを効率的に管理するには、ストリーミング・モードを使用することができます。 stream=True を予測メソッドの呼び出しメソッドに追加する。ストリーミング・モードは、メモリ効率のよい Results オブジェクトをロードする。長い動画や大きなデータセットの処理には、ストリーミングモードが特に便利です。詳細はこちら ストリーミングモード.

What inference arguments does Ultralytics YOLO support?

について model.predict() method in YOLO supports various arguments such as conf, iou, imgsz, deviceなどがあります。これらの引数により、信頼しきい値、画像サイズ、計算に使用するデバイスなどのパラメータを設定し、推論プロセスをカスタマイズすることができます。これらの引数の詳細な説明は 推論引数 セクションを参照されたい。

How can I visualize and save the results of YOLO predictions?

After running inference with YOLO, the Results オブジェクトには、注釈付き画像を表示したり保存したりするためのメソッドが含まれています。以下のようなメソッドが使えます。 result.show() そして result.save(filename="result.jpg") を使用して結果を視覚化し、保存する。これらのメソッドの包括的なリストについては 結果との取り組み セクションを参照されたい。

📅 Created 11 months ago ✏️ Updated 9 days ago

コメント