import numpy as np
import cv2
import paddle.inference as paddle_infer

def preprocess_image(image_path):
    image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    print("原始:", "高:", image.shape[0], "宽:", image.shape[1], "通道数:", image.shape[2])
    width = 192
    height = 48
    scale = height / image.shape[0]
    w1 = int(image.shape[1] * scale)+1
    print(w1, height)
    image = cv2.resize(image, (w1, height))
    print("resize后:",  "高:", image.shape[0], "宽:", image.shape[1], "通道数:", image.shape[2])

    # 减均值除方差
    image = (image / 255.0 - 0.5) / 0.5
    print("减均值除方差后:", image.shape)
    if w1 < width:
        # 往右边填充
        image = cv2.copyMakeBorder(image, 0, 0, 0, width - w1, cv2.BORDER_CONSTANT, value=[0, 0, 0])
    image = image.transpose(2, 0, 1)
    print("处理后:", image.shape)

    # 添加批次维度
    image = np.expand_dims(image, axis=0)

    return image

def infer_paddle_model(model_path, params_path, image_path):
    """
    加载 PaddlePaddle 模型并对输入图像进行推理。

    :param model_path: PaddlePaddle 模型文件路径 (.pdmodel)
    :param params_path: PaddlePaddle 参数文件路径 (.pdiparams)
    :param image_path: 输入图像的路径
    :return: 推理结果
    """
    # 创建配置对象
    config = paddle_infer.Config(model_path, params_path)
    # 启用 GPU (如果需要)
    # config.enable_use_gpu(100, 0)
    
    # 创建预测器
    predictor = paddle_infer.create_predictor(config)

    # 获取输入名称和句柄
    input_names = predictor.get_input_names()
    print("输入名称:", input_names)
    input_handle = predictor.get_input_handle(input_names[0])

    # 预处理图像
    input_data = preprocess_image(image_path)
    print("预处理后图像形状:", input_data.shape, type(input_data))

    # 设置输入数据
    input_handle.reshape(input_data.shape)
    input_handle.copy_from_cpu(input_data.astype(np.float32))  # 确保转换为float32

    # 运行推理
    predictor.run()

    # 获取输出结果
    output_names = predictor.get_output_names()
    print("输出名称:", output_names)
    output_handle = predictor.get_output_handle(output_names[0])
    output_data = output_handle.copy_to_cpu()

    return output_data

if __name__ == "__main__":
    # PaddlePaddle 模型路径,请替换为实际路径
    model_path = r"C:\Users\Admin\Desktop\demo\export\inference.pdmodel"
    params_path = r"C:\Users\Admin\Desktop\demo\export\inference.pdiparams"
    # 输入图像路径,请替换为实际路径
    image_path = r"C:\Users\Admin\Desktop\demo\test\90\1.jpg"

    # 进行推理
    results = infer_paddle_model(model_path, params_path, image_path)

    # 打印推理结果
    print("推理结果:", results)

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