Back to Ultralytics

Model Prediction with Ultralytics YOLO

docs/en/modes/predict.md

8.4.4647.3 KB
Original Source

Model Prediction with Ultralytics YOLO

Introduction

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

<p align="center"> <iframe loading="lazy" width="720" height="405" src="https://www.youtube.com/embed/YKbBXWBJloY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe>

<strong>Watch:</strong> How to Extract Results from Ultralytics YOLO26 Tasks for Custom Projects 🚀

</p>

Real-world Applications

ManufacturingSportsSafety
Vehicle Spare Parts DetectionFootball Player DetectionPeople Fall Detection

Why Use Ultralytics YOLO for Inference?

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

  • Versatility: Capable of running inference on images, videos, and even live streams.
  • Performance: Engineered for real-time, high-speed processing without sacrificing accuracy.
  • Ease of Use: Intuitive Python and CLI interfaces for rapid deployment and testing.
  • Highly Customizable: Various settings and parameters to tune the model's inference behavior according to your specific requirements.
  • Production Ready: Deploy models as API endpoints on Ultralytics Platform with auto-scaling and monitoring, or run inference locally.

Key Features of Predict Mode

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

  • Multiple Data Source Compatibility: Whether your data is in the form of individual images, a collection of images, video files, or real-time video streams, predict mode has you covered.
  • Streaming Mode: Use the streaming feature to generate a memory-efficient generator of Results objects. Enable this by setting stream=True in the predictor's call method.
  • Batch Processing: Process multiple images or video frames in a single batch, further reducing total inference time.
  • Integration Friendly: Easily integrate with existing data pipelines and other software components, thanks to its flexible API.

Ultralytics YOLO models return either a Python list of Results objects or a memory-efficient generator of Results objects when stream=True is passed to the model during inference:

!!! example "Predict"

=== "Return a list with `stream=False`"

    ```python
    from ultralytics import YOLO

    # Load a model
    model = YOLO("yolo26n.pt")  # pretrained YOLO26n 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
    ```

=== "Return a generator with `stream=True`"

    ```python
    from ultralytics import YOLO

    # Load a model
    model = YOLO("yolo26n.pt")  # pretrained YOLO26n 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
    ```

Inference Sources

YOLO26 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 ✅. Streaming mode is beneficial for processing videos or live streams as it creates a generator of results instead of loading all frames into memory.

!!! tip

Use `stream=True` for processing long videos or large datasets to efficiently manage memory. When `stream=False`, the results for all frames or data points are stored in memory, which can quickly add up and cause out-of-memory errors for large inputs. In contrast, `stream=True` utilizes a generator, which only keeps the results of the current frame or data point in memory, significantly reducing memory consumption and preventing out-of-memory issues.
SourceExampleTypeNotes
image'image.jpg'str or PathSingle image file.
URL'https://ultralytics.com/images/bus.jpg'strURL to an image.
screenshot'screen'strCapture a screenshot.
PILImage.open('image.jpg')PIL.ImageHWC format with RGB channels.
OpenCVcv2.imread('image.jpg')np.ndarrayHWC format with BGR channels uint8 (0-255).
numpynp.zeros((640,1280,3))np.ndarrayHWC format with BGR channels uint8 (0-255).
torchtorch.zeros(16,3,320,640)torch.TensorBCHW format with RGB channels float32 (0.0-1.0).
CSV'sources.csv'str or PathCSV file containing paths to images, videos, or directories.
video ✅'video.mp4'str or PathVideo file in formats like MP4, AVI, etc.
directory ✅'path/'str or PathPath to a directory containing images or videos.
glob ✅'path/*.jpg'strGlob pattern to match multiple files. Use the * character as a wildcard.
YouTube ✅'https://youtu.be/LNwODJXcvt4'strURL to a YouTube video.
stream ✅'rtsp://example.com/media.mp4'strURL for streaming protocols such as RTSP, RTMP, TCP, or an IP address.
multi-stream ✅'list.streams'str or Path*.streams text file with one stream URL per row, i.e., 8 streams will run at batch-size 8.
webcam ✅0intIndex of the connected camera device to run inference on.

Below are code examples for using each source type:

!!! example "Prediction sources"

