Pytorch中transforms.RandomResizedCrop使用说明

加载数据
训练集数据扩充(数据增强)和归一化。数据扩充(数据增强)的意义在于通过人为的随机范围裁剪,缩放,旋转等操作,增大训练集中的数据多样性、全面性,进而提高模型的泛化能力。

#训练集数据扩充和归一化
#在验证集上仅需要归一化
data_transforms = {
    
    
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224), #随机裁剪一个area然后再resize
        transforms.RandomHorizontalFlip(), #随机水平翻转
        transforms.ToTensor(),#归一化到[0.0,1.0]
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])#归一化到[-1.0,1.0]
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

RandomResizedCrop参数说明
看一下函数定义:

A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the Inception networks.

按某个随机的面积比例scale(默认:0.08到1.0)和一个随机的长宽比ratio(默认3.0/4到4.0/3)去裁剪原始图像。它通常用于训练神经网络。
Args参数:
size: expected output size of each edge。期望输出尺寸,如果只填一个数字,默认长宽相等。
scale: range of size of the origin size cropped。随机的面积比例,裁剪出的区域面积占原图总面积的比例。
ratio: range of aspect ratio of the origin aspect ratio cropped。随机的裁剪宽高比范围。
interpolation: Default: PIL.Image.BILINEAR 图像插值方法(双线性插值)。

"""

def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=Image.BILINEAR):
    if isinstance(size, tuple):
        self.size = size
    else:
        self.size = (size, size)
    if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
        warnings.warn("range should be of kind (min, max)")

    self.interpolation = interpolation
    self.scale = scale
    self.ratio = ratio

transforms.RandomResizedCrop(224) 将给定图像随机裁剪为不同的大小和宽高比,然后缩放所裁剪得到的图像为制定的大小;(即先随机采集,然后对裁剪得到的图像缩放为同一大小)
默认scale=(0.08, 1.0)。

假设原图是500*721,scale=(0.08, 1.0) ,ratio=(3. / 4., 4. / 3.),
那么原图的面积S0 = 500x721=360,500
那么随机裁剪出的最小区域(WxH)面积是 S0 x 0.08 = 360,500 x 0.08 = 28,840 = WxH。
且W/H处于(3. / 4., 4. / 3.)范围。
根据这个关系,便可以唯一确定W H的具体值。 假设W/H=1,那么W=H=sqrt(S0 x 0.08 )=sqrt(28,840 ) = 169.8 ~= 170。

猜你喜欢

转载自blog.csdn.net/thequitesunshine007/article/details/118703054