def augment(): with open(CONFIG, "r") as file: config = json.loads(file.read()) if config[ImageAugmentation.AUGMENT_DATA]: matrix = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) return iaa.Sometimes(ImageAugmentation.AUG_PERCENTAGE, [ iaa.GaussianBlur(sigma=2.0), iaa.Sequential([iaa.Affine(rotate=45), iaa.Sharpen(alpha=1.0)]), iaa.WithColorspace(to_colorspace="HSV", from_colorspace="RGB", children=iaa.WithChannels( 0, iaa.Add((10, 50)))), iaa.AdditiveGaussianNoise(scale=0.2 * 255), iaa.Add(50, per_channel=True), iaa.Sharpen(alpha=0.5), iaa.WithChannels(0, iaa.Add((10, 100))), iaa.WithChannels(0, iaa.Affine(rotate=(0, 45))), iaa.Noop(), iaa.Superpixels(p_replace=0.5, n_segments=64), iaa.Superpixels(p_replace=(0.1, 1.0), n_segments=(16, 128)), iaa.ChangeColorspace(from_colorspace="RGB", to_colorspace="HSV"), iaa.WithChannels(0, iaa.Add((50, 100))), iaa.ChangeColorspace(from_colorspace="HSV", to_colorspace="RGB"), iaa.Grayscale(alpha=(0.0, 1.0)), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.AverageBlur(k=(2, 11)), iaa.AverageBlur(k=((5, 11), (1, 3))), iaa.MedianBlur(k=(3, 11)), iaa.Convolve(matrix=matrix), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5)), iaa.EdgeDetect(alpha=(0.0, 1.0)), iaa.DirectedEdgeDetect(alpha=(0.0, 1.0), direction=(0.0, 1.0)), iaa.Add((-40, 40)), iaa.Add((-40, 40), per_channel=0.5), iaa.AddElementwise((-40, 40)), iaa.AddElementwise((-40, 40), per_channel=0.5), iaa.AdditiveGaussianNoise(scale=(0, 0.05 * 255)), iaa.AdditiveGaussianNoise(scale=0.05 * 255), iaa.AdditiveGaussianNoise(scale=0.05 * 255, per_channel=0.5), iaa.Multiply((0.5, 1.5), per_channel=0.5), iaa.Dropout(p=(0, 0.2)), iaa.Dropout(p=(0, 0.2), per_channel=0.5), iaa.CoarseDropout(0.02, size_percent=0.5), iaa.CoarseDropout((0.0, 0.05), size_percent=(0.02, 0.25)), iaa.CoarseDropout(0.02, size_percent=0.15, per_channel=0.5), iaa.Invert(0.25, per_channel=0.5), iaa.Invert(0.5), iaa.ContrastNormalization((0.5, 1.5)), iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5), iaa.ElasticTransformation(alpha=(0, 5.0), sigma=0.25) ]) else: return None
def __init__(self, ratio=0.5): self.ratio = ratio self.noise_list = [ iaa.AddElementwise((-40, 40)), iaa.AddElementwise((-40, 40), per_channel=0.5), iaa.AdditiveGaussianNoise(scale=(0, 0.05 * 255)), iaa.Dropout(p=(0, 0.2)), iaa.Dropout(p=(0, 0.2), per_channel=0.5), iaa.CoarseDropout(0.02, size_percent=0.5), iaa.CoarseDropout((0.0, 0.05), size_percent=(0.02, 0.25)), iaa.CoarseDropout(0.02, size_percent=0.15, per_channel=0.5) ]
def chapter_augmenters_addelementwise(): aug = iaa.AddElementwise((-40, 40)) run_and_save_augseq("addelementwise.jpg", aug, [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1, quality=90) aug = iaa.AddElementwise((-40, 40), per_channel=0.5) run_and_save_augseq("addelementwise_per_channel.jpg", aug, [ia.quokka(size=(512, 512)) for _ in range(1)], cols=1, rows=1, quality=90)
def f13(): ''' Add random values between -20 and 20 to images, with each value being sampled per pixel ''' aug = iaa.AddElementwise((-20, 20)) desc = 'Noise' return aug, desc
def augmentation_sequence(params): if params is None: params = dicto.load_("params.yml") n_augmenters = params.data_augmentation.n_augmenters return iaa.SomeOf(n_augmenters, [ iaa.Grayscale(alpha=(0.0, 1.0)), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.AverageBlur(k=(2, 9)), iaa.MedianBlur(k=(3, 9)), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5)), iaa.Add((-40, 40), per_channel=0.5), iaa.AddElementwise((-40, 40), per_channel=0.5), iaa.AdditiveGaussianNoise(scale=0.05 * 255, per_channel=0.5), iaa.Multiply((0.5, 1.5), per_channel=0.5), iaa.MultiplyElementwise((0.5, 1.5), per_channel=0.5), iaa.Dropout(p=(0, 0.2), per_channel=0.5), iaa.CoarseDropout(0.05, size_percent=0.1), iaa.Invert(1.0, per_channel=0.5), iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5), iaa.ElasticTransformation(alpha=(0, 5.0), sigma=0.25), iaa.PiecewiseAffine(scale=(0.01, 0.05)), ])
def f14(): ''' Add random values between -20 and 20 to images, with each value being sampled per pixel ''' aug = iaa.AddElementwise((-20, 20), per_channel=0.5) desc = 'ColorNoise' return aug, desc
def __init__(self, blur=True, flip=False, rotate=10, shear=10, **kwargs): from imgaug import augmenters as iaa sequence = [] sequence += [ iaa.Scale((INPUT_SIZE, INPUT_SIZE)), iaa.ContrastNormalization((0.75, 1.25)), iaa.AddElementwise((-10, 10), per_channel=0.5), iaa.AddToHueAndSaturation(value=(-20, 20), per_channel=True), iaa.Multiply((0.75, 1.25)), ] sequence += [ iaa.PiecewiseAffine(scale=(0.0005, 0.005)), iaa.Affine(rotate=(-rotate, rotate), shear=(-shear, shear), mode='symmetric'), iaa.Grayscale(alpha=(0.0, 0.5)), ] if flip: sequence += [ iaa.Fliplr(0.5), ] if blur: sequence += [ iaa.Sometimes(0.01, iaa.GaussianBlur(sigma=(0, 1.0))), ] self.aug = iaa.Sequential(sequence)
def data_aug(images): seq = iaa.Sometimes( 0.5, iaa.Identity(), iaa.Sometimes( 0.5, iaa.Sequential([ iaa.Sometimes( 0.5, iaa.OneOf([ iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)), iaa.AdditiveLaplaceNoise(scale=(0, 0.1 * 255)), iaa.ReplaceElementwise(0.03, [0, 255]), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.BilateralBlur(d=(3, 10), sigma_color=(10, 250), sigma_space=(10, 250)) ])), iaa.OneOf([ iaa.Add((-40, 40)), iaa.AddElementwise((-20, 20)), iaa.pillike.EnhanceBrightness() ]), iaa.OneOf([ iaa.GammaContrast((0.2, 2.0)), iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.4, 0.6)), iaa.LogContrast(gain=(0.6, 1.4)), iaa.AllChannelsCLAHE(), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), ]) ]))) images = seq(images=images) return images
def noise(): return iaa.OneOf([ iaa.Add((-10, 10), per_channel=0.5), iaa.AddElementwise((-10, 10), per_channel=0.5), iaa.AdditiveGaussianNoise(scale=0.1 * 255, per_channel=0.5), iaa.AdditiveLaplaceNoise(scale=0.1 * 255, per_channel=0.5), iaa.AdditivePoissonNoise(lam=2, per_channel=0.5), iaa.Multiply((0.5, 1.5), per_channel=0.5) ])
def add_element_noise(origImage, value): ''' Add values to the pixels of images with possibly different values for neighbouring pixels. origImage : Array of image pixels as numpy array value : Is a postive integer than is used as the upper bound to a random value generator for noise Returns: Augmented image array with added pixel noise ''' return (iaa.AddElementwise((-value, value)), value)
def augmentor(self, images, targets): '''Augments each batch of data with random transformations''' sometimes = lambda aug: iaa.Sometimes(0.5, aug) seq = iaa.Sequential([ iaa.Fliplr(0.5, name="Fliplr"), iaa.Flipud(0.5, name="Flipud"), sometimes( iaa.SomeOf((0, 2), [ iaa.Affine(translate_percent={ "x": (-0.1, 0.1), "y": (-0.1, 0.1) }, rotate=(-25, 25), name="Affine"), iaa.ElasticTransformation(alpha=(0.01, 0.1), sigma=0.15, name="ElasticTransformation"), iaa.PiecewiseAffine(scale=(0.001, 0.03), name="PiecewiseAffine"), iaa.PerspectiveTransform(scale=(0.01, 0.05), name="PerspectiveTransform"), ], random_order=True)), sometimes( iaa.OneOf([ iaa.GaussianBlur(sigma=(0, 0.2)), iaa.AverageBlur(k=3), iaa.MedianBlur(k=3), ])), sometimes( iaa.OneOf([ iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.01 * 255)), iaa.AddElementwise((-5, 5)), ])), sometimes( iaa.OneOf([ iaa.GammaContrast(gamma=(0.75, 1.50)), iaa.HistogramEqualization(), iaa.Multiply((0.80, 1.15)), iaa.Add((-20, 15)), iaa.Sharpen(alpha=(0, 0.5), lightness=(0.7, 1.5)), iaa.Emboss(alpha=(0, 0.5), strength=(0.7, 1.5)), ])), ], random_order=True) seq_det = seq.to_deterministic() images = seq_det.augment_images(images) targets = seq_det.augment_segmentation_maps([ ia.SegmentationMapOnImage(t.astype(bool), shape=t.shape) for t in targets ]) targets = np.array([t.get_arr_int() for t in targets]) return images, targets
def __init__(self): self._add_augmentation_list = [ iaa.Add((-30, 30), per_channel=True), iaa.Add((-30, 30), per_channel=False), iaa.AddElementwise((-30, 30), per_channel=False), iaa.AddElementwise((-30, 30), per_channel=True), iaa.Invert(p=0.2, per_channel=True), iaa.Invert(p=0.2, per_channel=False), iaa.AddToHueAndSaturation((0, 80), True), iaa.Multiply((0.8, 1.2), per_channel=True), iaa.Multiply((0.8, 1.2), per_channel=False), iaa.MultiplyElementwise((0.8, 1.2), per_channel=True), iaa.MultiplyElementwise((0.8, 1.2), per_channel=False) ] self._blur_augmentation_list = [ iaa.GaussianBlur((2, 3)), iaa.AverageBlur((2, 3)), iaa.MedianBlur((3, 5)), iaa.BilateralBlur((2, 3)) ] self._noise_augmentation_list = [ iaa.AdditiveGaussianNoise(0, (5, 20), per_channel=True), iaa.AdditiveGaussianNoise(0, (5, 20), per_channel=False), iaa.Dropout((0.05, 0.15), per_channel=False), iaa.Dropout((0.05, 0.15), per_channel=True), iaa.CoarseDropout((0.05, 0.15), size_percent=(0.65, 0.85)) ] self._other_augmentation_list = [ iaa.Sharpen((0.9, 0.11), (0.8, 1.2)), iaa.Emboss((0.9, 0.11), (0.3, 1.6)), iaa.EdgeDetect((0, 0.4)), iaa.Grayscale((0, 1)) ] self.noise_list = self._add_augmentation_list +\ self._blur_augmentation_list +\ self._noise_augmentation_list +\ self._other_augmentation_list
def test_augmentations_with_seed_match_for_images_and_keypoints(self): augseq = iaa.AddElementwise((0, 255)) image = np.zeros((10, 10, 1), dtype=np.uint8) # keypoints here will not be changed by augseq, but they will induce # deterministic mode to start in augment_batches() as each batch # contains images AND keypoints kps = ia.KeypointsOnImage([ia.Keypoint(x=2, y=0)], shape=(10, 10, 1)) batch = ia.Batch(images=np.uint8([image, image]), keypoints=[kps, kps]) batches = [batch.deepcopy() for _ in sm.xrange(60)] # seed=1 with multicore.Pool(augseq, processes=2, maxtasksperchild=30, seed=1) as pool: batches_aug1 = pool.map_batches(batches, chunksize=2) # seed=1 with multicore.Pool(augseq, processes=2, seed=1) as pool: batches_aug2 = pool.map_batches(batches, chunksize=1) # seed=2 with multicore.Pool(augseq, processes=2, seed=2) as pool: batches_aug3 = pool.map_batches(batches, chunksize=1) assert len(batches_aug1) == 60 assert len(batches_aug2) == 60 assert len(batches_aug3) == 60 for batches_aug in [batches_aug1, batches_aug2, batches_aug3]: for batch in batches_aug: for keypoints_aug in batch.keypoints_aug: assert keypoints_aug.keypoints[0].x == 2 assert keypoints_aug.keypoints[0].y == 0 for b1, b2, b3 in zip(batches_aug1, batches_aug2, batches_aug3): # images were augmented assert not np.array_equal(b1.images_unaug, b1.images_aug) assert not np.array_equal(b2.images_unaug, b2.images_aug) assert not np.array_equal(b3.images_unaug, b3.images_aug) # original images still the same assert np.array_equal(b1.images_unaug, batch.images_unaug) assert np.array_equal(b2.images_unaug, batch.images_unaug) assert np.array_equal(b3.images_unaug, batch.images_unaug) # augmentations for same seed are the same assert np.array_equal(b1.images_aug, b2.images_aug) # augmentations for different seeds are different assert not np.array_equal(b1.images_aug, b3.images_aug) # make sure that batches for the two pools with same seed did not # repeat within results (only between the results of the two pools) for batches_aug in [batches_aug1, batches_aug2, batches_aug3]: self._assert_each_augmentation_not_more_than_once(batches_aug)
def __init__(self): from imgaug import augmenters as iaa self.aug = iaa.Sequential([ iaa.Scale((INPUT_SIZE, INPUT_SIZE)), iaa.ContrastNormalization((0.75, 1.25)), iaa.AddElementwise((-20, 20), per_channel=0.5), iaa.AddToHueAndSaturation(value=(-5, 5), per_channel=True), iaa.Multiply((0.75, 1.25)), # iaa.Dropout(p=(0.0, 0.1)), iaa.PiecewiseAffine(scale=(0.0001, 0.0005)), iaa.Affine(rotate=(-1, 1), shear=(-1, 1), mode='symmetric'), iaa.Grayscale(alpha=(0.0, 0.25)), ])
def create_image_only_augmenter(): aug = iaa.SomeOf((0, None), [ iaa.Noop(), iaa.GaussianBlur(sigma=(0.0, 1.0)), iaa.AdditiveGaussianNoise(scale=(0, 0.02 * 255)), iaa.AdditiveGaussianNoise(scale=0.02 * 255, per_channel=0.5), iaa.MultiplyElementwise((0.75, 1.25)), iaa.Dropout(p=(0, 0.1)), iaa.Add((-20, 20)), iaa.AddElementwise((-20, 20)), iaa.ContrastNormalization((0.75, 1.25)) ]) return aug
def get_augmenter(): seq = iaa.Sequential([ iaa.SomeOf((1, 4), [ iaa.Fliplr(0.5), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.MotionBlur(angle=(0, 360)), iaa.Add((-20, 20)), iaa.AddElementwise((-10, 10)), iaa.AdditiveGaussianNoise(scale=0.01*255), iaa.Multiply((0.8, 1.2)), ]) ]) return seq
def test_augmentations_without_seed_differ(self): augseq = iaa.AddElementwise((0, 255)) image = np.zeros((10, 10, 1), dtype=np.uint8) batch = ia.Batch(images=np.uint8([image, image])) batches = [batch.deepcopy() for _ in sm.xrange(20)] with multicore.Pool(augseq, processes=2, maxtasksperchild=5) as pool: batches_aug = pool.map_batches(batches, chunksize=2) with multicore.Pool(augseq, processes=2) as pool: batches_aug.extend(pool.map_batches(batches, chunksize=1)) assert len(batches_aug) == 2 * 20 self._assert_each_augmentation_not_more_than_once(batches_aug)
def DA_AddElementwise(inputimg): assert inputimg.ndim in [2, 3], "input invalid! Please check input" values = np.arange(-50,51,10) p_channels = np.arange(0.01,1.01,0.2) ret = [] for i in np.arange(len(p_channels)): for j in np.arange(len(values)): Name = "AddElementwise_" + str(j) + "_p_channels_" + str(p_channels[i]) VALUE = str(values[i]) + "_" + str(p_channels[j]) aug_img = iaa.AddElementwise(value=(-50, 50), per_channel=p_channels[i]).augment_image(inputimg) ret.append((Name, VALUE, aug_img)) assert len(ret) == 66, "DA_AddElementwise output size not match!" return ret
def get_transforms(): sometimes = lambda aug: iaa.Sometimes(0.2, aug) seq1 = iaa.Sequential([ iaa.Fliplr(0.5), iaa.Flipud(0.5), sometimes( iaa.Affine( scale={ "x": (0.8, 1.2), "y": (0.8, 1.2) }, translate_percent={ "x": (-0.2, 0.2), "y": (-0.2, 0.2) }, rotate=(-30, 30), shear=(-10, 10), mode='constant', cval=(0, 255), )), sometimes( iaa.PiecewiseAffine( scale=(0.01, 0.05), nb_cols=8, nb_rows=8, mode='constant', cval=(0, 255), )), ], ) seq2 = iaa.Sequential([ iaa.SomeOf((0, 1), [ sometimes(iaa.MultiplyElementwise((0.8, 1.2))), sometimes(iaa.AddElementwise((-20, 20))), sometimes(iaa.ContrastNormalization((0.8, 1.2))), ]), iaa.SomeOf((0, 1), [ iaa.OneOf([ iaa.GaussianBlur((0, 2.0)), iaa.AverageBlur(k=2), iaa.MedianBlur(k=3), ]), iaa.AdditiveGaussianNoise(0, 10), iaa.SaltAndPepper(0.01), iaa.ReplaceElementwise(0.05, (0, 255)) ]), ], ) return seq1, seq2
def aug_lv3(images): seq = iaa.Sequential( [ # Blur iaa.OneOf([ iaa.GaussianBlur(sigma=(0, 0.5)), iaa.AverageBlur(k=(2, 7)), iaa.MedianBlur((3, 11)) ]), iaa.OneOf([ iaa.AdditiveGaussianNoise( loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5), iaa.Dropout((0.01, 0.1), per_channel=0.5), iaa.CoarseDropout( (0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2), ]), iaa.OneOf([ iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.5, 1.5)), # iaa.EdgeDetect(alpha=(0.0 , 0.2)) ]), iaa.SomeOf(2, [ iaa.Add((-40, 40), per_channel=0.5), iaa.AddElementwise((-40, 40), per_channel=0.5), iaa.Multiply((0.5, 1.5)), iaa.Multiply((0.5, 1.5), per_channel=0.5), ], random_order=True), iaa.SomeOf((0, None), [ iaa.OneOf([ iaa.ContrastNormalization((0.5, 1.5)), iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5), ]), ]), iaa.Affine(scale=(0.8, 1.2), translate_percent={ "x": (-0.1, 0.1), "y": (-0.1, 0.1) }, rotate=(-30, 30)), iaa.OneOf([ iaa.Affine(shear=(0.01, 0.05)), iaa.PiecewiseAffine((0.01, 0.05)) ]), ], random_order=True) augimgs = seq.augment_images(images) return augimgs
def cpu_augment(self, imgs, boxes): # for bx in boxes: # self.assert_bboxes(bx) ia_bb = [] for n in range(len(imgs)): c_boxes = [] for i in boxes[n]: try: c_boxes.append( ia.BoundingBox(x1=i[0], y1=i[1], x2=i[2], y2=i[3])) except AssertionError: print('Assertion Error: ', i) ia_bb.append(ia.BoundingBoxesOnImage(c_boxes, shape=imgs[n].shape)) seq = iaa.Sequential([ iaa.Sometimes(0.5, iaa.AddElementwise((-20, 20), per_channel=1)), iaa.Sometimes(0.5, iaa.AdditiveGaussianNoise(scale=(0, 0.10 * 255))), iaa.Sometimes(0.5, iaa.Multiply((0.75, 1.25), per_channel=1)), iaa.Sometimes(0.5, iaa.MultiplyElementwise((0.75, 1.25))), iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0.0, 1.0))), iaa.Fliplr(0.5), iaa.Sometimes( 0.95, iaa.SomeOf(1, [ iaa.CoarseDropout(p=(0.10, 0.25), size_percent=(0.25, 0.5)), iaa.CoarseDropout(p=(0.0, 0.15), size_percent=(0.1, 0.25)), iaa.Dropout(p=(0, 0.25)), iaa.CoarseSaltAndPepper(p=(0, 0.25), size_percent=(0.1, 0.2)) ])), iaa.Affine(scale=iap.Choice( [iap.Uniform(0.4, 1), iap.Uniform(1, 3)]), rotate=(-180, 180)) ]) seq_det = seq.to_deterministic() image_b_aug = seq_det.augment_images(imgs) bbs_b_aug = seq_det.augment_bounding_boxes(ia_bb) bbs_b_aug = [ b.remove_out_of_image().cut_out_of_image() for b in bbs_b_aug ] return image_b_aug, [ np.array([self.bbox_r(j) for j in i.bounding_boxes]) for i in bbs_b_aug ]
def get_augmenter(self): seq = iaa.Sequential([ iaa.SomeOf((2, 6), [ iaa.Flipud(0.5), iaa.Rot90(k=(0, 3)), iaa.GaussianBlur(sigma=(0.0, 3.0)), iaa.MotionBlur(angle=(0, 360), k=(3, 8)), iaa.Add((-50, 5)), iaa.AddElementwise((-20, 2)), iaa.AdditiveGaussianNoise(scale=0.05 * 255), iaa.Multiply((0.3, 1.05)), iaa.SaltAndPepper(p=(0.1, 0.3)), iaa.JpegCompression(compression=(20, 90)), iaa.Affine(shear=(-15, 15)), iaa.Affine(rotate=(-10, 10)), ]) ]) return seq
def augment_image(image_file): im = Image.open(image_file) im_array = img_to_array(im) #function returns an array of images (including the first one) output_images = [] output_images.append(im_array) #darken image #aug_dark = iaa.Add(-30) #aug_image = aug_dark.augment_images([im_array])[0] #output_images.append(aug_image) #lighten image #aug_light = iaa.Add(30) #aug_image = aug_light.augment_images([im_array])[0] # output_images.append(aug_image) augmentations = [ iaa.Fliplr(1), iaa.PerspectiveTransform(0.03, True), iaa.PerspectiveTransform(0.04, True), iaa.PerspectiveTransform(0.045, True), iaa.Add(30, per_channel=True), iaa.Add(-20, per_channel=True), iaa.PiecewiseAffine(scale=0.01), iaa.AdditiveGaussianNoise(scale=10), iaa.MedianBlur(k=(3, 3)), iaa.PerspectiveTransform(0.02, True), iaa.PerspectiveTransform(0.021, True), iaa.PerspectiveTransform(0.022, True), iaa.AddElementwise(20), iaa.Affine(rotate=3), iaa.Affine(rotate=-5), iaa.Affine(rotate=4) ] #do this 3 times base = 4 for i in range(7): #for i in range(1): #get between 2 and 5 augs aug = iaa.SomeOf(i + base, augmentations) #produce more images where there are more augs for j in range(4): this_image = aug.augment_images([im_array])[0] output_images.append(this_image) return(output_images)
def test_augmentations_with_seed_match(self): nb_batches = 60 augseq = iaa.AddElementwise((0, 255)) image = np.zeros((10, 10, 1), dtype=np.uint8) batch = ia.Batch(images=np.uint8([image, image])) batches = [batch.deepcopy() for _ in sm.xrange(nb_batches)] # seed=1 with multicore.Pool(augseq, processes=2, maxtasksperchild=30, seed=1) as pool: batches_aug1 = pool.map_batches(batches, chunksize=2) # seed=1 with multicore.Pool(augseq, processes=2, seed=1) as pool: batches_aug2 = pool.map_batches(batches, chunksize=1) # seed=2 with multicore.Pool(augseq, processes=2, seed=2) as pool: batches_aug3 = pool.map_batches(batches, chunksize=1) assert len(batches_aug1) == nb_batches assert len(batches_aug2) == nb_batches assert len(batches_aug3) == nb_batches for b1, b2, b3 in zip(batches_aug1, batches_aug2, batches_aug3): # images were augmented assert not np.array_equal(b1.images_unaug, b1.images_aug) assert not np.array_equal(b2.images_unaug, b2.images_aug) assert not np.array_equal(b3.images_unaug, b3.images_aug) # original images still the same assert np.array_equal(b1.images_unaug, batch.images_unaug) assert np.array_equal(b2.images_unaug, batch.images_unaug) assert np.array_equal(b3.images_unaug, batch.images_unaug) # augmentations for same seed are the same assert np.array_equal(b1.images_aug, b2.images_aug) # augmentations for different seeds are different assert not np.array_equal(b1.images_aug, b3.images_aug) # make sure that batches for the two pools with same seed did not # repeat within results (only between the results of the two pools) for batches_aug in [batches_aug1, batches_aug2, batches_aug3]: self._assert_each_augmentation_not_more_than_once(batches_aug)
def chapter_parameters_introduction(): ia.seed(1) from imgaug import augmenters as iaa from imgaug import parameters as iap seq = iaa.Sequential([ iaa.GaussianBlur(sigma=iap.Uniform(0.0, 1.0)), iaa.ContrastNormalization( iap.Choice([1.0, 1.5, 3.0], p=[0.5, 0.3, 0.2])), iaa.Affine(rotate=iap.Normal(0.0, 30), translate_px=iap.RandomSign(iap.Poisson(3))), iaa.AddElementwise(iap.Discretize( (iap.Beta(0.5, 0.5) * 2 - 1.0) * 64)), iaa.Multiply(iap.Positive(iap.Normal(0.0, 0.1)) + 1.0) ]) images = np.array([ia.quokka_square(size=(128, 128)) for i in range(16)]) images_aug = [seq.augment_image(images[i]) for i in range(len(images))] save("parameters", "introduction.jpg", grid(images_aug, cols=4, rows=4))
def from_config(cls, config: AugmentationConfig) -> "ImgaugAugmenter": """Create an augmenter from a set of configuration parameters. Args: config: An `AugmentationConfig` instance with the desired parameters. Returns: An instance of this class with the specified augmentation configuration. """ aug_stack = [] if config.rotate: aug_stack.append( iaa.Affine(rotate=(config.rotation_min_angle, config.rotation_max_angle))) if config.translate: aug_stack.append( iaa.Affine( translate_px={ "x": (config.translate_min, config.translate_max), "y": (config.translate_min, config.translate_max), })) if config.scale: aug_stack.append( iaa.Affine(scale=(config.scale_min, config.scale_max))) if config.uniform_noise: aug_stack.append( iaa.AddElementwise(value=(config.uniform_noise_min_val, config.uniform_noise_max_val))) if config.gaussian_noise: aug_stack.append( iaa.AdditiveGaussianNoise(loc=config.gaussian_noise_mean, scale=config.gaussian_noise_stddev)) if config.contrast: aug_stack.append( iaa.GammaContrast(gamma=(config.contrast_min_gamma, config.contrast_max_gamma))) if config.brightness: aug_stack.append( iaa.Add(value=(config.brightness_min_val, config.brightness_max_val))) return cls(augmenter=iaa.Sequential(aug_stack))
def image_augment(input_dir, augmented_dir, coefficient=10): # 删除原来的 for file_name in os.listdir(augmented_dir): os.remove(augmented_dir + '/' + file_name) seq = iaa.Sequential( [ iaa.GaussianBlur(sigma=(0.2, 0.4)), # 高斯模糊 # iaa.Add((-50,50), per_channel=0.5),#为图像中的所有像素添加值 iaa.Sometimes(0.3, iaa.AddElementwise((-40, 40))), # 相邻像素加法增强器 iaa.Sometimes( 0.3, iaa.AdditiveGaussianNoise(scale=0.05 * 255, per_channel=0.5)), # 高斯噪声 iaa.Sometimes(0.3, iaa.PiecewiseAffine(scale=0.03)), # 扭曲增强器 iaa.Sometimes( 0.3, iaa.ElasticTransformation(alpha=(0, 5.0), sigma=0.25)), # 像素位移增强器 # iaa.Sometimes(0.2, iaa.Superpixels(p_replace=0.05, n_segments=8)) #部分地将图像变换为其超像素表示 ], random_order=True) # do all of the above in random order i = 0 for file_name in os.listdir(input_dir): image = cv2.imread(input_dir + file_name) if not (image.shape == (64, 64)): image = cv2.resize(image, (64, 64)) images_aug = [seq.augment_image(image) for _ in range(coefficient)] # 应用data augmentation # ia.imshow(ia.draw_grid(images_aug, cols=4, rows=2)) # 显示图片操作效果 for img in images_aug: output_file_name = file_name.split("_")[0] + "_" + str(i) + ".jpg" cv2.imwrite(augmented_dir + output_file_name, img) i += 1
def test_augmentations_without_seed_differ_for_images_and_keypoints(self): augseq = iaa.AddElementwise((0, 255)) image = np.zeros((10, 10, 1), dtype=np.uint8) # keypoints here will not be changed by augseq, but they will induce deterministic mode to start in # augment_batches() as each batch contains images AND keypoints kps = ia.KeypointsOnImage([ia.Keypoint(x=2, y=0)], shape=(10, 10, 1)) batch = ia.Batch(images=np.uint8([image, image]), keypoints=[kps, kps]) batches = [batch.deepcopy() for _ in sm.xrange(20)] with multicore.Pool(augseq, processes=2, maxtasksperchild=5) as pool: batches_aug = pool.map_batches(batches, chunksize=2) with multicore.Pool(augseq, processes=2) as pool: batches_aug.extend(pool.map_batches(batches, chunksize=1)) assert len(batches_aug) == 2 * 20 for batch in batches_aug: for keypoints_aug in batch.keypoints_aug: assert keypoints_aug.keypoints[0].x == 2 assert keypoints_aug.keypoints[0].y == 0 self._assert_each_augmentation_not_more_than_once(batches_aug)
def randomIntensityAugmentation(image): intensity_seq = iaa.Sequential( [ # iaa.Invert(0.3), iaa.Sometimes(0.3, iaa.ContrastNormalization((0.5, 1.5))), iaa.OneOf([ iaa.Noop(), iaa.Sequential([ iaa.OneOf([ iaa.Add((-10, 10)), iaa.AddElementwise((-10, 10)), iaa.Multiply((0.95, 1.05)), iaa.MultiplyElementwise((0.95, 1.05)), ]), ]), iaa.OneOf([ iaa.GaussianBlur(sigma=(0.0, 1.0)), iaa.AverageBlur(k=(2, 5)), iaa.MedianBlur(k=(3, 5)) ]) ]) ], random_order=False) return intensity_seq.augment_images(image)
def stochastic(): return iaa.Sequential([ iaa.GaussianBlur( sigma=iap.Uniform(0.0, 1.0) ), iaa.ContrastNormalization( iap.Choice( [1.0, 1.5, 3.0], p=[0.5, 0.3, 0.2] ) ), iaa.Affine( rotate=iap.Normal(0.0, 30), translate_px=iap.RandomSign(iap.Poisson(3)) ), iaa.AddElementwise( iap.Discretize( (iap.Beta(0.5, 0.5) * 2 - 1.0) * 64 ) ), iaa.Multiply( iap.Positive(iap.Normal(0.0, 0.1)) + 1.0 ) ])