=== "image"

    Run inference on an image file.
    ```python
    from ultralytics import YOLO

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

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

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

=== "screenshot"

    Run inference on the current screen content as a screenshot.
    ```python
    from ultralytics import YOLO

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

    # Define current screenshot as source
    source = "screen"

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

=== "URL"

    Run inference on an image or video hosted remotely via URL.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "PIL"

    Run inference on an image opened with Python Imaging Library (PIL).
    ```python
    from PIL import Image

    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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"

    Run inference on an image read with OpenCV.
    ```python
    import cv2

    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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"

    Run inference on an image represented as a numpy array.
    ```python
    import numpy as np

    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "torch"

    Run inference on an image represented as a [PyTorch](https://www.ultralytics.com/glossary/pytorch) tensor.
    ```python
    import torch

    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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"

    Run inference on a collection of images, URLs, videos, and directories listed in a CSV file.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "video"

    Run inference on a video file. By using `stream=True`, you can create a generator of Results objects to reduce memory usage.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "directory"

    Run inference on all images and videos in a directory. To include assets in subdirectories, use a glob pattern such as `path/to/dir/**/*`.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "glob"

    Run inference on all images and videos that match a glob expression with `*` characters.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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"

    Run inference on a YouTube video. By using `stream=True`, you can create a generator of Results objects to reduce memory usage for long videos.
    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

