深度学习 preprocess 预处理图片方式去 pytorch 化

发布于:2023-04-04 ⋅ 阅读:(585) ⋅ 点赞:(0)

我的模型需要线上部署了,想直接使用 onnx,而不是 pytorch,所以我需要把代码中关于 pytorch 的都删除了,比如下面这段代码,怎么使用其他库替代?

from torchvision import transforms


preprocess = transforms.Compose([
    transforms.Resize(224),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

下面是 ChatGPT 给我的答案:

可以使用 Pillow 和 numpy 库替代 torchvision 和 torch 中的操作,示例代码如下:

from PIL import Image
import numpy as np

def preprocess(image_path):
    image = Image.open(image_path)
    image = image.resize((224, 224))
    image = np.array(image)
    image = image.transpose((2, 0, 1))
    image = image.astype(np.float32)
    image /= 255.0
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    image = (image - mean) / std
    return image

这个函数将接受图像文件路径作为输入并返回预处理后的图像。


网站公告

今日签到

点亮在社区的每一天
去签到