预测

您所在的位置:网站首页 如何通过八卦预测数字的方法有哪些 预测

预测

2024-07-10 04:16| 来源: 网络整理| 查看: 265

模型预测与Ultralytics YOLO

Ultralytics YOLO 生态系统和集成

导言

在机器学习和计算机视觉领域,从可视数据中找出意义的过程被称为 "推理 "或 "预测"。Ultralytics YOLOv8 提供了一个名为 "预测模式"的强大功能,专门用于对各种数据源进行高性能的实时推理。

观看: 如何从Ultralytics YOLOv8 模型中提取输出用于定制项目。

真实世界的应用 制造业 体育 安全 车辆备件检测 足球运动员检测 人员坠落检测 车辆备件检测 足球运动员检测 人员坠落检测 为什么使用Ultralytics YOLO 进行推理?

以下是您应该考虑使用YOLOv8 的预测模式来满足各种推理需求的原因:

多功能性:能够对图像、视频甚至实时流进行推断。 性能:专为实时、高速处理而设计,同时不影响精度。 易用性:直观的Python 和CLI 界面,便于快速部署和测试。 高度可定制:各种设置和参数可根据您的具体要求调整模型的推理行为。 预测模式的主要功能

YOLOv8预测模式的设计坚固耐用、用途广泛,具有以下特点:

兼容多种数据源:无论您的数据是单个图像、图像集合、视频文件还是实时视频流,预测模式都能满足您的需求。 流媒体模式: 使用流功能生成具有内存效率的 Results 对象。通过设置 stream=True 在预测器的调用方法中。 批处理:批量处理:能够一次性处理多个图像或视频帧,进一步加快推理时间。 易于集成:凭借灵活的应用程序接口,可轻松与现有数据管道和其他软件组件集成。

Ultralytics YOLO 模型返回Python Results 对象,或一个内存效率高的Python Results 当 stream=True 会在推理过程中传递给模型:

预测

from ultralytics import YOLO # Load a model model = YOLO("yolov8n.pt") # pretrained YOLOv8n model # Run batched inference on a list of images results = model(["im1.jpg", "im2.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("yolov8n.pt") # pretrained YOLOv8n model # Run batched inference on a list of images results = model(["im1.jpg", "im2.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 推理源

YOLOv8 可以处理不同类型的输入源进行推理,如下表所示。输入源包括静态图像、视频流和各种数据格式。表中还标明了每种输入源是否可以在流模式下使用参数 stream=True ✅.流模式有利于处理视频或实时流,因为它会创建一个结果生成器,而不是将所有帧加载到内存中。

提示

使用 stream=True 用于处理长视频或大型数据集,以有效管理内存。当 stream=False在这种情况下,所有帧或数据点的结果都会存储在内存中,这可能会迅速累加,并导致大量输入出现内存不足错误。与此形成鲜明对比的是 stream=True 利用生成器,它只将当前帧或数据点的结果保存在内存中,从而大大减少了内存消耗并防止出现内存不足的问题。

