预处理之随机擦除
预处理之随机擦除
预处理之随机擦除
补充: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):
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)
if 'ToTensor' in str(transform_train):
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_
if __name__ == '__main__':
img = Image.open(r"./test.jpg").convert('RGB')
img_transform = transforms.Compose([transforms.ToTensor()])
img_tensor = img_transform(img)
print(img_tensor)
print(img_tensor.shape)
img = transform_invert(img_tensor, img_transform)
img.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/406c53a1ffc347f3b2c0f69cb293fe72.png)
随机擦除: RandomErasing
功能:对图像进行随机遮挡
主要参数说明:
- p:概率值,执行该操作的概率
- scale:遮挡区域的面积
- ratio:遮挡区域长宽比(a:长比宽,b:宽比长)
- value:设置遮挡区域的像素值,(R, G, B) or (Gray)
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.ToTensor() , # 转Tensor型变量
transforms.RandomErasing(p=1,scale=(0.01,0.35),ratio=(0.5,1),value=(0,0,255)), # 仿射变换
])
# 3.进行预处理
img_tensor = img_transform(img)
# 4.逆Transform变换
img = transform_invert(img_tensor, img_transform) # input: shape=[c h w]
# 5.进行预处理效果展示
img.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/8d20c0d2ded64fbc8b6809517997c4c9.png)