Transforms data enhancement makes the same transformation on input and label pictures

When training the network, if data augmentation is used to expand the data set, pytorch is commonly used

transforms.Compose([
    transforms.RandomSizedCrop(max(resize)),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

Method to transform. There are many random transformation methods in transform. If you need to ensure that the input and label images undergo the same transformation, there will be problems.
So disassemble all transformation methods as follows:

p1 = random.randint(0,1)
p2 = random.randint(0,1)
transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.RandomCrop(128),
    transforms.RandomHorizontalFlip(p1),
    transforms.RandomVerticalFlip(p2)
])
seed = np.random.randint(2147483647)  # make a seed with numpy generator
random.seed(seed)  # apply this seed to img tranfsorms
x = transform(x)
random.seed(seed)  # apply this seed to img tranfsorms
t = transform(t)

Randomly given p1 p2 (0 or 1), respectively apply to the two probability random transformations in transforms, to ensure that input (x) and label(t) are transformed at the same time (with probability of 1) or unchanged at the same time (with probability of 0), For randomcrop, which does not depend on probability, the same seed can be set every time before the function is applied to ensure that the random crop area is the same.

Guess you like

Origin blog.csdn.net/qq_41872271/article/details/107265052