使用 Ultralytics YOLO 进行模型预测
简介
在机器学习和计算机视觉领域,从视觉数据中理解信息的过程被称为“推理”或“预测”。Ultralytics YOLO11 提供了一个强大的功能,称为预测模式,该模式专为在各种数据源上进行高性能、实时推理而定制。
观看: 如何从 Ultralytics YOLO 模型中提取输出以用于自定义项目。
实际应用
制造业 | 体育 | 安全性 |
---|---|---|
车辆备件检测 | 足球运动员检测 | 人员跌倒检测 |
为什么使用 Ultralytics YOLO 进行推理?
以下是您应考虑使用 YOLO11 预测模式来满足各种推理需求的原因:
- 多功能性: 能够对图像、视频甚至直播流进行推理。
- 性能: 专为实时、高速处理而设计,且不牺牲准确性。
- 易于使用: 直观的 Python 和 CLI 界面,可实现快速部署和测试。
- 高度可定制: 提供各种设置和参数,可根据您的特定要求调整模型的推理行为。
预测模式的主要特性
YOLO11 的预测模式设计强大且用途广泛,具有以下特点:
- 多种数据源兼容性: 无论您的数据是单个图像、图像集合、视频文件还是实时视频流,预测模式都能满足您的需求。
- 流模式: 使用流式传输功能可以生成一个内存高效的
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 可以处理不同类型的输入源以进行推理。这些源包括静态图像、视频流和各种数据格式。该表还指示了每个源是否可以在流模式下与参数一起使用 stream=True
✅。流模式有利于处理视频或直播流,因为它会创建一个结果生成器,而不是将所有帧加载到内存中。
提示
使用 stream=True
用于处理长视频或大型数据集,以有效管理内存。当 stream=False
时,所有帧或数据点的结果都存储在内存中,这会迅速累积,并导致大型输入出现内存不足错误。相反, stream=True
采用生成器,仅将当前帧或数据点的结果保存在内存中,从而显著降低内存消耗并防止内存溢出问题。
来源 | 示例 | 类型 | 备注 |
---|---|---|---|
图像 | 'image.jpg' |
str 或 Path |
单个图像文件。 |
URL | 'https://ultralytics.com/images/bus.jpg' |
str |
图像的URL。 |
截图 | 'screen' |
str |
截取屏幕截图。 |
PIL | Image.open('image.jpg') |
PIL.Image |
具有RGB通道的HWC格式。 |
OpenCV | cv2.imread('image.jpg') |
np.ndarray |
具有BGR通道的HWC格式 uint8 (0-255) . |
numpy | np.zeros((640,1280,3)) |
np.ndarray |
具有BGR通道的HWC格式 uint8 (0-255) . |
torch | torch.zeros(16,3,320,640) |
torch.Tensor |
具有RGB通道的BCHW格式 float32 (0.0-1.0) . |
CSV | 'sources.csv' |
str 或 Path |
包含图像、视频或目录路径的CSV文件。 |
视频 ✅ | 'video.mp4' |
str 或 Path |
MP4、AVI等格式的视频文件。 |
目录 ✅ | 'path/' |
str 或 Path |
包含图像或视频的目录的路径。 |
glob ✅ | 'path/*.jpg' |
str |
用于匹配多个文件的Glob模式。使用 * 字符作为通配符。 |
YouTube ✅ | 'https://youtu.be/LNwODJXcvt4' |
str |
YouTube视频的URL。 |
流 ✅ | 'rtsp://example.com/media.mp4' |
str |
用于流媒体协议的URL,例如RTSP、RTMP、TCP或IP地址。 |
多流 ✅ | 'list.streams' |
str 或 Path |
*.streams 包含每行一个流 URL 的文本文件,例如,8 个流将以 batch-size 8 运行。 |
网络摄像头 ✅ | 0 |
int |
用于运行推理的已连接摄像头设备的索引。 |
以下是使用每种来源类型的代码示例:
预测来源
对图像文件运行推理。
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 图像库 (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
对表示为 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
推理参数
model.predict()
来在连接的摄像头设备上运行推理。
示例
from ultralytics import YOLO
# Load a pretrained YOLO11n model
model = YOLO("yolo11n.pt")
# Run inference on 'bus.jpg' with arguments
model.predict("https://ultralytics.com/images/bus.jpg", save=True, imgsz=320, conf=0.5)
推理参数:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
source |
str |
'ultralytics/assets' |
指定推理的数据源。可以是图像路径、视频文件、目录、URL 或实时馈送的设备 ID。 支持多种格式和来源,从而可以在不同类型的输入上灵活应用。 |
conf |
float |
0.25 |
设置检测的最小置信度阈值。 将忽略置信度低于此阈值的检测到的对象。 调整此值有助于减少误报。 |
iou |
float |
0.7 |
用于非极大值抑制 (NMS) 的 Intersection Over Union (IoU) 阈值。较低的值会通过消除重叠的框来减少检测结果,这对于减少重复项很有用。 |
imgsz |
int 或 tuple |
640 |
定义推理的图像大小。可以是一个整数 640 表示正方形调整大小,也可以是 (height, width) 元组。适当的大小调整可以提高检测 准确性 和处理速度。 |
rect |
bool |
True |
如果启用,则对图像较短的一边进行最小填充,直到可以被步长整除,以提高推理速度。如果禁用,则在推理期间将图像填充为正方形。 |
half |
bool |
False |
启用半精度 (FP16) 推理,这可以加快在支持的 GPU 上的模型推理速度,同时对准确性的影响极小。 |
device |
str |
None |
指定用于推理的设备(例如, cpu , cuda:0 或 0 )。允许用户在 CPU、特定 GPU 或其他计算设备之间进行选择,以执行模型。 |
batch |
int |
1 |
指定推理的批处理大小(仅在源为以下情况时有效: 目录、视频文件或 .txt 文件)。更大的批处理大小可以提供更高的吞吐量,从而缩短推理所需的总时间。 |
max_det |
int |
300 |
每张图像允许的最大检测数量。限制模型在单次推理中可以检测到的对象总数,防止在密集场景中产生过多的输出。 |
vid_stride |
int |
1 |
视频输入的帧步长。允许跳过视频中的帧,以加快处理速度,但会降低时间分辨率。值为 1 时处理每一帧,值越高跳过的帧越多。 |
stream_buffer |
bool |
False |
确定是否为视频流排队传入帧。如果 False ,旧帧会被丢弃以适应新帧(针对实时应用进行了优化)。如果 True ,在缓冲区中对新帧进行排队,确保不跳过任何帧,但如果推理 FPS 低于流 FPS,则会导致延迟。 |
visualize |
bool |
False |
激活推理期间模型特征的可视化,从而深入了解模型正在“看到”的内容。这对于调试和模型解释非常有用。 |
augment |
bool |
False |
启用测试时增强 (TTA) 进行预测,可能会提高检测的鲁棒性,但会降低推理速度。 |
agnostic_nms |
bool |
False |
启用与类别无关的非极大值抑制 (NMS),它会合并不同类别的重叠框。在类别重叠很常见的多类别检测场景中非常有用。 |
classes |
list[int] |
None |
将预测结果筛选到一组类别 ID。只会返回属于指定类别的检测结果。这对于专注于多类别检测任务中的相关对象非常有用。 |
retina_masks |
bool |
False |
返回高分辨率分割掩码。返回的掩码(masks.data )如果启用,将与原始图像大小匹配。如果禁用,它们将具有推理期间使用的图像大小。 |
embed |
list[int] |
None |
指定从中提取特征向量或 embeddings 的层。对于诸如聚类或相似性搜索之类的下游任务非常有用。 |
project |
str |
None |
如果 save 已启用,则为保存预测输出的项目目录的名称。 |
name |
str |
None |
预测运行的名称。用于在项目文件夹中创建一个子目录,如果 save 已启用,则为保存预测输出的项目目录的名称。 |
stream |
bool |
False |
通过返回 Results 对象的生成器而不是一次将所有帧加载到内存中,从而为长视频或大量图像启用内存高效处理。 |
verbose |
bool |
True |
控制是否在终端中显示详细的推理日志,从而提供有关预测过程的实时反馈。 |
已启用,则预测输出存储在该子目录中。
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
show |
bool |
False |
可视化参数: True ,则在窗口中显示带注释的图像或视频。这对于开发或测试期间的即时视觉反馈非常有用。 |
save |
bool |
False or True |
启用将带注释的图像或视频保存到文件。这对于文档编制、进一步分析或共享结果非常有用。使用 CLI 时默认为 True,在 python 中使用时默认为 False。 |
save_frames |
bool |
False |
处理视频时,将各个帧另存为图像。这对于提取特定帧或进行详细的逐帧分析非常有用。 |
save_txt |
bool |
False |
以文本文件格式保存检测结果,格式如下: [class] [x_center] [y_center] [width] [height] [confidence] 。 有助于与其他分析工具集成。 |
save_conf |
bool |
False |
在保存的文本文件中包含置信度分数。 增强了可用于后处理和分析的细节。 |
save_crop |
bool |
False |
保存检测到的裁剪图像。 有助于数据集增强、分析或为特定对象创建重点数据集。 |
show_labels |
bool |
True |
在可视化输出中显示每个检测的标签。 能够立即理解检测到的对象。 |
show_conf |
bool |
True |
在标签旁边显示每个检测的置信度分数。 可以深入了解模型对每次检测的确定性。 |
show_boxes |
bool |
True |
在检测到的对象周围绘制边界框。 这对于在图像或视频帧中以可视方式识别和定位对象至关重要。 |
line_width |
None or int |
None |
指定边界框的线条宽度。 如果 None ,则线条宽度会根据图像大小自动调整。 提供视觉自定义以提高清晰度。 |
图像和视频格式
YOLO11 支持各种图像和视频格式,如 ultralytics/data/utils.py 中所指定。请参见下表,了解有效的后缀和示例预测命令。
图像
下表包含有效的 Ultralytics 图像格式。
注意
HEIC 图像仅支持推理,不支持训练。
图像后缀 | 示例预测命令 | 参考 |
---|---|---|
.bmp |
yolo predict source=image.bmp |
Microsoft BMP 文件格式 |
.dng |
yolo predict source=image.dng |
Adobe DNG |
.jpeg |
yolo predict source=image.jpeg |
JPEG |
.jpg |
yolo predict source=image.jpg |
JPEG |
.mpo |
yolo predict source=image.mpo |
多图片对象 |
.png |
yolo predict source=image.png |
便携式网络图形 |
.tif |
yolo predict source=image.tif |
标签图像文件格式 |
.tiff |
yolo predict source=image.tiff |
标签图像文件格式 |
.webp |
yolo predict source=image.webp |
WebP |
.pfm |
yolo predict source=image.pfm |
便携式浮点图 |
.HEIC |
yolo predict source=image.HEIC |
高效率图像格式 |
视频
下表包含有效的 Ultralytics 视频格式。
视频后缀 | 示例预测命令 | 参考 |
---|---|---|
.asf |
yolo predict source=video.asf |
高级系统格式 |
.avi |
yolo predict source=video.avi |
音视频交错格式 |
.gif |
yolo predict source=video.gif |
图像互换格式 |
.m4v |
yolo predict source=video.m4v |
MPEG-4 Part 14 |
.mkv |
yolo predict source=video.mkv |
Matroska |
.mov |
yolo predict source=video.mov |
QuickTime 文件格式 |
.mp4 |
yolo predict source=video.mp4 |
MPEG-4 Part 14 - 维基百科 |
.mpeg |
yolo predict source=video.mpeg |
MPEG-1 Part 2 |
.mpg |
yolo predict source=video.mpg |
MPEG-1 Part 2 |
.ts |
yolo predict source=video.ts |
MPEG 传输流 |
.wmv |
yolo predict source=video.wmv |
Windows Media 视频 |
.webm |
yolo predict source=video.webm |
WebM 项目 |
处理结果
所有 Ultralytics predict()
调用将返回一个 Results
对象列表:
结果
from ultralytics import YOLO
# Load a pretrained YOLO11n model
model = YOLO("yolo11n.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
对象具有以下属性:
属性 | 类型 | 描述 |
---|---|---|
orig_img |
np.ndarray |
原始图像,以 numpy 数组形式呈现。 |
orig_shape |
tuple |
原始图像的形状,格式为(高度,宽度)。 |
boxes |
Boxes, optional |
一个 Boxes 对象,包含检测到的边界框。 |
masks |
Masks, optional |
一个 Masks 对象,包含检测到的掩码。 |
probs |
Probs, optional |
一个 Probs 对象,包含分类任务中每个类别的概率。 |
keypoints |
Keypoints, optional |
一个 Keypoints 对象,包含每个对象检测到的关键点。 |
obb |
OBB, optional |
包含旋转框检测的 OBB 对象。 |
speed |
dict |
一个字典,包含预处理、推理和后处理的速度,单位为毫秒/图像。 |
names |
dict |
一个将类索引映射到类名称的字典。 |
path |
str |
图像文件的路径。 |
save_dir |
str, optional |
用于保存结果的目录。 |
Results
对象具有以下方法:
方法 | 返回类型 | 描述 |
---|---|---|
update() |
None |
使用新的检测数据(框、掩码、概率、obb、关键点)更新 Results 对象。 |
cpu() |
Results |
返回 Results 对象的副本,其中所有 tensor 都已移动到 CPU 内存。 |
numpy() |
Results |
返回 Results 对象的副本,其中所有 tensor 都已转换为 numpy 数组。 |
cuda() |
Results |
返回 Results 对象的副本,其中所有 tensor 都已移动到 GPU 内存。 |
to() |
Results |
返回 Results 对象的副本,其中 tensor 已移动到指定的设备和数据类型。 |
new() |
Results |
创建一个新的 Results 对象,该对象具有相同的图像、路径、名称和速度属性。 |
plot() |
np.ndarray |
在输入的 RGB 图像上绘制检测结果,并返回带注释的图像。 |
show() |
None |
显示带有注释的推理结果的图像。 |
save() |
str |
将带注释的推理结果图像保存到文件并返回文件名。 |
verbose() |
str |
返回每个任务的日志字符串,详细说明检测和分类结果。 |
save_txt() |
str |
将检测结果保存到文本文件,并返回保存文件的路径。 |
save_crop() |
None |
将裁剪的检测图像保存到指定目录。 |
summary() |
List[Dict[str, Any]] |
将推理结果转换为汇总字典,可以选择进行归一化。 |
to_df() |
DataFrame |
将检测结果转换为极坐标数据帧。 |
to_csv() |
str |
将检测结果转换为 CSV 格式。 |
to_json() |
str |
将检测结果转换为 JSON 格式。 |
有关更多详细信息,请参见 Results
类文档.
边界框
Boxes
对象可用于索引、操作和将边界框转换为不同的格式。
边界框
from ultralytics import YOLO
# Load a pretrained YOLO11n model
model = YOLO("yolo11n.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
以下是 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("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
类的方法和属性表,包括它们的名称、类型和描述:
名称 | 类型 | 描述 |
---|---|---|
cpu() |
方法 | 返回 CPU 内存上的掩码 tensor。 |
numpy() |
方法 | 返回作为 numpy 数组的掩码 tensor。 |
cuda() |
方法 | 返回 GPU 内存上的掩码 tensor。 |
to() |
方法 | 返回具有指定设备和数据类型的掩码 tensor。 |
xyn |
属性 (torch.Tensor ) |
表示为 tensor 的归一化分割列表。 |
xy |
属性 (torch.Tensor ) |
表示为 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("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
类的方法和属性表,包括它们的名称、类型和描述:
名称 | 类型 | 描述 |
---|---|---|
cpu() |
方法 | 返回 CPU 内存上的关键点 tensor。 |
numpy() |
方法 | 返回作为 numpy 数组的关键点 tensor。 |
cuda() |
方法 | 返回 GPU 内存上的关键点 tensor。 |
to() |
方法 | 返回具有指定设备和数据类型的关键点 tensor。 |
xyn |
属性 (torch.Tensor ) |
表示为 tensor 的归一化关键点列表。 |
xy |
属性 (torch.Tensor ) |
表示为 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("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
函数:
名称 | 类型 | 描述 |
---|---|---|
cpu() |
方法 | 返回 CPU 内存中 probs tensor 的副本。 |
numpy() |
方法 | 返回 probs tensor 作为 numpy 数组的副本。 |
cuda() |
方法 | 返回 GPU 内存中 probs tensor 的副本。 |
to() |
方法 | 返回具有指定设备和数据类型的 probs tensor 副本。 |
top1 |
属性 (int ) |
排名第一的类别的索引。 |
top5 |
属性 (list[int] ) |
排名前 5 的类别的索引。 |
top1conf |
属性 (torch.Tensor ) |
排名第一的类别的置信度。 |
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("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
类的方法和属性表,包括它们的名称、类型和描述:
名称 | 类型 | 描述 |
---|---|---|
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 ) |
以 xyxyxyxy 格式返回旋转框。 |
xyxyxyxyn |
属性 (torch.Tensor ) |
返回由图像大小归一化的 xyxyxyxy 格式的旋转框。 |
有关更多详细信息,请参见 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()
方法支持各种参数来自定义输出:
参数 | 类型 | 描述 | 默认值 |
---|---|---|---|
conf |
bool |
包括检测置信度分数。 | True |
line_width |
float |
边界框的线条宽度。如果图像大小为,则缩放 None . |
None |
font_size |
float |
文本字体大小。如果图像大小为,则缩放 None . |
None |
font |
str |
文本注释的字体名称。 | 'Arial.ttf' |
pil |
bool |
将图像作为 PIL 图像对象返回。 | False |
img |
np.ndarray |
用于绘制图像的替代图像。如果未提供,则使用原始图像。 None . |
None |
im_gpu |
torch.Tensor |
用于更快进行掩码绘制的 GPU 加速图像。形状:(1, 3, 640, 640)。 | None |
kpt_radius |
int |
绘制的关键点半径。 | 5 |
kpt_line |
bool |
用线条连接关键点。 | True |
labels |
bool |
在注释中包含类别标签。 | True |
boxes |
bool |
在图像上叠加边界框。 | True |
masks |
bool |
在图像上叠加掩码。 | True |
probs |
bool |
包含分类概率。 | True |
show |
bool |
使用默认图像查看器直接显示带注释的图像。 | False |
save |
bool |
将带注释的图像保存到指定的文件中。 filename . |
False |
filename |
str |
如果指定了 ,则为保存带注释图像的文件的路径和名称。 save 是 True . |
None |
color_mode |
str |
指定颜色模式,例如“instance”或“class”。 | 'class' |
txt_color |
tuple[int, int, int] |
用于边界框和图像分类标签的 RGB 文本颜色。 | (255, 255, 255) |
线程安全推理
当您在不同线程中并行运行多个 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 是一种最先进的实时目标检测、分割和分类模型。它的 predict 模式 允许用户对各种数据源(如图像、视频和直播流)执行高速推理。它专为性能和多功能性而设计,还提供批量处理和流式传输模式。有关其功能的更多详细信息,请查看Ultralytics YOLO predict 模式。
如何使用 Ultralytics YOLO 在不同的数据源上运行推理?
Ultralytics YOLO 可以处理各种数据源,包括单个图像、视频、目录、URL 和流。您可以在以下位置指定数据源 model.predict()
调用。例如,使用 'image.jpg'
用于本地图像或 'https://ultralytics.com/images/bus.jpg'
用于 URL。查看各种 推理来源 的详细示例,请参阅文档。
如何优化 YOLO 推理速度和内存使用?
要优化推理速度并有效地管理内存,您可以通过设置 stream=True
在 predictor 的调用方法中使用流式传输模式。流式传输模式生成一个内存高效的 Results
对象生成器,而不是将所有帧加载到内存中。对于处理长视频或大型数据集,流式传输模式特别有用。了解更多关于 流式传输模式.
Ultralytics YOLO 支持哪些推理参数?
字段 model.predict()
方法在 YOLO 中支持各种参数,例如 conf
, iou
, imgsz
, device
等等。这些参数允许您自定义推理过程,设置置信度阈值、图像大小和用于计算的设备等参数。有关这些参数的详细说明,请参阅 推理参数 部分。
如何可视化和保存 YOLO 预测的结果?
在使用 YOLO 运行推理后, Results
对象包含用于显示和保存带注释图像的方法。您可以使用诸如 result.show()
和 result.save(filename="result.jpg")
等方法来可视化和保存结果。有关这些方法的完整列表,请参阅 处理结果 部分。