• Pytorch:反transform操作,实现从tensor转成PIL image


    该代码为transforms的反函数,实现从tensor转成PIL image,用于在框架的enumerate迭代中的中间图片可视化。

    代码思想如下,可以根据具体情况和需要进行修改

    def transform_invert(img_, transform_train):
        """
        将data 进行反transfrom操作
        :param img_: tensor
        :param transform_train: torchvision.transforms
        :return: PIL image
        """
        if 'Normalize' in str(transform_train):
            norm_transform = list(filter(lambda x: isinstance(x, transforms.Normalize), transform_train.transforms))
            mean = torch.tensor(norm_transform[0].mean, dtype=img_.dtype, device=img_.device)
            std = torch.tensor(norm_transform[0].std, dtype=img_.dtype, device=img_.device)
            img_.mul_(std[:, None, None]).add_(mean[:, None, None])
    
        img_ = img_.transpose(0, 2).transpose(0, 1)  # C*H*W --> H*W*C
        img_ = np.array(img_) * 255
    
        if img_.shape[2] == 3:
            img_ = Image.fromarray(img_.astype('uint8')).convert('RGB')
        elif img_.shape[2] == 1:
            img_ = Image.fromarray(img_.astype('uint8').squeeze())
        else:
            raise Exception("Invalid img shape, expected 1 or 3 in axis 2, but got {}!".format(img_.shape[2]) )
    
        return img_
  • 相关阅读:
    【JZOJ4743】积木【状压dp】
    学生增删改查练习
    Java关键字
    集合基本知识
    简单模拟用户登录
    遍历输入的字符串
    字符串截取
    equals与equalsIgnoreCase
    StringBuilder成员方法
    StringBuilder
  • 原文地址:https://www.cnblogs.com/sakuraie/p/13375894.html
Copyright © 2020-2023  润新知