Transform使用,transforms.ToTensor(),Resize(),Compose()

Transform使用,transforms.ToTensor(),Resize(),Compose()_第1张图片

 normalize的作用:归一化

Transform使用,transforms.ToTensor(),Resize(),Compose()_第2张图片

from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
writer = SummaryWriter('logs')
image = Image.open('hymenoptera_data/train/ants/0013035.jpg')
print(image)
# transforms.ToTensor()
trans_totensor = transforms.ToTensor()
image_tensor = trans_totensor(image)



# Normalize
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
image_norm = trans_norm(image_tensor)

# Resize
trans_resize = transforms.Resize((512,512))
image_resize = trans_resize(image)
# ->转tensor
image_resize = trans_totensor(image_resize)
print(image_resize)

# Compose,把几个转换组合在一起,先resize,然后toTensor
trans_resize2 = transforms.Resize(512)
# compose[]内部,第一个的输出,必须符合后面的输入类型,要相互匹配
trans_compose = transforms.Compose([trans_resize2,transforms.ToTensor()])
image_resize2 = trans_compose(image)

#Randomcrop
trans_randomcrop = transforms.RandomCrop((20,20))
trans_compose2 = transforms.Compose([trans_randomcrop,transforms.ToTensor()])
image_resize3 = trans_compose2(image)
for i in range(10):
    writer.add_image('random', image_resize3,i)

writer.close()
#下面写一下初始化对象时需要注意的点
class Resize(object):
    """Resize the input PIL Image to the given size.

    Args:
        size (sequence or int): Desired output size. If size is a sequence like
            (h, w), output size will be matched to this. If size is an int,
            smaller edge of the image will be matched to this number.
            i.e, if height > width, then image will be rescaled to
            (size * height / width, size)
        interpolation (int, optional): Desired interpolation. Default is
            ``PIL.Image.BILINEAR``
        #有默认值的不用管,无需赋值

    """
    #trans_resize = transforms.Resize((512,512)),初始化时,需要对Init中的size赋值

    def __init__(self, size, interpolation=Image.BILINEAR):
        assert isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)
        self.size = size
        self.interpolation = interpolation
    #image_resize = trans_resize(image),__call__就相当于无需使用.方法的形式来调用函数
    def __call__(self, img):
        """
        Args:
            img (PIL Image): Image to be scaled.

        Returns:
            PIL Image: Rescaled image.
        """
        return F.resize(img, self.size, self.interpolation)

    def __repr__(self):
        interpolate_str = _pil_interpolation_to_str[self.interpolation]
        return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
  • 要注意函数的输入输出,图片的类型PIL,Tensor,array
  • 主要使用类时,需要初始化对象,初始化对象时,需要给定init需要的参数
  • 不知道返回值的时候,使用print(...),print(type(...))
  • 最后可以使用tensorboard 看图片处理后的结果

如何使用tensorboard可以借鉴:

(3条消息) SummaryWriter的使用_可基大萌萌哒的马鹿的博客-CSDN博客https://blog.csdn.net/weixin_42934729/article/details/123356349

你可能感兴趣的:(深度学习,计算机视觉,人工智能)