使用YOLOv7与ZED双目相机提取锥桶x/y坐标时代码报错求助
问题分析与修复
错误原因
- 调用对象错误:
img是PIL Image格式的图片,并非PyTorch张量,因此没有unsqueeze()方法。你应该对经过transform处理后的image张量做维度扩展,而非原始的PIL图片。 - 模型调用错误:
model已经是通过attempt_load加载好的预训练模型实例,不需要再执行model()创建新实例,直接传入处理好的张量即可完成推理。
修正后的完整代码
from models.experimental import attempt_load import torchvision.transforms as transforms from PIL import Image import torch from utils.general import non_max_suppression # 设置设备 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # YOLOv7权重文件路径 weights_path = 'runs/train/yolov7-cones/weights/best.pt' # 加载模型并设置为评估模式 model = attempt_load(weights_path, map_location=device) model.to(device).eval() img_size = 640 # 加载图片 img = Image.open("inference/3cone.jpeg") # 定义图像预处理流程 transform = transforms.Compose([ transforms.Resize((640, 640)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 预处理图片得到张量 image = transform(img) # 添加batch维度,并将张量移至对应设备 image = image.unsqueeze(0).to(device) # 模型推理 output = model(image) # 非极大值抑制过滤冗余预测框 pred = non_max_suppression(output)[0] # 提取目标的中心x、y坐标并存储为列表 coords = [] if pred is not None: for det in pred: # det格式:[x1, y1, x2, y2, conf, cls] x_center = (det[0] + det[2]) / 2 y_center = (det[1] + det[3]) / 2 coords.append([x_center.item(), y_center.item()]) # 打印结果 print("目标中心坐标列表:", coords) print("模型输出张量形状:", output[0].shape)
关键修改说明
- 补充
from PIL import Image导入,原代码缺少该模块会导致Image.open报错。 - 将
img.unsqueeze(0)改为image.unsqueeze(0).to(device),确保操作的是预处理后的张量,同时和模型设备保持一致。 - 移除错误的
model1 = model(),直接用model(image)执行推理。 - 添加非极大值抑制(NMS)步骤,过滤YOLO模型输出的重复预测框。
- 新增目标中心坐标提取逻辑,将结果存储为列表,满足你提取坐标的需求。
内容的提问来源于stack exchange,提问作者sureya nachiappan
相关产品推荐
相关产品推荐

