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 可以处理不同类型的输入源以进行推理。这些源包括静态图像、视频流和各种数据格式。该表还指示了每个源是否可以在流模式下与参数一起使用 stream=True ✅。流模式有利于处理视频或直播流,因为它会创建一个结果生成器,而不是将所有帧加载到内存中。
使用 stream=True 用于处理长视频或大型数据集,以有效管理内存。当 stream=False时,所有帧或数据点的结果都存储在内存中,这会迅速累积,并导致大型输入出现内存不足错误。相反, stream=True 采用生成器,仅将当前帧或数据点的结果保存在内存中,从而显著降低内存消耗并防止内存溢出问题。
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
对表示为 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,您可以创建一个 Results 对象生成器来减少内存使用。
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
对目录中的所有图像和视频运行推理。要同时捕获子目录中的图像和视频,请使用 glob 模式,例如 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
对所有与 glob 表达式匹配的图像和视频运行推理 * 字符。
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
使用流模式,通过 RTSP、RTMP、TCP 或 IP 地址协议在实时视频流上运行推理。如果提供单个流,模型将以 批次大小 为 1 的 batch-size 运行推理。对于多个流,可以使用 .streams 文本文件来执行批量推理,其中批量大小由提供的流的数量决定(例如,8 个流的批量大小为 8)。
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
对于单流使用,批量大小默认设置为 1,从而可以高效地实时处理视频流。
要同时处理多个视频流,请使用包含流媒体源的 .streams 文本文件。模型将运行批量推理,其中批量大小等于流的数量。此设置可以高效地并发处理多个源。
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 文本文件:
rtsp://example.com/media1.mp4
rtsp://example.com/media2.mp4
rtmp://example2.com/live
tcp://192.168.1.100:554
文件中的每一行代表一个流媒体源,允许您同时监控多个视频流并对其执行推理。
您可以通过将特定摄像头的索引传递给 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
# Run inference on 'bus.jpg' with arguments
model.predict("https://ultralytics.com/images/bus.jpg", save=True, imgsz=320, conf=0.5)
推理参数:
'ultralytics/assets'
指定推理的数据源。可以是图像路径、视频文件、目录、URL 或实时馈送的设备 ID。 支持多种格式和来源,从而可以在不同类型的输入上灵活应用。
float
设置检测的最小置信度阈值。 将忽略置信度低于此阈值的检测到的对象。 调整此值有助于减少误报。
float
用于非极大值抑制 (NMS) 的 Intersection Over Union (IoU) 阈值。较低的值会通过消除重叠的框来减少检测结果,这对于减少重复项很有用。
imgsz
int 或 tuple
定义推理的图像大小。可以是一个整数 640 表示正方形调整大小,也可以是 (height, width) 元组。适当的大小调整可以提高检测 准确性 和处理速度。
如果启用,则对图像较短的一边进行最小填充,直到可以被步长整除,以提高推理速度。如果禁用,则在推理期间将图像填充为正方形。
False
启用半精度 (FP16) 推理,这可以加快在支持的 GPU 上的模型推理速度,同时对准确性的影响极小。
device
指定用于推理的设备(例如, cpu, cuda:0 或 0)。允许用户在 CPU、特定 GPU 或其他计算设备之间进行选择,以执行模型。
batch
指定推理的批处理大小(仅在源为以下情况时有效: 目录、视频文件或 .txt 文件)。更大的批处理大小可以提供更高的吞吐量,从而缩短推理所需的总时间。
max_det
每张图像允许的最大检测数量。限制模型在单次推理中可以检测到的对象总数,防止在密集场景中产生过多的输出。
vid_stride
视频输入的帧步长。允许跳过视频中的帧,以加快处理速度,但会降低时间分辨率。值为 1 时处理每一帧,值越高跳过的帧越多。
stream_buffer
False
确定是否为视频流排队传入帧。如果 False,旧帧会被丢弃以适应新帧(针对实时应用进行了优化)。如果 True,在缓冲区中对新帧进行排队,确保不跳过任何帧,但如果推理 FPS 低于流 FPS,则会导致延迟。
visualize
False
激活推理期间模型特征的可视化,从而深入了解模型正在“看到”的内容。这对于调试和模型解释非常有用。
augment
False
启用测试时增强 (TTA) 进行预测,可能会提高检测的鲁棒性,但会降低推理速度。
agnostic_nms
False
启用与类别无关的非极大值抑制 (NMS),它会合并不同类别的重叠框。在类别重叠很常见的多类别检测场景中非常有用。
classes
list[int]
将预测结果筛选到一组类别 ID。只会返回属于指定类别的检测结果。这对于专注于多类别检测任务中的相关对象非常有用。
retina_masks
False
返回高分辨率分割掩码。返回的掩码(masks.data)如果启用,将与原始图像大小匹配。如果禁用,它们将具有推理期间使用的图像大小。
embed
list[int]
指定从中提取特征向量或 embeddings 的层。对于诸如聚类或相似性搜索之类的下游任务非常有用。
project
如果 save 已启用,则为保存预测输出的项目目录的名称。
预测运行的名称。用于在项目文件夹中创建一个子目录,如果 save 已启用,则为保存预测输出的项目目录的名称。
stream
False
通过返回 Results 对象的生成器而不是一次将所有帧加载到内存中,从而为长视频或大量图像启用内存高效处理。
verbose
控制是否在终端中显示详细的推理日志,从而提供有关预测过程的实时反馈。
compile
False
启用PyTorch 2.x torch.compile 图编译以优化模型执行。适用于支持的设备CUDAMPS)。使用方法 backend='inductor', mode='max-autotune'.如果不支持,则退回急切模式并发出警告。
已启用,则预测输出存储在该子目录中。
False or True
启用将带注释的图像或视频保存到文件。这对于文档编制、进一步分析或共享结果非常有用。使用 CLI 时默认为 True,在 python 中使用时默认为 False。
save_frames
False
处理视频时,将各个帧另存为图像。这对于提取特定帧或进行详细的逐帧分析非常有用。
save_txt
False
以文本文件格式保存检测结果,格式如下: [class] [x_center] [y_center] [width] [height] [confidence]。 有助于与其他分析工具集成。
save_conf
False
在保存的文本文件中包含置信度分数。 增强了可用于后处理和分析的细节。
save_crop
False
保存检测到的裁剪图像。 有助于数据集增强、分析或为特定对象创建重点数据集。
show_labels
在可视化输出中显示每个检测的标签。 能够立即理解检测到的对象。
show_conf
在标签旁边显示每个检测的置信度分数。 可以深入了解模型对每次检测的确定性。
show_boxes
在检测到的对象周围绘制边界框。 这对于在图像或视频帧中以可视方式识别和定位对象至关重要。
line_width
None or int
指定边界框的线条宽度。 如果 None,则线条宽度会根据图像大小自动调整。 提供视觉自定义以提高清晰度。
YOLO11 支持各种图像和视频格式,如 ultralytics/data/utils.py 中所指定。请参见下表,了解有效的后缀和示例预测命令。
下表包含有效的 Ultralytics 图像格式。
HEIC 图像仅支持推理,不支持训练。
# 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 对象具有以下属性:
# 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
以下是 Boxes 类的方法和属性表,包括它们的名称、类型和描述:
# 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
以下是 Masks 类的方法和属性表,包括它们的名称、类型和描述:
# 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
以下是 Keypoints 类的方法和属性表,包括它们的名称、类型和描述:
# 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
下表总结了以下方法的属性: Probs 函数:
# 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
以下是 OBB 类的方法和属性表,包括它们的名称、类型和描述:
有关更多详细信息,请参见 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(["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() 方法参数
字段 plot() 方法支持各种参数来自定义输出:
线程安全推理
当您在不同线程中并行运行多个 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 (cv2) 和 YOLO 运行视频帧推理的 python 脚本。此脚本假定您已安装必要的软件包 (opencv-python 和 ultralytics)。
流式 for 循环
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”退出循环。
什么是 Ultralytics YOLO 及其用于实时推理的预测模式?
Ultralytics YOLO 是一种最先进的实时