pytorch入门8:学会transform的使用

"""
本节主要学会transform的使用
"""

from PIL import Image
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter
"""
transforms是对数据进行一系列转换的模块
比如输入一张图片->transforms工具箱(totensor/resize等等)->结果
"""
"""
transforms在python中的使用->tensor数据类型
通过transforms.ToTensor来看两个问题
1.transforms该如何使用
2.为什么要使用Tensor数据类型
"""

img_path = 'dataset/train/ants/0013035.jpg'
img = Image.open(img_path)
writer = SummaryWriter('transforms_log')

# 熟悉ToTensor方法的运用
trans_tensor = transforms.ToTensor()  # 首先定义一个ToTensor的对象
tensor_img = trans_tensor(img)
#print(tensor_img)
writer.add_image('tensor',tensor_img)
# 使用opencv
# import cv2
# cv_img = cv2.imread(img_path)

# 熟悉Normalize(归一化)的运用:(样本值-均值)/标准差
print(tensor_img[0][0][0])
trans_normalize = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])  #因为图片是三维的,所以需要输入三个均值和标准差
normalize_img = trans_normalize(tensor_img)
print(normalize_img[0][0][0])
writer.add_image('Normalize',normalize_img)

# 熟悉Resize的运用
print(img.size)
trans_resize = transforms.Resize((512,512))
# img PIL --> resize --> resize_img PIL
resize_img = trans_resize(img)
# resize_img PIL --> resize --> resize_img tensor
resize_img = trans_tensor(resize_img)
writer.add_image("resize",resize_img)

# 熟悉Compose的运用
trans_resize_2 = transforms.Resize(512)
compose_trans = transforms.Compose([trans_resize_2,trans_tensor])
img_resize_2 = compose_trans(img)
writer.add_image("compose",img_resize_2)

# 熟悉randomcrop
trans_random = transforms.RandomCrop((500,512))
trans_compose_2 = transforms.Compose([trans_random,trans_tensor])
for i in range(10):
    img_crop = trans_compose_2(img)
    writer.add_image('randomcup',img_crop,i)

writer.close()


你可能感兴趣的:(pytorch,pytorch,python)