类型错误:无法将向量元素转换为"分数",索引=0



我正试图获取yolov5s.onnx模型的输出,并在其上运行NMSBoxes。但我一直收到这个错误:

Traceback (most recent call last):
File "python_detection.py", line 132, in <module>
class_ids, confidences, boxes = wrap_detection(inputImage, outs[0])
File "python_detection.py", line 88, in wrap_detection
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45)
TypeError: Can't convert vector element for 'scores', index=0

无论我走到哪里,人们都在使用与我完全相同的代码。这是有道理的,因为这些代码大多是从教程中复制的。所以我不知道我做错了什么,所以一直给我这个错误。

以下是完整的功能:

def wrap_detection(input_image, output_data):
class_ids = []
confidences = []
boxes = []
rows = output_data.shape[0]
image_width, image_height, _ = input_image.shape
x_factor = image_width / INPUT_WIDTH
y_factor =  image_height / INPUT_HEIGHT
for r in range(rows):
row = output_data[r]
confidence = row[4]
if confidence >= 0.4:
classes_scores = row[5:]
_, _, _, max_indx = cv2.minMaxLoc(classes_scores)
class_id = max_indx[1]
if (classes_scores[class_id] > .25):
confidences.append(confidence)
class_ids.append(class_id)
x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()
left = int((x - 0.5 * w) * x_factor)
top = int((y - 0.5 * h) * y_factor)
width = int(w * x_factor)
height = int(h * y_factor)
box = np.array([left, top, width, height])
boxes.append(box)
'''
Print the raw output
'''
# Save output
np.set_printoptions(threshold=sys.maxsize)
file = open("python_raw_model_output.txt", "w+")
for i in range(len(boxes)):
file.write(str(boxes[i]) + " " + str(confidences[i]) + " " + str(class_ids[i]))
file.write("n")
file.close()
# NMS on the lists
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45)
result_class_ids = []
result_confidences = []
result_boxes = []
for i in indexes:
result_confidences.append(confidences[i])
result_class_ids.append(class_ids[i])
result_boxes.append(boxes[i])
return result_class_ids, result_confidences, result_boxes

我遇到了同样的问题。这似乎与cuda配置有关,因为它在cpu上运行良好。我没有弄清楚到底出了什么问题,但我通过使用fastNMS解决了这个问题:在这里输入链接描述

我不知道你是否还需要帮助,但对于像我一样遇到这个问题的人来说,解决办法是你需要确保你使用的Python版本是Python>3.8opencv版本至少为4.5.4。使用pip install opencv-python==4.5.5.64解决了我的问题。

对于其他遇到此问题的人,我可以通过将confidences设置为Numpy数组(而不是列表(来解决同样的问题(在Python 3.8.10OpenCV 4.5.3上(。针对CUDA或Python/OpenCV版本的答案可能仍然正确,但对于某些情况,这可能是一个更简单的解决方案。

最新更新