=== "Stream"

    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](https://www.ultralytics.com/glossary/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).

    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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.

=== "Multi-Stream"

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

    ```python
    from ultralytics import YOLO

    # Load a pretrained YOLO26n model
    model = YOLO("yolo26n.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
    ```

    Example `.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.

=== "Webcam"

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

    ```python
    from ultralytics import YOLO

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

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

Inference Arguments

model.predict() accepts multiple arguments that can be passed at inference time to override defaults:

!!! note

Ultralytics uses minimal padding during inference by default (`rect=True`). In this mode, the shorter side of each image is padded only as much as needed to make it divisible by the model's maximum stride, rather than padding it all the way to the full `imgsz`. When running inference on a batch of images, minimal padding only works if all images have identical size. Otherwise, images are uniformly padded to a square shape with both sides equal to `imgsz`.

- `batch=1`, using `rect` padding by default.
- `batch>1`, using `rect` padding only if all the images in one batch have identical size, otherwise using square padding to `imgsz`.

!!! example

=== "Python"

    ```python
    from ultralytics import YOLO

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

    # Run inference on 'bus.jpg' with arguments
    model.predict("https://ultralytics.com/images/bus.jpg", save=True, imgsz=320, conf=0.25)
    ```

=== "CLI"

    ```bash
    # Run inference on 'bus.jpg'
    yolo predict model=yolo26n.pt source='https://ultralytics.com/images/bus.jpg'
    ```

Inference arguments:

{% include "macros/predict-args.md" %}

Visualization arguments:

{% from "macros/visualization-args.md" import param_table %} {{ param_table() }}

Image and Video Formats

YOLO26 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.

Images

The below table contains valid Ultralytics image formats.

!!! note

HEIC/HEIF formats require `pi-heif`, which is installed automatically on first use. AVIF is supported natively by Pillow.
Image SuffixesExample Predict CommandReference
.avifyolo predict source=image.avifAV1 Image File Format
.bmpyolo predict source=image.bmpMicrosoft BMP File Format
.dngyolo predict source=image.dngAdobe DNG
.heicyolo predict source=image.heicHigh Efficiency Image Format
.heifyolo predict source=image.heifHigh Efficiency Image Format
.jp2yolo predict source=image.jp2JPEG 2000
.jpegyolo predict source=image.jpegJPEG
.jpgyolo predict source=image.jpgJPEG
.mpoyolo predict source=image.mpoMulti Picture Object
.pngyolo predict source=image.pngPortable Network Graphics
.tifyolo predict source=image.tifTag Image File Format
.tiffyolo predict source=image.tiffTag Image File Format
.webpyolo predict source=image.webpWebP

Videos

The below table contains valid Ultralytics video formats.

Video SuffixesExample Predict CommandReference
.asfyolo predict source=video.asfAdvanced Systems Format
.aviyolo predict source=video.aviAudio Video Interleave
.gifyolo predict source=video.gifGraphics Interchange Format
.m4vyolo predict source=video.m4vMPEG-4 Part 14
.mkvyolo predict source=video.mkvMatroska
.movyolo predict source=video.movQuickTime File Format
.mp4yolo predict source=video.mp4MPEG-4 Part 14 - Wikipedia
.mpegyolo predict source=video.mpegMPEG-1 Part 2
.mpgyolo predict source=video.mpgMPEG-1 Part 2
.tsyolo predict source=video.tsMPEG Transport Stream
.wmvyolo predict source=video.wmvWindows Media Video
.webmyolo predict source=video.webmWebM Project

Working with Results

All Ultralytics predict() calls will return a list of Results objects:

!!! example "Results"

```python
from ultralytics import YOLO

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

# Run inference on an image
results = model("https://ultralytics.com/images/bus.jpg")
results = model(
    [
        "https://ultralytics.com/images/bus.jpg",
        "https://ultralytics.com/images/zidane.jpg",
    ]
)  # batch inference
```

Results objects have the following attributes:

AttributeTypeDescription
orig_imgnp.ndarrayThe original image as a numpy array.
orig_shapetupleThe original image shape in (height, width) format.
boxesBoxes, optionalA Boxes object containing the detection bounding boxes.
masksMasks, optionalA Masks object containing the detection masks.
probsProbs, optionalA Probs object containing probabilities of each class for classification task.
keypointsKeypoints, optionalA Keypoints object containing detected keypoints for each object.
obbOBB, optionalAn OBB object containing oriented bounding boxes.
speeddictA dictionary of preprocess, inference, and postprocess speeds in milliseconds per image.
namesdictA dictionary mapping class indices to class names.
pathstrThe path to the image file.
save_dirstr, optionalDirectory to save results.

Results objects have the following methods:

MethodReturn TypeDescription
update()NoneUpdates the Results object with new detection data (boxes, masks, probs, obb, keypoints).
cpu()ResultsReturns a copy of the Results object with all tensors moved to CPU memory.
numpy()ResultsReturns a copy of the Results object with all tensors converted to numpy arrays.
cuda()ResultsReturns a copy of the Results object with all tensors moved to GPU memory.
to()ResultsReturns a copy of the Results object with tensors moved to specified device and dtype.
new()ResultsCreates a new Results object with the same image, path, names, and speed attributes.
plot()np.ndarrayPlots detection results on an input RGB image and returns the annotated image.
show()NoneDisplays the image with annotated inference results.
save()strSaves annotated inference results image to file and returns the filename.
verbose()strReturns a log string for each task, detailing detection and classification outcomes.
save_txt()strSaves detection results to a text file and returns the path to the saved file.
save_crop()NoneSaves cropped detection images to specified directory.
summary()List[Dict[str, Any]]Converts inference results to a summarized dictionary with optional normalization.
to_df()DataFrameConverts detection results to a Polars DataFrame.
to_csv()strConverts detection results to CSV format.
to_json()strConverts detection results to JSON format.

For more details see the Results class documentation.

Boxes

Boxes object can be used to index, manipulate, and convert bounding boxes to different formats.

!!! example "Boxes"

```python
from ultralytics import YOLO

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

# Run inference on an image
results = model("https://ultralytics.com/images/bus.jpg")  # results list

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

Here is a table for the Boxes class methods and properties, including their name, type, and description:

NameTypeDescription
cpu()MethodMove the object to CPU memory.
numpy()MethodConvert the object to a numpy array.
cuda()MethodMove the object to CUDA memory.
to()MethodMove the object to the specified device.
xyxyProperty (torch.Tensor)Return the boxes in xyxy format.
confProperty (torch.Tensor)Return the confidence values of the boxes.
clsProperty (torch.Tensor)Return the class values of the boxes.
idProperty (torch.Tensor)Return the track IDs of the boxes (if available).
xywhProperty (torch.Tensor)Return the boxes in xywh format.
xyxynProperty (torch.Tensor)Return the boxes in xyxy format normalized by original image size.
xywhnProperty (torch.Tensor)Return the boxes in xywh format normalized by original image size.

For more details see the Boxes class documentation.

Masks

Masks object can be used to index, manipulate and convert masks to segments.

!!! example "Masks"

```python
from ultralytics import YOLO

# Load a pretrained YOLO26n-seg Segment model
model = YOLO("yolo26n-seg.pt")

# Run inference on an image
results = model("https://ultralytics.com/images/bus.jpg")  # results list

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

Here is a table for the Masks class methods and properties, including their name, type, and description:

NameTypeDescription
cpu()MethodReturns the masks tensor on CPU memory.
numpy()MethodReturns the masks tensor as a numpy array.
cuda()MethodReturns the masks tensor on GPU memory.
to()MethodReturns the masks tensor with the specified device and dtype.
xynProperty (torch.Tensor)A list of normalized segments represented as tensors.
xyProperty (torch.Tensor)A list of segments in pixel coordinates represented as tensors.

For more details see the Masks class documentation.

Keypoints

Keypoints object can be used to index, manipulate and normalize coordinates.

!!! example "Keypoints"

```python
from ultralytics import YOLO

# Load a pretrained YOLO26n-pose Pose model
model = YOLO("yolo26n-pose.pt")

# Run inference on an image
results = model("https://ultralytics.com/images/bus.jpg")  # results list

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

Here is a table for the Keypoints class methods and properties, including their name, type, and description:

NameTypeDescription
cpu()MethodReturns the keypoints tensor on CPU memory.
numpy()MethodReturns the keypoints tensor as a numpy array.
cuda()MethodReturns the keypoints tensor on GPU memory.
to()MethodReturns the keypoints tensor with the specified device and dtype.
xynProperty (torch.Tensor)A list of normalized keypoints represented as tensors.
xyProperty (torch.Tensor)A list of keypoints in pixel coordinates represented as tensors.
confProperty (torch.Tensor)Returns confidence values of keypoints if available, else None.

For more details see the Keypoints class documentation.

Probs

Probs object can be used index, get top1 and top5 indices and scores of classification.

!!! example "Probs"

```python
from ultralytics import YOLO

# Load a pretrained YOLO26n-cls Classify model
model = YOLO("yolo26n-cls.pt")

# Run inference on an image
results = model("https://ultralytics.com/images/bus.jpg")  # results list

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

Here's a table summarizing the methods and properties for the Probs class:

NameTypeDescription
cpu()MethodReturns a copy of the probs tensor on CPU memory.
numpy()MethodReturns a copy of the probs tensor as a numpy array.
cuda()MethodReturns a copy of the probs tensor on GPU memory.
to()MethodReturns a copy of the probs tensor with the specified device and dtype.
top1Property (int)Index of the top 1 class.
top5Property (list[int])Indices of the top 5 classes.
top1confProperty (torch.Tensor)Confidence of the top 1 class.
top5confProperty (torch.Tensor)Confidences of the top 5 classes.

For more details see the Probs class documentation.

OBB

OBB object can be used to index, manipulate, and convert oriented bounding boxes to different formats.

!!! example "OBB"

```python
from ultralytics import YOLO

# Load a pretrained YOLO26n model
model = YOLO("yolo26n-obb.pt")

# Run inference on an image
results = model("https://ultralytics.com/images/boats.jpg")  # results list

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

Here is a table for the OBB class methods and properties, including their name, type, and description:

NameTypeDescription
cpu()MethodMove the object to CPU memory.
numpy()MethodConvert the object to a numpy array.
cuda()MethodMove the object to CUDA memory.
to()MethodMove the object to the specified device.
confProperty (torch.Tensor)Return the confidence values of the boxes.
clsProperty (torch.Tensor)Return the class values of the boxes.
idProperty (torch.Tensor)Return the track IDs of the boxes (if available).
xyxyProperty (torch.Tensor)Return the horizontal boxes in xyxy format.
xywhrProperty (torch.Tensor)Return the rotated boxes in xywhr format.
xyxyxyxyProperty (torch.Tensor)Return the rotated boxes in xyxyxyxy format.
xyxyxyxynProperty (torch.Tensor)Return the rotated boxes in xyxyxyxy format normalized by image size.

For more details see the OBB class documentation.

Plotting Results

The plot() method in Results objects facilitates visualization of predictions by overlaying detected objects (such as bounding boxes, masks, keypoints, and probabilities) onto the original image. This method returns the annotated image as a NumPy array, allowing for easy display or saving.

!!! example "Plotting"

```python
from PIL import Image

from ultralytics import YOLO

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

# Run inference on 'bus.jpg'
results = model(["https://ultralytics.com/images/bus.jpg", "https://ultralytics.com/images/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() Method Parameters

The plot() method supports various arguments to customize the output:

ArgumentTypeDescriptionDefault
confboolInclude detection confidence scores.True
line_widthfloatLine width of bounding boxes. Scales with image size if None.None
font_sizefloatText font size. Scales with image size if None.None
fontstrFont name for text annotations.'Arial.ttf'
pilboolReturn image as a PIL Image object.False
imgnp.ndarrayAlternative image for plotting. Uses the original image if None.None
im_gputorch.TensorGPU-accelerated image for faster mask plotting. Shape: (1, 3, 640, 640).None
kpt_radiusintRadius for drawn keypoints.5
kpt_lineboolConnect keypoints with lines.True
labelsboolInclude class labels in annotations.True
boxesboolOverlay bounding boxes on the image.True
masksboolOverlay masks on the image.True
probsboolInclude classification probabilities.True
showboolDisplay the annotated image directly using the default image viewer.False
saveboolSave the annotated image to a file specified by filename.False
filenamestrPath and name of the file to save the annotated image if save is True.None
color_modestrSpecify the color mode, e.g., 'instance' or 'class'.'class'
txt_colortuple[int, int, int]RGB text color for bounding box and image classification label.(255, 255, 255)

Thread-Safe Inference

Ensuring thread safety during inference is crucial when you are running multiple YOLO models in parallel across different threads. Thread-safe inference guarantees that each thread's predictions are isolated and do not interfere with one another, avoiding race conditions and ensuring consistent and reliable outputs.

When using YOLO models in a multi-threaded application, it's important to instantiate separate model objects for each thread or employ thread-local storage to prevent conflicts:

!!! example "Thread-Safe Inference"

Instantiate a single model inside each thread for thread-safe inference:
```python
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=("yolo26n.pt", "image1.jpg")).start()
Thread(target=thread_safe_predict, args=("yolo26n.pt", "image2.jpg")).start()
```

For an in-depth look at thread-safe inference with YOLO models and step-by-step instructions, please refer to our YOLO Thread-Safe Inference Guide. This guide will provide you with all the necessary information to avoid common pitfalls and ensure that your multi-threaded inference runs smoothly.

Streaming Source for-loop

Here's a Python script using OpenCV (cv2) and YOLO to run inference on video frames. This script assumes you have already installed the necessary packages (opencv-python and ultralytics).

!!! example "Streaming for-loop"

```python
import cv2

from ultralytics import YOLO

# Load the YOLO model
model = YOLO("yolo26n.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()
```

This script will run predictions on each frame of the video, visualize the results, and display them in a window. The loop can be exited by pressing 'q'.

FAQ

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() call. For example, use 'image.jpg' for a local image or 'https://ultralytics.com/images/bus.jpg' for a URL. Check out the detailed examples for various inference sources in the documentation.

How do I optimize YOLO inference speed and memory usage?

To optimize inference speed and manage memory efficiently, you can use the streaming mode by setting stream=True in the predictor's call method. The streaming mode generates a memory-efficient generator of Results objects instead of loading all frames into memory. For processing long videos or large datasets, streaming mode is particularly useful. Learn more about streaming mode.

What inference arguments does Ultralytics YOLO support?

The model.predict() method in YOLO supports various arguments such as conf, iou, imgsz, device, and more. These arguments allow you to customize the inference process, setting parameters like confidence thresholds, image size, and the device used for computation. Detailed descriptions of these arguments can be found in the inference arguments section.

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

After running inference with YOLO, the Results objects contain methods for displaying and saving annotated images. You can use methods like result.show() and result.save(filename="result.jpg") to visualize and save the results. Any missing parent directories in the filename path are created automatically (e.g., result.save("path/to/result.jpg")). For a comprehensive list of these methods, refer to the working with results section.