PyTorch深度学习——Transforms的使用

PyTorch深度学习——Transforms的使用_第1张图片

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

writer = SummaryWriter("logs")

img_path = r"C:\Users\22843\pythonProject3\data1\train\ants_image\0013035.jpg"

img = Image.open(img_path)

tensor_trans = transforms.ToTensor()   #Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor
tensor_img = tensor_trans(img)


writer.add_image("Tensor_img",tensor_img)

print(tensor_img)
writer.close()

transforms中的常用方法:

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

writer = SummaryWriter("logs")
img = Image.open(r"C:\Users\22843\pythonProject3\imgs\aa.png")
print(img)

#ToSensor   Convert a ..``PIL Image`` or ``numpy.ndarray`` to tensor.
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image("ToTensor",img_tensor)

#Normolize   Normalize a tensor image with mean and standard deviation
print(img_tensor[0][0][0])
trans_norm = transforms.Normalize([1,3,5],[3,2,1])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])
writer.add_image("Normalize",img_norm,1)


#Resize   Resize the input image to the given size.
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 -resize -2
trans_resize_2 = transforms.Resize(512)
#PIL->PIL->tensor
trans_compose = transforms.Compose([trans_resize_2,trans_totensor])
img_resize_2 = trans_compose(img)
writer.add_image("Resize",img_resize_2,1)

#RandomCrop
trans_random = transforms.RandomCrop(512)
trans_compose_2 = transforms.Compose([trans_resize_2,trans_totensor])
for i in range(10):
    img_crop = trans_compose_2(img)
    writer.add_image("RandomCrop",img_crop,i)


writer.close()

你可能感兴趣的:(PyTorch)