RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed.

修改YOLOv8预测结果的标签值时,报了如下错误:

image 1/1 /Users/mac10.12/Downloads/IMG_1122.PNG: 640x384 3 persons, 86.8ms
Speed: 3.1ms preprocess, 86.8ms inference, 1.4ms postprocess per image at shape (1, 3, 640, 384)
Traceback (most recent call last):
  File "/Users/mac10.12/github/YOLOSHOW/bb.py", line 10, in <module>
    result.boxes[0].cls[0] = 1
    ~~~~~~~~~~~~~~~~~~~^^^
RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed.You can make a clone to get a normal tensor before doing inplace update.See https://github.com/pytorch/rfcs/pull/17 for more details.

报错的代码如下:

from pathlib import Path

from ultralytics import YOLO  # type:ignore[import-untyped]

pic = Path.home() / "Downloads" / "IMG_1122.PNG"
model = YOLO("yolov8n.pt")

result = model(pic)[0]
result.names = {0: "woman", 1: "man", 2: "child"}
result.boxes[0].cls[0] = 1
result.show()

点开报错提示里的链接看了下,未能找到解决方案。

查看了result的源码(ultralytics.engine.results.Results)并在IPython中试了下,发现可以通过修改函数plot来实现目的。优化代码的过程中,发现还有更简洁的方式:定制predictor

最终代码如下:

from pathlib import Path

from ultralytics import YOLO, models  # type:ignore[import-untyped]
from ultralytics.engine.results import Results  # type:ignore[import-untyped]

pic = Path.home() / "Downloads" / "IMG_1122.PNG"
model = YOLO("yolov8n.pt")


class Predictor(models.yolo.detect.DetectionPredictor):
    def postprocess(self, preds, img, orig_imgs) -> list[Results]:
        results = super().postprocess(preds, img, orig_imgs)
        for i in results:
            self.update_person_labels(i)
        return results

    def update_person_labels(self, result: Results) -> None:
        new_names = {0: "文慧", 1: "man", 2: "child"}
        result.boxes[0].cls[0] = 0 # 修改第一个框的类别ID
        result.names = new_names # 修改各个类别对应的名称


result = model(pic, predictor=Predictor(overrides={"save": False, "conf": 0.5}))[0]
result.show()

结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值