Pytorch:torchvision.transforms中常见函数使用方法

Pytorch:torchvision.transforms中常见函数使用方法

常见的Transforms

  • Totensor
  • Normalize
  • resize
  • Compose
  • RandomCrop随机裁剪

代码中涉及到tensorboard 的使用,使用方式详见之前的文章:
https://blog.csdn.net/qq_41940277/article/details/130712118

from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms

writer=SummaryWriter("logs")
img=Image.open("dataset/train/ants/0013035.jpg") #任意图片所在位置
print(img)

#Totensor的使用
trans_totensor=transforms.ToTensor()
img_tensor=trans_totensor(img)
writer.add_image("tensor",img_tensor,1)

#Normalize
trans_norm=transforms.Normalize([0.5,.5,0.5],[0.5,0.5,0.5]) #图片三通道的均值和标准差
'''
    Args:
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channel.
        inplace(bool,optional): Bool to make this operation in-place.

'''
print(img_tensor[0][0][0])

img_norm=trans_norm(img_tensor)
'''
``output[channel] = (input[channel] - mean[channel]) / std[channel]``

'''
print(img_norm[0][0][0])
writer.add_image("norm",img_norm,1)


#resize
print(img.size)
trans_resize=transforms.Resize((512,512))
#img PIL-> resize->img_resize PIL
img_resize=trans_resize(img)
#img_resize PIL-> totensor -> img_resize tensor
img_resize=trans_totensor(img_resize)
writer.add_image("Resize", img_resize, 0)
print(img_resize)


#Compose()用法
trans_resize_2=transforms.Resize(512) #如果输入为整数时,512为短边长度,长边等比例放大
trans_compose= transforms.Compose([trans_resize_2,trans_totensor])
'''
Compose()中的参数需要是一个列表。
python中,列表表示的形式为【数据1,数据2,。。。】
在Compose中,数据需要是transforms类型
所以得到,Compose(【transforms参数1, transforms参数2,。。。。】)

'''
img_resize_2=trans_compose(img)
writer.add_image("Resize",img_resize_2,1)

#RandomCrop随机裁剪
trans_random=transforms.RandomCrop(100)
trans_compose_2=transforms.Compose([trans_random,trans_totensor])
for i in range(10):
    img_crop=trans_compose_2(img)
    writer.add_image("RandomCrop",img_crop,i)


writer.close()

感谢:PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】
视频网址:https://www.bilibili.com/video/BV1hE411t7RN?p=14&spm_id_from=pageDriver&vd_source=5b6e0605c1ed0f1db9c92503dd5994e0

你可能感兴趣的:(pytorch,python,深度学习,开发语言)