补充:transform.invert 预处理逆操作
from PIL import Image
from torchvision import transforms
import torch
import numpy as np
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):
# 分析transforms里的Normalize
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
# 如果有ToTensor,那么之前数值就会被压缩至0-1之间。现在需要反变换回来,也就是乘255
if 'ToTensor' in str(transform_train):
img_ = np.array(img_) * 255
# 先将np的元素转换为uint8数据类型,然后转换为PIL.Image类型
if img_.shape[2] == 3: # 若通道数为3 需要转为RGB类型
img_ = Image.fromarray(img_.astype('uint8')).convert('RGB')
elif img_.shape[2] == 1: # 若通道数为1 需要压缩张量的维度至2D
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_
if __name__ == '__main__':
img = Image.open(r"./test.jpg").convert('RGB')
img_transform = transforms.Compose([transforms.ToTensor()])
img_tensor = img_transform(img)
# img_tensor.unsqueeze_(dim=0) # C*H*W to B*C*H*W
print(img_tensor)
print(img_tensor.shape)
img = transform_invert(img_tensor, img_transform) # input: shape=[c h w]
img.show()
一 转灰度图:Grayscale
功能:将图片转换为灰度图
主要参数说明:
- num_ ouput channels: 输出通道数,只能设1或3
from PIL import Image
from torchvision import transforms
from utils import transform_invert
if __name__ == '__main__':
# 1.读取图像
img = Image.open(r"./cat.png").convert('RGB')
# 2.确定预处理方式
img_transform = transforms.Compose([## transforms.Resize((300,300)), # 重置大小为300*300
transforms.Grayscale(num_output_channels=3), # 色相
transforms.ToTensor() # 转Tensor型变量
])
# 3.进行预处理
img_tensor = img_transform(img)
# 4.逆Transform变换
img = transform_invert(img_tensor, img_transform) # input: shape=[c h w]
# 5.进行预处理效果展示
img.show()
二 随机转灰度图:RandomGrayscale
功能:依概率将图片转换为灰度图
主要参数说明:
- p:概率值,图像被转换为灰度图的概率
from PIL import Image
from torchvision import transforms
from utils import transform_invert
if __name__ == '__main__':
# 1.读取图像
img = Image.open(r"./cat.png").convert('RGB')
# 2.确定预处理方式
img_transform = transforms.Compose([## transforms.Resize((300,300)), # 重置大小为300*300
transforms.RandomGrayscale(p=0.9), # 转灰度图
transforms.ToTensor() # 转Tensor型变量
])
# 3.进行预处理
img_tensor = img_transform(img)
# 4.逆Transform变换
img = transform_invert(img_tensor, img_transform) # input: shape=[c h w]
# 5.进行预处理效果展示
img.show()