Jonvy

导航

多类别检测和单类别检测,python程序使用 ONNX Runtime进行推理的不同?

使用 ONNX Runtime 进行多类别检测和单类别检测的 Python 程序在推理过程中的主要区别在于模型的输出处理和结果解析。以下是详细的比较:

单类别检测

单类别检测模型只检测一种特定类别的物体。推理过程相对简单,主要步骤包括:

  • 加载模型:
session = ort.InferenceSession("single_class_model.onnx")
  • 预处理图片:
img = Image.open("image.jpg").resize((224, 224))
img_data = np.array(img).transpose(2, 0, 1).astype(np.float32) / 255
img_data = np.expand_dims(img_data, axis=0)
  • 进行推理:
input_name = session.get_inputs()[0].name
output = session.run(None, {input_name: img_data})
  • 解析结果:
predicted_class = np.argmax(output[0])
print(f"预测结果:类别{predicted_class}")

多类别检测

多类别检测模型能够同时检测和识别多种不同类别的物体。推理过程更复杂,主要步骤包括:

  • 加载模型:
session = ort.InferenceSession("multi_class_model.onnx")
  • 预处理图片:
img = Image.open("image.jpg").resize((640, 640))
img_data = np.array(img).transpose(2, 0, 1).astype(np.float32) / 255
img_data = np.expand_dims(img_data, axis=0)
  • 进行推理: 
input_name = session.get_inputs()[0].name
output = session.run(None, {input_name: img_data})
  • 解析结果

由于多类别检测模型输出多个类别的边界框和置信度,需要进行后处理,例如过滤低置信度的预测结果和非极大值抑制(NMS)。

def postprocess_output(output, input_shape, conf_threshold=0.5):
    boxes = output[0][:, :4]
    scores = output[0][:, 4]
    classes = output[0][:, 5]

    indices = np.where(scores > conf_threshold)[0]
    boxes = boxes[indices]
    scores = scores[indices]
    classes = classes[indices]

    boxes[:, [0, 2]] *= input_shape[1]
    boxes[:, [1, 3]] *= input_shape[0]

    return boxes, scores, classes

boxes, scores, classes = postprocess_output(output, (640, 640))
  • 可视化结果

多类别检测通常需要在图像上绘制多个边界框和类别标签:

def draw_boxes(image_path, boxes, scores, classes):
    img = cv2.imread(image_path)
    for box, score, cls in zip(boxes, scores, classes):
        x1, y1, x2, y2 = box.astype(int)
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
        label = f"Class {int(cls)}: {score:.2f}"
        cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    cv2.imshow("Detection", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

draw_boxes("image.jpg", boxes, scores, classes)

总结

  • 单类别检测:处理简单,主要关注单个类别的预测结果。
  • 多类别检测:处理复杂,需要解析多个类别的预测结果,并进行后处理和可视化。

 

 

 

posted on 2025-03-25 17:43  不亮  阅读(86)  评论(0)    收藏  举报