资料来源 论据 类型 说明 图像 'image.jpg' str 或 Path 单个图像文件。 网址 'https://ultralytics.com/images/bus.jpg' str 图片的 URL。 截图 'screen' str 截图 PIL Image.open('im.jpg') PIL.Image 具有 RGB 通道的 HWC 格式。 OpenCV cv2.imread('im.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 包含图像或视频的目录路径。 球体 ✅ 'path/*.jpg' str 全局模式来匹配多个文件。使用 * 字符作为通配符。 YouTube ✅ 'https://youtu.be/LNwODJXcvt4' str YouTube 视频的 URL。 流 ✅ 'rtsp://example.com/media.mp4' str 流媒体协议(如 RTSP、RTMP、TCP)的 URL 或 IP 地址。 多流 ✅ 'list.streams' str 或 Path *.streams 文本文件,每行一个流 URL,即 8 个流将以 8 的批处理大小运行。

下面是使用每种源类型的代码示例:

预测来源

在图像文件上运行推理。

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n model model = YOLO("yolov8n.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此外,您还可以创建一个结果对象生成器,以减少长视频的内存使用量。

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.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 地址协议对远程流媒体源进行推理。如果在一个 *.streams 文本文件,则将运行批处理推理,即 8 个数据流将以 8 的批处理大小运行,否则单个数据流将以 1 的批处理大小运行。

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.pt") # Single stream with batch-size 1 inference source = "rtsp://example.com/media.mp4" # RTSP, RTMP, TCP or IP streaming address # Multiple streams with batched inference (i.e. batch-size 8 for 8 streams) source = "path/to/list.streams" # *.streams text file with one streaming address per row # Run inference on the source results = model(source, stream=True) # generator of Results objects

推理论据

model.predict() 接受多个参数,这些参数可以在推理时传递,以覆盖默认值:

示例

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.pt") # Run inference on 'bus.jpg' with arguments model.predict("bus.jpg", save=True, imgsz=320, conf=0.5)

推理论据:

论据 类型 默认值 说明 source str 'ultralytics/assets' 指定推理的数据源。可以是图像路径、视频文件、目录、URL 或用于实时馈送的设备 ID。支持多种格式和来源,可灵活应用于不同类型的输入。 conf float 0.25 设置检测的最小置信度阈值。如果检测到的对象置信度低于此阈值,则将不予考虑。调整该值有助于减少误报。 iou float 0.7 非最大抑制 (NMS) 的交叉重叠 (IoU) 阈值。较低的数值可以消除重叠的方框,从而减少检测次数,这对减少重复检测非常有用。 imgsz int or tuple 640 定义用于推理的图像大小。可以是一个整数 640 或一个(高、宽)元组。适当调整大小可以提高检测精度和处理速度。 half bool False 启用半精度(FP16)推理,可加快支持的 GPU 上的模型推理速度,同时将对精度的影响降至最低。 device str None 指定用于推理的设备(例如:......)、 cpu, cuda:0 或 0).允许用户选择 CPU、特定 GPU 或其他计算设备来执行模型。 max_det int 300 每幅图像允许的最大检测次数。限制模型在单次推理中可检测到的物体总数,防止在密集场景中产生过多输出。 vid_stride int 1 视频输入的帧间距。允许跳过视频中的帧,以加快处理速度,但会牺牲时间分辨率。值为 1 时处理每一帧,值越大跳帧越多。 stream_buffer bool False 确定在处理视频流时是否对所有帧进行缓冲 (True),或者模型是否应该返回最近的帧 (False).适用于实时应用。 visualize bool False 在推理过程中激活模型特征的可视化,从而深入了解模型 "看到 "了什么。这对调试和模型解释非常有用。 augment bool False 可对预测进行测试时间增强(TTA),从而在牺牲推理速度的情况下提高检测的鲁棒性。 agnostic_nms bool False 启用与类别无关的非最大抑制 (NMS),可合并不同类别的重叠方框。这在多类检测场景中非常有用,因为在这种场景中,类的重叠很常见。 classes list[int] None 根据一组类别 ID 过滤预测结果。只返回属于指定类别的检测结果。在多类检测任务中,该功能有助于集中检测相关对象。 retina_masks bool False 如果模型中存在高分辨率的分割掩膜,则使用高分辨率的分割掩膜。这可以提高分割任务的掩膜质量,提供更精细的细节。 embed list[int] None 指定从中提取特征向量或嵌入的层。这对聚类或相似性搜索等下游任务非常有用。

可视化参数:

论据 类型 默认值 说明 show bool False 如果 True在一个窗口中显示注释的图像或视频。有助于在开发或测试过程中提供即时视觉反馈。 save bool 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根据图像大小自动调整线宽。提供可视化定制,使图像更加清晰。 图像和视频格式

YOLOv8 支持ultralytics/data/utils .py 中指定的各种图像和视频格式。有关有效后缀和预测命令示例,请参见下表。

图片

下表包含有效的Ultralytics 图像格式。

图像后缀 预测命令示例 参考资料 .bmp yolo predict source=image.bmp 微软 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 便携式浮图 视频

下表包含有效的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 第 14 部分 .mkv yolo predict source=video.mkv 马特罗斯卡 .mov yolo predict source=video.mov QuickTime 文件格式 .mp4 yolo predict source=video.mp4 MPEG-4 第 14 部分 - 维基百科 .mpeg yolo predict source=video.mpeg MPEG-1 第 2 部分 .mpg yolo predict source=video.mpg MPEG-1 第 2 部分 .ts yolo predict source=video.ts MPEG 传输流 .wmv yolo predict source=video.wmv Windows 媒体视频 .webm yolo predict source=video.webm WebM 项目 利用成果开展工作

全部Ultralytics predict() 调用将返回一个 Results 物件

成果

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.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_img numpy.ndarray 原始图像的 numpy 数组。 orig_shape tuple 原始图像的形状,格式为(高、宽)。 boxes Boxes, optional 包含检测边界框的方框对象。 masks Masks, optional 包含检测掩码的掩码对象。 probs Probs, optional Probs 对象,包含分类任务中每个类别的概率。 keypoints Keypoints, optional 关键点对象,包含每个对象的检测关键点。 obb OBB, optional 包含定向包围盒的 OBB 对象。 speed dict 每幅图像的预处理、推理和后处理速度字典,单位为毫秒。 names dict 类名字典。 path str 图像文件的路径。

Results 对象有以下方法:

方法 返回类型 说明 update() None 更新结果对象的方框、掩码和 probs 属性。 cpu() Results 返回包含 CPU 内存中所有张量的结果对象副本。 numpy() Results 返回结果对象的副本,其中所有张量均为 numpy 数组。 cuda() Results 返回包含 GPU 内存中所有张量的 Results 对象副本。 to() Results 返回带有指定设备和 dtype 上张量的 Results 对象副本。 new() 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 YOLOv8n model model = YOLO("yolov8n.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 YOLOv8n-seg Segment model model = YOLO("yolov8n-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() 方法 以 numpy 数组形式返回掩码tensor 。 cuda() 方法 返回 GPU 内存中的掩码tensor 。 to() 方法 返回具有指定设备和 dtype 的掩码tensor 。 xyn 财产 (torch.Tensor) 以张量表示的标准化片段列表。 xy 财产 (torch.Tensor) 以张量表示的像素坐标线段列表。

更多详情,请参阅 Masks 类文档.

要点

Keypoints 对象可用于索引、处理和归一化坐标。

要点

from ultralytics import YOLO # Load a pretrained YOLOv8n-pose Pose model model = YOLO("yolov8n-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() 方法 以 numpy 数组形式返回关键点tensor 。 cuda() 方法 返回 GPU 内存中的关键点tensor 。 to() 方法 返回指定设备和 dtype 的关键点tensor 。 xyn 财产 (torch.Tensor) 以张量表示的标准化关键点列表。 xy 财产 (torch.Tensor) 以张量表示的像素坐标关键点列表。 conf 财产 (torch.Tensor) 返回关键点的置信度值(如果有),否则为空。

更多详情,请参阅 Keypoints 类文档.

问题

Probs 对象可用于索引、获取 top1 和 top5 分类指数和分数。

问题

from ultralytics import YOLO # Load a pretrained YOLOv8n-cls Classify model model = YOLO("yolov8n-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() 方法 以 numpy 数组形式返回 probstensor 的副本。 cuda() 方法 返回 GPU 内存中 probstensor 的副本。 to() 方法 返回带有指定设备和 dtype 的 probstensor 的副本。 top1 财产 (int) 前 1 级的指数。 top5 财产 (list[int]) 前 5 个等级的指数。 top1conf 财产 (torch.Tensor) 对前 1 级充满信心。 top5conf 财产 (torch.Tensor) 前五名班级的机密

更多详情,请参阅 Probs 类文档.

OBB

OBB 对象可用于索引、操作和将定向边界框转换为不同格式。

OBB

from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n-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) 以 xyxyxyxy 格式返回旋转后的方框。 xyxyxyxyn 财产 (torch.Tensor) 以 xyxyxyxy 格式返回按图像大小归一化的旋转方框。

更多详情,请参阅 OBB 类文档.

绘制结果

"(《世界人权宣言》) plot() 方法中的 Results 对象,将检测到的对象(如边界框、遮罩、关键点和概率)叠加到原始图像上,从而实现预测的可视化。该方法以 NumPy 数组形式返回注释图像,便于显示或保存。

绘图

from PIL import Image from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.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() 方法支持各种参数来定制输出:

论据 类型 说明 默认值 conf bool 包括检测置信度分数。 True line_width float 边界框的线宽。根据图像大小缩放,如果 None. None font_size float 文字字体大小。与图像大小一致,如果 None. None font str 文本注释的字体名称。 'Arial.ttf' pil bool 将图像作为 PIL 图像对象返回。 False img numpy.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 线程安全推理

在不同线程并行运行多个YOLO 模型时,确保推理过程中的线程安全至关重要。线程安全推理可确保每个线程的预测都是独立的,不会相互干扰,从而避免出现竞赛条件,并确保输出结果的一致性和可靠性。

在多线程应用程序中使用YOLO 模型时,必须为每个线程实例化单独的模型对象,或使用线程本地存储以防止冲突:

线程安全推理

在每个线程内实例化一个模型,以实现线程安全推理:

from threading import Thread from ultralytics import YOLO def thread_safe_predict(image_path): """Performs thread-safe prediction on an image using a locally instantiated YOLO model.""" local_model = YOLO("yolov8n.pt") results = local_model.predict(image_path) # Process results # Starting threads that each have their own model instance Thread(target=thread_safe_predict, args=("image1.jpg",)).start() Thread(target=thread_safe_predict, args=("image2.jpg",)).start()

如需深入了解YOLO 模型的线程安全推理以及分步说明,请参阅我们的YOLO 线程安全推理指南。本指南将为您提供所有必要信息,以避免常见陷阱,确保您的多线程推理顺利进行。

流媒体源 for-循环

Python 下面是一个使用 OpenCV (cv2)和YOLOv8 对视频帧进行推理。本脚本假定您已经安装了必要的软件包 (opencv-python 和 ultralytics).

流式 for 循环

import cv2 from ultralytics import YOLO # Load the YOLOv8 model model = YOLO("yolov8n.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 YOLOv8 inference on the frame results = model(frame) # Visualize the results on the frame annotated_frame = results[0].plot() # Display the annotated frame cv2.imshow("YOLOv8 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 YOLOv8 及其用于实时推理的预测模式?

Ultralytics YOLOv8 是一种用于实时对象检测、分割和分类的先进模型。其预测模式允许用户对图像、视频和实时流等各种数据源进行高速推理。它还提供批处理和流模式,专为高性能和多功能而设计。有关其功能的更多详情,请查看Ultralytics YOLOv8 预测模式。

如何在不同数据源上使用Ultralytics YOLOv8 运行推理?

Ultralytics YOLOv8 可以处理多种数据源,包括单个图像、视频、目录、URL 和数据流。您可以在 model.predict() 调用。例如,使用 'image.jpg' 本地图像或 'https://ultralytics.com/images/bus.jpg' 的 URL。查看详细示例,了解各种 推理源 在文档中。

如何优化YOLOv8 的推理速度和内存使用率?

要优化推理速度并有效管理内存,可以通过设置 stream=True 在预测器的调用方法中。流模式会生成一个具有内存效率的 Results 对象,而不是将所有帧加载到内存中。对于处理长视频或大型数据集,流模式尤其有用。了解更多 流媒体模式.

Ultralytics YOLOv8 支持哪些推论论据?

"(《世界人权宣言》) model.predict() YOLOv8 中的 conf, iou, imgsz, device等参数。通过这些参数,您可以自定义推理过程,设置置信度阈值、图像大小和计算设备等参数。有关这些参数的详细说明,请参阅 推理论据 节。

如何可视化并保存YOLOv8 预测结果?

使用YOLOv8 运行推理后, Results 对象包含用于显示和保存注释图像的方法。您可以使用以下方法 result.show() 和 result.save(filename="result.jpg") 来可视化和保存结果。有关这些方法的完整列表,请参阅 工作成果 节。

创建于 2023-11-12,更新于 2024-07-04作者:glenn-jocher(24),IvorZhu331(1),RizwanMunawar(1),UltralyticsAssistant(1),Burhan-Q(1),plashchynski(1),tensorturtle(1),AyushExel(1),Laughing-q(1) 评论


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3