没有足够的值来解压(预计有 6 个,实际有 1 个)

问题描述 投票:0回答:1

我正在加载对象检测模型和分类模型,以准确加载、检测和预测图像的类别。该代码将正确地迭代检测到的对象,根据置信度阈值 0.5 对其进行过滤,并对每个对象执行分类。如果分类结果是“干净”或“脏”,则会打印相应的消息。但是错误 ValueError:没有足够的值来解包(预期 6,得到 1)不断出现

这是我的代码

#Load an image  to process
import cv2  # Import OpenCV
import numpy as np
from PIL import Image

image_path = '/content/drive/MyDrive/clean_indian2.jpeg'
original_image = cv2.imread(image_path)

#Resize the image to match the expected input size of the YOLOv8 model
resized_image = cv2.resize(original_image, (640, 640)) 

#Convert the resized image to a PyTorch tensor
image_tensor= torch.from_numpy(np.ascontiguousarray(resized_image.transpose(2, 0, 1))).float()

#Normalize the image
image_tensor /= 255.0

#Make it a batch of 1
image_tensor = image_tensor.unsqueeze(0)

#Use YOLOv8n to detect pot seats in the image
#results = yolo_model(image_tensor.unsqueeze(0))  # Add a batch dimension

#Use your YOLOv8 model to predict objects in the image
with torch.no_grad():
    results = yolov8_model(image_tensor)

到这里它工作正常,但这里它给出了错误

#Iterate through detected objects and classify them
for obj in results[0]:  # Access the first (and possibly only) prediction
    x1, y1, x2, y2, conf, cls = obj  
#Bounding box coordinates, confidence, and class index

    # You can filter detections based on confidence if needed
    if conf > 0.5:
        object_image = resized_image[int(y1):int(y2), int(x1):int(x2)]

        # Convert the object image to PIL format
        object_pil_image = Image.fromarray(cv2.cvtColor(object_image, cv2.COLOR_BGR2RGB))

        # Perform classification using your classification model
        class_result = classification_model(object_pil_image)

        if class_result == 'clean':
            print("Detected a clean pot seat.")
        elif class_result == 'dirty':
            print("Detected a dirty pot seat.")

错误信息:

ValueError:
<ipython-input-74-92bf1423bdc4> in <cell line: 2>()
      1 # Iterate through detected objects and classify them
      2 for obj in results[0]:  # Access the first (and possibly only) prediction
----> 3     x1, y1, x2, y2, conf, cls = obj  # Bounding box coordinates, confidence, and class index
      4 
      5     # You can filter detections based on confidence if needed

ValueError: not enough values to unpack (expected 6, got 1)
python object-detection image-classification yolov8
1个回答
0
投票

这里的

obj
变量是一个
ultralytics.engine.results.Results
对象 - 一个用于存储和操作推理结果的类。你不能像有一个值列表一样解压它。为了达到具体的值,我们需要引用
Results
属性之一:
boxes
masks
probs
keypoints
- 作为检测、分割、分类或姿势估计任务的结果。考虑到您正在使用检测任务模型,我们需要引用
boxes
属性及其属性
xyxy
conf
cls
- 它们都是张量。

for obj in results[0].boxes:
  x1, y1, x2, y2 = obj.xyxy[0].tolist()
  conf = obj.conf.item()
  cls = int(obj.cls.item())
  print(x1, y1, x2, y2, conf, cls)

预计输出格式如下:

2643.072265625 1688.5892333984375 3643.5322265625 2735.485107421875 0.4271290600299835 77

有关使用 yolov8 预测结果的更多信息请参阅文档:https://docs.ultralytics.com/modes/predict/#working-with-results

© www.soinside.com 2019 - 2024. All rights reserved.