YOLOv8(PyTorch)中如何编辑model.track返回的Result对象?
YOLO Result对象跟踪ID修改解决方案
问题场景
尝试修改YOLO model.track返回的Result对象属性时触发错误,代码及错误信息如下:
原代码
for result in model.track(source=source, show=False, stream=True, verbose=False): frame = result.orig_img # result.boxes.id[0] = 0 # 代码崩溃 print('After', result.boxes.id)
错误信息
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.
可行解决方案
问题核心是result.boxes.id属于PyTorch InferenceMode下的只读张量,无法直接原地修改,需通过克隆生成可编辑张量后重新赋值:
修改后代码
import torch for result in model.track(source=source, show=False, stream=True, verbose=False): frame = result.orig_img # 仅当存在跟踪ID时执行修改 if result.boxes.id is not None: # 克隆张量,脱离InferenceMode限制 editable_ids = result.boxes.id.clone() # 修改目标ID editable_ids[0] = 0 # 将修改后的张量重新赋值给boxes.id result.boxes.id = editable_ids print('After', result.boxes.id)
补充说明
clone()方法会生成原张量的独立副本,拥有可写权限,不受原InferenceMode约束。- 若需批量替换ID,可直接创建新张量赋值,需注意与原张量设备(CPU/GPU)保持一致:
result.boxes.id = torch.tensor([1, 2, 3], device=result.boxes.id.device) - 必须先判断
result.boxes.id is not None,避免无跟踪结果时触发空值报错。
内容的提问来源于stack exchange,提问作者liran bratt
相关产品推荐
相关产品推荐

