此处以YOLOv8模型为例,在一张图片中检测出一个bounding box,检测代码如下:
from ultralytics import YOLO
import os
import cv2
current_dir = os.path.dirname(os.path.abspath(__file__))
model_dir = os.path.join(current_dir, 'model')
model_path = os.path.join(model_dir, 'find_box.pt')
image_dir = os.path.join(current_dir, 'images')
images_path_list = [os.path.join(image_dir, image_name) for image_name in os.listdir(image_dir)]
first_image_path = images_path_list[0]
detect_model = YOLO(model_path)
# 模型检测box
result = detect_model(first_image_path, save=True)
print('result:\n' ,result)打印result的结果如下:
result:
[ultralytics.engine.results.Results object with attributes:
boxes: ultralytics.engine.results.Boxes object
keypoints: None
masks: None
names: {0: 'box'}
obb: None
orig_img: array([[[ 0, 146, 194],
[ 2, 148, 196],
[ 3, 149, 197],
...
[ 5, 37, 56],
[ 5, 37, 56],
[ 6, 38, 57]]], dtype=uint8)
orig_shape: (1520, 2688)
path: 'c:\\Users\\Administrator\\Desktop\\tmp\\images\\1.jpg'
probs: None
save_dir: 'runs\\detect\\predict2'
speed: {'preprocess': 2.999544143676758, 'inference': 193.587064743042, 'postprocess': 1.9960403442382812}]result结果分析:
boxes: ultralytics.engine.results.Boxes object
存储检测框信息的对象,存储了包括坐标、置信度、类别等。
keypoints: None
关键点检测结果(人体姿态等),当前模型没有这个功能
masks: None
实例分割的掩码,当前模型没有这个功能
names: {0: 'box'}
类别名称映射表:类别ID=0 对应名称 'box'
obb: None
旋转目标框(Oriented Bounding Box),当前模型不支持
orig_img: array([[[0,146,194]...]]
原始图像的像素数据(三维数组,H×W×C)
orig_shape: (1520, 2688)
原始图像的真实尺寸(高×宽),不是模型输入尺寸
path: 'c:\\Users\\Administrator\\Desktop\\tmp\\images\\1.jpg'
源文件位置
probs: None
分类概率,当前模型没有这个功能(只做目标检测)
save_dir: 'runs\\detect\\predict2'
结果保存目录(带标注的图像会存到这里)
speed: {'preprocess': 2.999544143676758, 'inference': 193.587064743042, 'postprocess': 1.9960403442382812}
详细的各阶段耗时(字典格式)
boxes属性分析:
不能直接print(result.boxes),因为result是一个list类型,保存了多张图片的检测结果,即使目前只处理了一张图片,但是也是一个list,所以要用print(result[0].boxes)。
print(result[0].boxes)结果如下:
cls: tensor([0.])
conf: tensor([0.9534])
data: tensor([[1.1318e+03, 3.6029e+02, 1.8270e+03, 1.0282e+03, 9.5337e-01, 0.0000e+00]])
id: None
is_track: False
orig_shape: (1520, 2688)
shape: torch.Size([1, 6])
xywh: tensor([[1479.3813, 694.2301, 695.2084, 667.8889]])
xywhn: tensor([[0.5504, 0.4567, 0.2586, 0.4394]])
xyxy: tensor([[1131.7772, 360.2856, 1826.9856, 1028.1746]])
xyxyn: tensor([[0.4210, 0.2370, 0.6797, 0.6764]])cls:检测到的目标类别ID
conf:置信度
data:完整的检测数据,[左上角x, 左上角y, 右下角x, 右下角y, 置信度, 类别ID]
id:目标追踪ID,None 表示未启用目标追踪功能
is_track:是否启用追踪模式,False 表示这是单帧独立检测,不跨帧关联目标
orig_shape:原始图像的真实尺寸
shape:[1, 6] 表示有 1 个检测目标,每个目标有 6 个属性值
xywh:[中心点x, 中心点y, 宽度, 高度]
xywhn:归一化的边界框坐标(0~1范围)
xyxy:边界框的四个角坐标(原始图像像素单位)[左上角x, 左上角y, 右下角x, 右下角y]
xyxyn:归一化的四个角坐标(0~1范围)
登录 后才能评论