修改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()
结果如下: