def initialise_augmenter(): # Horizontal and Vertical Flips (set to 1 as the SomeOf function will choose when to apply these itself) horizontal_flip = iaa.Fliplr(1) #0.5) vertical_flip = iaa.Flipud(1) #0.5) # 90, 180 and 270 degree rotations rotate_90 = iaa.Affine(rotate=90) rotate_180 = iaa.Affine(rotate=180) rotate_270 = iaa.Affine(rotate=270) # Translations of -10% to 10% of the image's pixels translate_x = iaa.TranslateX(percent=(-0.1, 0.1)) translate_y = iaa.TranslateY(percent=(-0.1, 0.1)) # Scale the image between 0.75 and 1.1 of the original size scale_x = iaa.ScaleX((0.75, 1.1)) scale_y = iaa.ScaleY((0.75, 1.1)) # Shear the image between -20 and 20 degrees shear_x = iaa.ShearX((-20, 20)) shear_y = iaa.ShearY((-20, 20)) augmentation = iaa.SomeOf((0, None), [ horizontal_flip, vertical_flip, iaa.OneOf([rotate_90, rotate_180, rotate_270]), translate_x, translate_y, scale_x, scale_y, shear_x, shear_y ], random_order=True) return augmentation
def _lane_argue(*, image, lane_src): lines_tuple = [[(float(pt['x']), float(pt['y'])) for pt in line_spec] for line_spec in lane_src['Lines']] lss = [ia_LineString(line_tuple_spec) for line_tuple_spec in lines_tuple] lsoi = LineStringsOnImage(lss, shape=image.shape) color_shift = iaa.OneOf([ iaa.GaussianBlur(sigma=(0.5, 1.5)), iaa.LinearContrast((1.5, 1.5), per_channel=False), iaa.Multiply((0.8, 1.2), per_channel=0.2), iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.1 * 255), per_channel=0.5), iaa.WithColorspace(to_colorspace=iaa.CSPACE_HSV, from_colorspace=iaa.CSPACE_RGB, children=iaa.WithChannels(0, iaa.Multiply((0.7, 1.3)))), iaa.WithColorspace(to_colorspace=iaa.CSPACE_HSV, from_colorspace=iaa.CSPACE_RGB, children=iaa.WithChannels(1, iaa.Multiply((0.1, 2)))), iaa.WithColorspace(to_colorspace=iaa.CSPACE_HSV, from_colorspace=iaa.CSPACE_RGB, children=iaa.WithChannels(2, iaa.Multiply((0.5, 1.5)))), ]) posion_shift = iaa.SomeOf(4, [ iaa.Fliplr(), iaa.Crop(percent=([0, 0.2], [0, 0.15], [0, 0], [0, 0.15]), keep_size=True), iaa.TranslateX(px=(-16, 16)), iaa.ShearX(shear=(-15, 15)), iaa.Rotate(rotate=(-15, 15)) ]) aug = iaa.Sequential([ iaa.Sometimes(p=0.6, then_list=color_shift), iaa.Sometimes(p=0.6, then_list=posion_shift) ], random_order=True) batch = ia.Batch(images=[image], line_strings=[lsoi]) batch_aug = list(aug.augment_batches([batch]))[0] # augment_batches returns a generator image_aug = batch_aug.images_aug[0] lsoi_aug = batch_aug.line_strings_aug[0] lane_aug = [[dict(x=kpt.x, y=kpt.y) for kpt in shapely_line.to_keypoints()] for shapely_line in lsoi_aug] return image_aug, dict(Lines=lane_aug)
def someAug(): bg = iap.Uniform(16, 18) #Creating a series of augmentations shearXY = iaa.Sequential([ iaa.ShearY(iap.Uniform(-10, 10), cval=bg), iaa.ShearX(iap.Uniform(-10, 10), cval=bg) ]) rotate = iaa.Rotate(rotate=iap.Choice([-30, -15, 15, 30], p=[0.25, 0.25, 0.25, 0.25]), cval=bg) pwAff = iaa.PiecewiseAffine(scale=(0.01, 0.06), cval=bg) affine = iaa.Affine(scale={ "x": iap.Uniform(1.1, 1.2), "y": iap.Uniform(1.1, 1.2) }, cval=bg) noise = iaa.AdditiveGaussianNoise(loc=0, scale=(0, 0.025 * 255)) #Using SomeOf to randomly select some augmentations someAug = iaa.SomeOf(iap.Choice([2, 3, 4], p=[1 / 3, 1 / 3, 1 / 3]), [affine, shearXY, pwAff, rotate, noise], random_order=True) return someAug
def augmentation(X, y, masks, itterations): ys = np.concatenate( (y[:, :, np.newaxis], y[:, :, np.newaxis], y[:, :, np.newaxis]), axis=2) masks = np.concatenate( (masks[:, :, np.newaxis], masks[:, :, np.newaxis], masks[:, :, np.newaxis]), axis=2) B = np.concatenate((ys, X, masks), axis=2).astype(np.uint8) A = np.zeros((itterations, np.shape(B)[0], np.shape(B)[1], np.shape(B)[2])) for num in range(itterations): aug1 = iaa.Affine(scale={"x": (1, 1.5), "y": (1, 1.5)}) aug2 = iaa.Fliplr(1) aug3 = iaa.Flipud(1) aug4 = iaa.ShearX((-20, 20), mode='reflect') aug5 = iaa.ShearY((-20, 20), mode='reflect') aug6 = iaa.Rotate((-45, 45), mode='reflect') aug7 = iaa.WithChannels((3, 4, 5), iaa.Multiply((0.5, 1.5))) aug_list = [aug1, aug2, aug3, aug4, aug5, aug6, aug7] ID = np.random.randint(0, len(aug_list)) A[num, :, :, :] = aug_list[ID](image=B) aug_y = A[:, :, :, 0] aug_X = A[:, :, :, 3:6] aug_masks = A[:, :, :, 8] return aug_X, aug_y, aug_masks
def shear(image): # shear image randomly between -25 and 25 degree aug_x = iaa.ShearX((-25, 25)) aug_y = iaa.ShearY((-25, 25)) image_aug = aug_x(image=image) image_aug = aug_y(image=image_aug) return image_aug
def shearX(shear_amount, input_path, output_path, image_count): images = [] labels = [] ia.seed(1) for img_path in range(image_count): img = imageio.imread(input_path + '/images/' + str(img_path) + '.png') images.append(img) lbl = imageio.imread(input_path + '/labels/' + str(img_path) + '.png') labels.append(lbl) seq = iaa.Sequential( [ iaa.ShearX((shear_amount)), ] ) images_aug = seq(images=images) labels_aug = seq(images=labels) path = os.path.join(output_path, 'images') os.mkdir(path) path = os.path.join(output_path, 'labels') os.mkdir(path) for indx, i in enumerate(images_aug): imageio.imwrite(output_path + '/images/' + 'shear'+ '_' + str(indx) + '.png', i) for indx, i in enumerate(labels_aug): imageio.imwrite(output_path + '/labels/' + 'shear'+ '_' + str(indx) + '.png', i) print("Shear results were saved given directory.")
def augment_geometric( d_scale=0.05, d_translate=0.02, d_rotate=3, d_shear_x=5, d_shear_y=1, ): return iaa.Sequential( [ iaa.Sometimes( 0.5, iaa.Affine( scale=(1 / (1 + d_scale), (1 + d_scale)), translate_percent=dict( x=(-d_translate, d_translate), y=(-d_translate, d_translate), ), rotate=(-d_rotate, d_rotate), ), ), iaa.Sometimes(0.5, iaa.ShearX(shear=(-d_shear_x, d_shear_x))), iaa.Sometimes(0.5, iaa.ShearY(shear=(-d_shear_y, d_shear_y))), ], random_order=True, )
def chapter_augmenters_shearx(): fn_start = "geometric/shearx" image = ia.quokka(size=(128, 128)) aug = iaa.ShearX((-20, 20)) run_and_save_augseq( fn_start + ".jpg", aug, [image for _ in range(4*2)], cols=4, rows=2)
def __init__(self): self.augmentations = augmenters.Sequential([ augmenters.Sometimes(0.5, augmenters.Flipud(0.5)), augmenters.Sometimes(0.5, augmenters.Fliplr(0.5)), augmenters.Sometimes(0.5, augmenters.Rotate((-45, 45))), augmenters.Sometimes(0.25, augmenters.ShearX((-20, 20))), augmenters.Sometimes( 0.1, augmenters.AdditiveGaussianNoise(scale=(0, 0.1 * 255))) ], random_order=True)
def __init__(self,num_of_augms=0): self.num_of_augms=num_of_augms self.aug=iaa.OneOf([ iaa.Sequential([ iaa.LinearContrast(alpha=(0.75, 1.5)), iaa.Fliplr(0.5) ]), iaa.Sequential([ iaa.Grayscale(alpha=(0.1, 0.9)), iaa.Affine( translate_percent={"y": (-0.15, 0.15)} ) ]), iaa.Sequential([ iaa.LinearContrast((0.6, 1.4)), iaa.ShearX((-10, 10)) ]), iaa.Sequential([ iaa.GaussianBlur(sigma=(0, 1)), iaa.ShearY((-10, 10)) ]), iaa.Sequential([ iaa.Cutout(nb_iterations=(1, 2), size=0.1, squared=False), iaa.Multiply((0.8, 1.2), per_channel=0.25), iaa.Fliplr(0.5), ]), iaa.Sequential([ iaa.LinearContrast((0.6, 1.4)), iaa.Affine( translate_percent={"x": (-0.25, 0.25)} ) ]), iaa.Sequential([ iaa.Cutout(nb_iterations=(1, 5), size=0.1, squared=False), iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 15), per_channel=0.5), iaa.Affine( scale={"x": (0.9, 1.1), "y": (0.9, 1.1)}, ) ]), iaa.Sequential([ iaa.CoarseDropout((0.0, 0.05), size_percent=(0.02, 0.25)), iaa.GaussianBlur(sigma=(0, 2)), iaa.Affine( scale={"x": (0.8, 1.2), "y": (0.8, 1.2)} )]) # iaa.Sequential([ # iaa.Cutout(nb_iterations=(1, 5), size=0.05, squared=False), # iaa.Grayscale(alpha=(0.0, 0.50)), # iaa.ScaleX((0.75, 1.25)) # ]), # iaa.Sequential([ # iaa.LinearContrast((0.8, 1.2), per_channel=True), # iaa.PerspectiveTransform(scale=(0.01, 0.15)) # ]) ])
def dictShearX(baseImageListFunc, baseMaskListFunc, fullImageListFunc, segmapListFunc): print('ShearX, starting number of images:', len(segmapListFunc)) shearX_x00percent = 2 shearX = iaa.ShearX((-3, 3), mode="reflect") shearX._mode_segmentation_maps = "reflect" alteredImageListFunc, alteredMaskListFunc = expandList(baseImageListFunc, baseMaskListFunc, shearX_x00percent) (alteredImageListFunc, alteredMaskListFunc) = shearX(images=alteredImageListFunc, segmentation_maps=alteredMaskListFunc) fullImageListFunc.extend(alteredImageListFunc) segmapListFunc.extend(alteredMaskListFunc) return fullImageListFunc, segmapListFunc
def shear_x(magnitude: int) -> iaa.ShearY: """ Apply x shear to the image and boxes Tensorflow Policy Equivalent: shear_x :type magnitude: int :param magnitude: magnitude of y shear :rtype: iaa.ShearY :return: Method to y shear bounding boxes """ level = _shear_mag_to_arg(magnitude) return iaa.ShearX(level)
def shear_x_bbox(magnitude: int) -> iaa.BlendAlphaBoundingBoxes: """ Apply x shear only to bboxes Tensorflow Policy Equivalent: shear_x_only_bboxes :type magnitude: int :param magnitude: magnitude of x shear :rtype: iaa.BlendAlphaBoundingBoxes :return: Method to x shear bounding boxes """ level = _shear_mag_to_arg(magnitude) return iaa.BlendAlphaBoundingBoxes( None, foreground=iaa.ShearX(level), )
def __init__(self,num_of_augms=0): self.num_of_augms=num_of_augms self.aug=iaa.OneOf([ iaa.Sequential([ iaa.LinearContrast(alpha=(0.75, 1.5)), iaa.Fliplr(0.5) ]), iaa.Sequential([ iaa.Grayscale(alpha=(0.1, 0.9)), iaa.Affine( translate_percent={"y": (-0.15, 0.15)} ) ]), iaa.Sequential([ iaa.Solarize(0.5, threshold=(0, 256)), iaa.ShearX((-10, 10)) ]), iaa.Sequential([ iaa.GaussianBlur(sigma=(0, 1)), iaa.ShearY((-10, 10)) ]), iaa.Sequential([ iaa.Multiply((0.5, 1.5), per_channel=0.25), iaa.Fliplr(0.5), ]), iaa.Sequential([ iaa.HistogramEqualization(), iaa.Affine( translate_percent={"x": (-0.25, 0.25)}, shear=(-8, 8) ) ]), iaa.Sequential([ iaa.Crop(percent=(0.01, 0.1)), iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), iaa.Affine( scale={"x": (0.9, 1.1), "y": (0.9, 1.1)}, ) ]), iaa.Sequential([ iaa.GaussianBlur(sigma=(0, 0.9)), iaa.Affine( scale={"x": (0.8, 1.2), "y": (0.8, 1.2)} ) ]) ])
def __call__(self, sample): img, annot = sample.image, sample.annotation unique_labels = np.unique( annot[:, 4].astype('int').astype('str')).tolist() bbs = BoundingBoxesOnImage([ BoundingBox(x1=ann[0], y1=ann[1], x2=ann[2], y2=ann[3], label=str(int(ann[4]))) for ann in annot ], shape=img.shape) aug = iaa.BlendAlphaBoundingBoxes(labels=unique_labels, foreground=iaa.ShearX(self.v)) img_aug, bbs_aug = aug(image=img, bounding_boxes=bbs) annot_aug = np.array( [[bb.x1, bb.y1, bb.x2, bb.y2, np.float32(bb.label)] for bb in bbs_aug]) masks = [] if sample.masks_and_category is not None: for index in sample.masks_and_category: masks.append(index[0]) mask_aug = [] if masks is not None: for mask in masks: mask = SegmentationMapsOnImage(mask, shape=img.shape).arr segmap, _ = aug(image=mask, bounding_boxes=bbs) mask_aug.append(segmap) # back to 2D array mask_result = [] for mask in mask_aug: mask_result.append(mask[:, :, 0]) for i, index in enumerate(sample.masks_and_category): index[0] = mask_result[i] # the shape has to be at least (0,5) if len(annot_aug) == 0: annot_aug = np.zeros((0, 5)) sample.image = img_aug sample.annotation = annot_aug
def build_augmenters(args, augmenters=None): ''' Construct a list of augmenters which rely on the arguments handled by the parent parser''' if augmenters is None: augmenters = [] opacity_range = args.opacity if opacity_range != (-1.0, -1.0): # set the alpha channel to a random value if opacity_range == (1.0, 1.0): opacity_range = (1.0) augmenters.insert( 0, iaa.Lambda(func_images=set_alpha_wrapper(opacity_range))) scale = args.scale if scale != (1.0, 1.0): augmenters.append( iaa.Affine(scale=scale) ) # scale the image between 20% to 125% of its original size rotate = args.rotate if rotate != (0.0, 0.0): augmenters.append( iaa.Rotate(rotate) ) # rotate the image somewhere in the range of -10.0 - 10.0 deg shear = args.shear if shear != (0.0, 0.0): augmenters.append( iaa.ShearX(shear) ) # rotate the image somewhere in the range of -10.0 - 10.0 deg noise = args.noise if noise != (0, 0): augmenters.append(iaa.AdditiveGaussianNoise(scale=noise)) grayscale = args.grayscale if grayscale != (0.0, 1.0): augmenters.append( iaa.WithChannels([0, 1, 2], iaa.Grayscale(alpha=(0.0, 1.0)))) return augmenters
def __call__(self, sample): img, annot = sample['img'], sample['annot'] bbs = BoundingBoxesOnImage([ BoundingBox(x1=ann[0], y1=ann[1], x2=ann[2], y2=ann[3], label=str(int(ann[4]))) for ann in annot ], shape=img.shape) aug = iaa.ShearX(self.v) img_aug, bbs_aug = aug(image=img, bounding_boxes=bbs) annot_aug = np.array( [[bb.x1, bb.y1, bb.x2, bb.y2, np.float32(bb.label)] for bb in bbs_aug]) # the shape has to be at least (0,5) if len(annot_aug) == 0: annot_aug = np.zeros((0, 5)) return {'img': img_aug, 'annot': annot_aug}
def get_aug(aug_cfg): seq = iaa.Sequential( [ iaa.Sometimes( aug_cfg["Shear"]["p"], iaa.OneOf([ iaa.ShearX(aug_cfg["Shear"]["X"]), iaa.ShearY(aug_cfg["Shear"]["Y"]), ]), ), iaa.Sometimes( aug_cfg["GaussianBlur"]["p"], iaa.GaussianBlur(sigma=aug_cfg["GaussianBlur"]["sigma"]), ), iaa.OneOf([ iaa.LinearContrast(aug_cfg["LinearContrast"]["alpha"]), iaa.AdditiveGaussianNoise( loc=aug_cfg["AdditiveGaussianNoise"]["loc"], scale=aug_cfg["AdditiveGaussianNoise"]["scale"], per_channel=aug_cfg["AdditiveGaussianNoise"] ["per_channel"], ), iaa.Multiply( aug_cfg["Multiply"]["mul"], per_channel=aug_cfg["Multiply"]["per_channel"], ), ]), iaa.Sometimes( aug_cfg["Affine"]["p"], iaa.Affine( translate_percent=iap.Normal( *aug_cfg["Affine"]["translate_percent"]), rotate=iap.Normal(*aug_cfg["Affine"]["rotate"]), scale=None, ), ), ], random_order=True, ) return seq
def gen_steps(): STEPS=[ iaa.Rotate((-50,-20)), iaa.Rotate((20,50)), iaa.Affine(shear=(-30,-10)), iaa.Affine(shear=(10,30)), iaa.ShearX(((-10, 10))), iaa.ShearY(((-10, 10))), iaa.Affine(scale=(0.5, 1.5)), iaa.Affine(scale=(1, 2)), iaa.Affine(translate_px={"x": (1, random.randint(300,800)), "y": (1, random.randint(300,800))}), [ iaa.Affine(translate_px={"x": (1, random.randint(300,800)), "y": (1, random.randint(300,800))}), iaa.Affine(shear=(-15,15)), ], [ iaa.Affine(translate_px={"x": (1, random.randint(300,800)), "y": (1, random.randint(300,800))}), iaa.Affine(shear=(-15,15)), ], ] return STEPS
def augmentations1(images): seq1 = iaa.PerspectiveTransform(scale=(0.01, 0.15)) # perspective trans seq2 = iaa.ElasticTransformation(alpha=(0, 2.5), sigma=0.25) #elastictrans seq3 = iaa.Dropout((0.05, 0.1), per_channel=0.5) # 점모양 노이즈 seq4 = iaa.PiecewiseAffine(scale=(0.01, 0.03)) #piecewiseaffine seq5 = iaa.ShearX((-20, 20)) seq6 = iaa.Affine(scale=(0.5, 1.5))#scale seq7 = iaa.CropAndPad(percent=(-0.17, 0.17)) seq8 = iaa.pillike.FilterSharpen() print("image augmentation beginning") img1=seq1.augment_images(images) img2=seq2.augment_images(images) img3=seq3.augment_images(images) img4=seq4.augment_images(images) img5=seq5.augment_images(images) img6=seq6.augment_images(images) img7=seq7.augment_images(images) img8=seq8.augment_images(images) print("proceed to next augmentations") list = [img1, img2, img3, img4, img5, img6, img7, img8] return list
def __call__(self, sample): img, annot = sample['img'], sample['annot'] unique_labels = np.unique( annot[:, 4].astype('int').astype('str')).tolist() bbs = BoundingBoxesOnImage([ BoundingBox(x1=ann[0], y1=ann[1], x2=ann[2], y2=ann[3], label=str(int(ann[4]))) for ann in annot ], shape=img.shape) aug = iaa.BlendAlphaBoundingBoxes(labels=unique_labels, foreground=iaa.ShearX(self.v)) img_aug, bbs_aug = aug(image=img, bounding_boxes=bbs) annot_aug = np.array( [[bb.x1, bb.y1, bb.x2, bb.y2, np.float32(bb.label)] for bb in bbs_aug]) # the shape has to be at least (0,5) if len(annot_aug) == 0: annot_aug = np.zeros((0, 5)) return {'img': img_aug, 'annot': annot_aug}
# loc=0, scale=(0.0, 0.02*255), per_channel=0.5 # ), # iaa.Add((-15, 15), per_channel=0.5), # iaa.Multiply((0.8, 1.2), per_channel=0.5), # iaa.imgcorruptlike.Contrast(severity=1), # iaa.imgcorruptlike.Brightness(severity=2), iaa.ContrastNormalization((0.1, 1.5), per_channel=0.5), iaa.WithHueAndSaturation([ iaa.WithChannels(0, iaa.Add((-15, 15))), iaa.WithChannels(1, iaa.Add((-20, 20))), ]), iaa.GammaContrast((0.3, 1.5)), iaa.WithBrightnessChannels(iaa.Add((-30, 70))), iaa.ScaleX((0.5, 1.5)), iaa.ScaleY((0.5, 1.5)), iaa.ShearX((-10, 10)), iaa.ShearY((-10, 10)), ], random_order=True) ], random_order=True) def augment_pair(fg, label): # print('Augment start') label_i, segmaps_aug_i = seq(images=fg, segmentation_maps=label) # print('Augment ok') return label_i, segmaps_aug_i #res = [1080, 960]
iaa.OneOf([ iaa.LinearContrast((0.80, 1.1)), iaa.Multiply((0.9, 1.5)), # iaa.pillike.Autocontrast((10, 20), per_channel=True), iaa.Sometimes(0.50, iaa.OneOf([ iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.03*255)), iaa.PiecewiseAffine(scale=(0.01, 0.05)) ]), ), ]), iaa.Sometimes(0.8, iaa.OneOf([ iaa.OneOf([ iaa.ShearX((-5,5)), iaa.ShearY((-5,5)) ]), iaa.OneOf([ iaa.Affine( scale={"x": (0.8, 1), "y": (0.8, 1)} ), iaa.Affine( translate_percent={"x": (-0.05, 0.05), "y": (-0.05, 0.05)} ), iaa.Affine( rotate=(-4, 4) ) ]), ]), ),
def GenerateRandomImgaugAugmentation( pNbAugmentations=5, # number of augmentations pEnableResizing=True, # enable scaling pScaleFactor=0.5, # maximum scale factor pEnableCropping=True, # enable cropping pCropFactor=0.25, # maximum crop out size (minimum new size is 1.0-pCropFactor) pEnableFlipping1=True, # enable x flipping pEnableFlipping2=True, # enable y flipping pEnableRotation90=True, # enable rotation pEnableRotation=True, # enable rotation pMaxRotationDegree=15, # maximum shear degree pEnableShearX=True, # enable x shear pEnableShearY=True, # enable y shear pMaxShearDegree=15, # maximum shear degree pEnableDropOut=True, # enable pixel dropout pMaxDropoutPercentage=.1, # maximum dropout percentage pEnableBlur=True, # enable gaussian blur pBlurSigma=.25, # maximum sigma for gaussian blur pEnableSharpness=True, # enable sharpness pSharpnessFactor=.1, # maximum additional sharpness pEnableEmboss=True, # enable emboss pEmbossFactor=.1, # maximum emboss pEnableBrightness=True, # enable brightness pBrightnessFactor=.1, # maximum +- brightness pEnableRandomNoise=True, # enable random noise pMaxRandomNoise=.1, # maximum random noise strength pEnableInvert=False, # enables color invert pEnableContrast=True, # enable contrast change pContrastFactor=.1, # maximum +- contrast ): augmentationMap = [] augmentationMapOutput = [] if pEnableResizing: if random.Random().randint(0, 1) == 1: randomResizeX = 1 - random.Random().random() * pScaleFactor else: randomResizeX = 1 + random.Random().random() * pScaleFactor if random.Random().randint(0, 1) == 1: randomResizeY = 1 - random.Random().random() * pScaleFactor else: randomResizeY = 1 + random.Random().random() * pScaleFactor aug = iaa.Resize({"height": randomResizeY, "width": randomResizeX}) augmentationMap.append(aug) if pEnableCropping: randomCrop2 = random.Random().random() * pCropFactor randomCrop4 = random.Random().random() * pCropFactor randomCrop1 = random.Random().random() * pCropFactor randomCrop3 = random.Random().random() * pCropFactor aug = iaa.Crop(percent=(randomCrop1, randomCrop2, randomCrop3, randomCrop4)) augmentationMap.append(aug) if pEnableFlipping1: aug = iaa.Fliplr() augmentationMap.append(aug) if pEnableFlipping2: aug = iaa.Flipud() augmentationMap.append(aug) if pEnableRotation90: randomNumber = random.Random().randint(1, 3) aug = iaa.Rot90(randomNumber) augmentationMap.append(aug) if pEnableRotation: if random.Random().randint(0, 1) == 1: randomRotation = random.Random().random() * pMaxRotationDegree else: randomRotation = -random.Random().random() * pMaxRotationDegree aug = iaa.Rotate(randomRotation) augmentationMap.append(aug) if pEnableShearX: if random.Random().randint(0, 1) == 1: randomShearingX = random.Random().random() * pMaxShearDegree else: randomShearingX = -random.Random().random() * pMaxShearDegree aug = iaa.ShearX(randomShearingX) augmentationMap.append(aug) if pEnableShearY: if random.Random().randint(0, 1) == 1: randomShearingY = random.Random().random() * pMaxShearDegree else: randomShearingY = -random.Random().random() * pMaxShearDegree aug = iaa.ShearY(randomShearingY) augmentationMap.append(aug) if pEnableDropOut: randomDropOut = random.Random().random() * pMaxDropoutPercentage aug = iaa.Dropout(p=randomDropOut, per_channel=False) augmentationMap.append(aug) if pEnableBlur: randomBlur = random.Random().random() * pBlurSigma aug = iaa.GaussianBlur(randomBlur) augmentationMap.append(aug) if pEnableSharpness: randomSharpness = random.Random().random() * pSharpnessFactor aug = iaa.Sharpen(randomSharpness) augmentationMap.append(aug) if pEnableEmboss: randomEmboss = random.Random().random() * pEmbossFactor aug = iaa.Emboss(randomEmboss) augmentationMap.append(aug) if pEnableBrightness: if random.Random().randint(0, 1) == 1: randomBrightness = 1 - random.Random().random() * pBrightnessFactor else: randomBrightness = 1 + random.Random().random() * pBrightnessFactor aug = iaa.Add(randomBrightness) augmentationMap.append(aug) if pEnableRandomNoise: if random.Random().randint(0, 1) == 1: randomNoise = 1 - random.Random().random() * pMaxRandomNoise else: randomNoise = 1 + random.Random().random() * pMaxRandomNoise aug = iaa.MultiplyElementwise(randomNoise, per_channel=True) augmentationMap.append(aug) if pEnableInvert: aug = iaa.Invert(1) augmentationMap.append(aug) if pEnableContrast: if random.Random().randint(0, 1) == 1: randomContrast = 1 - random.Random().random() * pContrastFactor else: randomContrast = 1 + random.Random().random() * pContrastFactor aug = iaa.contrast.LinearContrast(randomContrast) augmentationMap.append(aug) widthFactor = 1 heightFactor = 1 arr = numpy.arange(0, len(augmentationMap)) numpy.random.shuffle(arr) switchWidthHeight = False for i in range(pNbAugmentations): augmentationMapOutput.append(augmentationMap[arr[i]]) if arr[i] == 0: widthFactor *= randomResizeX heightFactor *= randomResizeY if arr[i] == 1: widthFactor *= (1.0 - (randomCrop2 + randomCrop4)) heightFactor *= (1.0 - (randomCrop1 + randomCrop3)) if arr[i] == 4: if randomNumber == 1 or randomNumber == 3: switchWidhtHeight = True return iaa.Sequential( augmentationMapOutput), widthFactor, heightFactor, switchWidthHeight
) seq_blur = iaa.Sequential([ iaa.Crop(px=(1, 16), keep_size=False), iaa.Fliplr(0.5), iaa.GaussianBlur(sigma=(0, 3.0)) ]) seq_rot = iaa.Sequential([ iaa.PerspectiveTransform(scale=(0.01, 0.15)), iaa.Rot90((1, 3)) ]) seq_shear = iaa.Sequential([ iaa.Crop(px=(1, 16), keep_size=False), iaa.ShearX((-20, 20)), iaa.ShearY((-20,20)) ]) seq_scale = iaa.Sequential([ iaa.Affine(scale={"x": (0.5, 1.5), "y": (0.5, 1.5)}) ]) seq_offset = iaa.Sequential([ iaa.Affine(translate_px={"x": (-100, 100), "y": (-100, 100)}), iaa.Crop(px=(1, 16), keep_size=False) ]) def create_aug_img(folder_path):
iaa.Cutout(fill_mode="constant", cval=(0, 255), fill_per_channel=1), iaa.SaltAndPepper(0.05), iaa.GaussianBlur(1.5), iaa.MotionBlur(k=15, angle=60, direction=1), iaa.MotionBlur(k=5, angle=60, direction=-1), iaa.Grayscale(0.5), iaa.SigmoidContrast(gain=10, cutoff=0.3), iaa.LogContrast(0.7), iaa.LogContrast(1.3), iaa.Sharpen(alpha=0.2, lightness=0.9), iaa.Sharpen(alpha=0.2, lightness=1.2), iaa.Fliplr(1), iaa.Flipud(1), iaa.Rotate(15), iaa.Rotate(-15), iaa.ShearX(-10), iaa.ShearX(10), iaa.ShearY(-10), iaa.ShearY(10), iaa.ScaleX(0.7), iaa.ScaleX(1.3), iaa.ScaleY(0.7), iaa.ScaleY(1.3), ] def custom_imshow(imgList, labels): fig = plt.figure() rows = 2 cols = 5
f"{class_name} class batch augmentation complete.\nBatch count: {i // 10}\n" ) img_batch = [] os.chdir("..") aug = iaa.SomeOf(3, [ iaa.OneOf([ iaa.Affine(scale=(0.5, 1.5)), iaa.ScaleX((0.5, 1.5)), iaa.ScaleY((0.5, 1.5)), ]), iaa.OneOf([ iaa.Rotate((-180, 180)), iaa.ShearX((-60, 60)), iaa.ShearY((-60, 60)), ]), iaa.OneOf([ iaa.Fliplr(0.5), iaa.Flipud(0.5), ]), iaa.OneOf([ iaa.AverageBlur(k=(2, 6)), iaa.GaussianBlur(sigma=(0.0, 2.0)), iaa.Sharpen(alpha=(0.0, 0.8), lightness=(0.8, 1.2)), ]), iaa.OneOf([ iaa.imgcorruptlike.GaussianNoise(severity=random.randint(1, 3)), iaa.imgcorruptlike.ImpulseNoise(severity=random.randint(1, 3)), iaa.imgcorruptlike.ElasticTransform(severity=random.randint(1, 3)),
#These three are from contrast module, the above five from blur module. sometimes2(iaa.HistogramEqualization()), sometimes2(iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6))), sometimes2(iaa.LinearContrast(alpha=(0.6, 1.4))) ]) sometimes3 = lambda aug: iaa.Sometimes(0.93, aug) seq3 = iaa.SomeOf( (1, 2), [ #sometimes3(iaa.Affine(scale=1.5)), # cuts out part of the objects, resulting in negative coordinates.. sometimes3(iaa.ElasticTransformation(alpha=(20, 30.0), sigma=5.0)), sometimes3(iaa.Rot90((1, 3), keep_size=False) ), # On 90,270 transformation, the width and height change. sometimes3(iaa.Rotate((-30, 30))), sometimes3(iaa.WithPolarWarping(iaa.AveragePooling((2, 7)))), sometimes3(iaa.ShearY((30, 50))), sometimes3(iaa.ShearX((30, 70))), ]) img_path = "C:\\Users\\gishy\\Dropbox\\My PC (LAPTOP-SQRN8N46)\\Desktop\\sample_images" txt_path = "C:\\Users\\gishy\\Dropbox\\My PC (LAPTOP-SQRN8N46)\\Desktop\\sample_annotations" #img_path="C:\\Users\\gishy\\Dropbox\\My PC (LAPTOP-SQRN8N46)\\Desktop\\final-dataset\\main\\Not Augmented\\train_images" #txt_path="C:\\Users\\gishy\\Dropbox\\My PC (LAPTOP-SQRN8N46)\\Desktop\\final-dataset\\main\\Not Augmented\\train_annotations_yolo" if __name__ == "__main__": conversion(txt_path, img_path, seq3)
contrast = iaa.GammaContrast(gamma=2.0) contrast_image = contrast.augment_image(img) aug = iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6)) sigmoid_image = aug.augment_image(img) aug = iaa.LogContrast(gain=(0.6, 1.4)) log_image = aug.augment_image(img) aug = iaa.MultiplySaturation((0.5, 1.5)) channel = aug.augment_image(img) aug = iaa.Rotate((-5, 5)) rotate1 = aug.augment_image(img) aug = iaa.ShearX((-20, 20)) shear = aug.augment_image(img) aug = iaa.PerspectiveTransform(scale=(0.01, 0.15)) perspec = aug.augment_image(img) cv2.imshow("3", perspec) cv2.waitKey(0) aaa rotate = iaa.Affine(rotate=(-50, 30)) polar = rotate.augment_image(img) image_name = files.split("_")[0] label = "_" + files.split("_")[1] cv2.imwrite( "C:/Users/Kenil/Downloads/Competitive/Dataset/Combined Dataset/final_training_data/2/" + image_name + str(0) + label, noise_image)