将YOLO模型结果保存为字符串

0 投票
1 回答
25 浏览
提问于 2025-04-13 20:05

我有一个模型,叫做 best.pt,我想运行它。这个模型需要一张图片作为输入,然后它会识别出这张图片中的一个物体,也就是水果。

from PIL import Image
from ultralytics import YOLO

# Load the pre-trained model
model = YOLO('best.pt')
# Load the input image
input_image = Image.open('fruit.jpeg')
# Pass the image through the model
output = model(input_image)

运行这段代码后,会输出:

0: 640x640 1 Banana, 70.7ms
Speed: 2.3ms preprocess, 70.7ms inference, 0.7ms postprocess per image at shape (1, 3, 640, 640)

我想把 Banana 保存到一个字符串里。

output 是一个类型为 list 的对象,里面有一个项目,这个项目是来自 ultralytics 库的 Results 实例。当我尝试打印 output 时,得到的结果是:

ultralytics.engine.results.Results object with attributes:

boxes: ultralytics.engine.results.Boxes object
keypoints: None
masks: None
names: {0: 'Apple', 1: 'Banana', 2: 'Blueberry'}
obb: None
orig_img: array([[[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]],

       ...,

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]], dtype=uint8)
orig_shape: (225, 225)
path: 'fruit.jpeg'
probs: None
save_dir: 'runs/detect/predict'
speed: {'preprocess': 2.3441314697265625, 'inference': 70.66583633422852, 'postprocess': 0.6880760192871094}

尝试打印 output.boxes 的结果是:

ultralytics.engine.results.Boxes object with attributes:

cls: tensor([0.])
conf: tensor([0.9832])
data: tensor([[ 63.5629,  44.9124, 153.1798, 183.1818,   0.9832,   0.0000]])
id: None
is_track: False
orig_shape: (225, 225)
shape: torch.Size([1, 6])
xywh: tensor([[108.3714, 114.0471,  89.6169, 138.2694]])
xywhn: tensor([[0.4817, 0.5069, 0.3983, 0.6145]])
xyxy: tensor([[ 63.5629,  44.9124, 153.1798, 183.1818]])
xyxyn: tensor([[0.2825, 0.1996, 0.6808, 0.8141]])

在这些输出中,我找不到任何地方显示结果是 Banana

我该如何把结果(Banana)保存到一个字符串里呢?

1 个回答

0

给你看看:

print(output[0].names[np.array(output[0].boxes.cls)[0]])

可能会检测到多个类,你可能需要把最后的 [0] 替换掉。

撰写回答