yolov目标检测的图片onnx输入尺寸及预处理

参考 (github.com)

当你使用不同的图像尺寸(例如1280)进行预测时,YOLOv8会自动对输入图像进行适当的预处理以适配模型。这通常包括缩放和填充操作,确保图像不会发生畸变,同时保持原始宽高比。

对于使用OpenCV进行预处理,你可以按照以下步骤来模拟YOLOv8的预处理过程:

  1. 保持图像的宽高比,将图像缩放到模型的输入尺寸(例如640x640)中较短的一边。
  2. 对缩放后的图像进行填充,以达到所需的输入尺寸,通常填充的是图像的右侧和底部。
  3. 确保填充值(通常是灰色,即(114, 114, 114))与训练时使用的填充值相匹配。

以下是一个简单的OpenCV代码示例,展示了如何进行这种预处理:

def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
    # Resize and pad image while meeting stride-multiple constraints
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return im, ratio, (dw, dh)

# Load image
img, ratio, dw, dh = cv2.imread('path/to/your/image.jpg')

# Preprocess image
img_preprocessed = letterbox(img)

# Now you can pass `img_preprocessed` to your model for prediction

这段代码会将图像缩放并填充到指定的尺寸,同时保持原始宽高比,从而避免畸变。
在实际应用中,你可能需要根据你的具体需求调整这个函数。

### YOLOv8目标检测通过ONNX执行推理 YOLOv8 是一种先进的实时对象检测框架,支持多种任务类型,包括旋转目标检测。为了实现基于 ONNX 的推理流程,可以按照以下方法操作。 #### 1. 导出模型至 ONNX 格式 首先需要将训练好的 YOLOv8 模型导出为 ONNX 文件格式。可以通过 Ultralytics 提供的工具完成此过程: ```python from ultralytics import YOLO # 加载预训练模型或自定义模型 model = YOLO('yolov8n.pt') # 或者 'path_to_custom_model.pt' # 将模型导出为 ONNX 格式 success = model.export(format='onnx', simplify=True, opset=12) ``` 上述代码会生成一个 `.onnx` 文件,该文件可用于后续的推理阶段[^1]。 --- #### 2. 使用 ONNX Runtime 进行推理 一旦获得了 ONNX 文件,就可以利用 `onnxruntime` 库加载并运行推理。下面是一个 Python 示例代码片段来演示这一过程: ```python import cv2 import numpy as np import onnxruntime as ort def preprocess_image(image_path, input_size=(640, 640)): image = cv2.imread(image_path) resized = cv2.resize(image, input_size) normalized = resized / 255.0 transposed = np.transpose(normalized, (2, 0, 1)) expanded = np.expand_dims(transposed, axis=0).astype(np.float32) return expanded def postprocess_output(output_data): predictions = output_data[0].squeeze() boxes = predictions[:, :4] scores = predictions[:, 4:] class_ids = np.argmax(scores, axis=1) confidences = np.max(scores, axis=1) filtered_indices = np.where(confidences > 0.5)[0] final_boxes = [] final_class_ids = [] final_confidences = [] for i in filtered_indices: box = boxes[i] class_id = class_ids[i] confidence = confidences[i] final_boxes.append(box.tolist()) final_class_ids.append(class_id.item()) final_confidences.append(confidence.item()) return final_boxes, final_class_ids, final_confidences if __name__ == "__main__": session = ort.InferenceSession("yolov8n.onnx") # 替换为你自己的 .onnx 路径 input_name = session.get_inputs()[0].name output_names = [output.name for output in session.get_outputs()] image_path = "test.jpg" # 输入图像路径 input_tensor = preprocess_image(image_path) outputs = session.run(output_names, {input_name: input_tensor}) boxes, classes, confidences = postprocess_output(outputs) print(f"Detected objects: {len(boxes)}") for idx, box in enumerate(boxes): print(f"Object {idx}: Class={classes[idx]}, Confidence={confidences[idx]:.2f}, Box={box}") ``` 这段代码展示了如何读取输入图片、对其进行预处理、调用 ONNX 模型进行推理以及解析输出数据[^2]。 --- #### 3. 可视化结果 对于可视化部分,可以借助 OpenCV 来绘制边界框和类别标签: ```python def draw_bounding_boxes(image, boxes, classes, confidences, colors=None): if colors is None: colors = [(np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255)) for _ in range(len(set(classes)))] for box, cls, conf in zip(boxes, classes, confidences): color = colors[int(cls)] x_min, y_min, x_max, y_max = map(int, box[:4]) label = f"{cls} ({conf:.2f})" cv2.rectangle(image, (x_min, y_min), (x_max, y_max), color, thickness=2) cv2.putText(image, label, (x_min, y_min - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2) return image image = cv2.imread(image_path) result_image = draw_bounding_boxes(image.copy(), boxes, classes, confidences) cv2.imshow("Result", result_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 以上代码实现了在原始图像上叠加预测的目标框及其分类信息的功能[^3]。 --- #### 总结 本教程介绍了从准备环境到最终可视化的整个工作流,涵盖了模型转换、推理设置及后处理逻辑等内容。希望这些内容能够帮助理解 YOLOv8ONNX 部署的相关技术要点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伪_装

您的支持,是我持续创作的光

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值