Python源码示例:imgaug.augmenters.Fliplr()
示例1
def __init__(self, dataset_path,scale,k_fold_test=1, mode='train'):
super().__init__()
self.mode = mode
self.img_path=dataset_path+'/img'
self.mask_path=dataset_path+'/mask'
self.image_lists,self.label_lists=self.read_list(self.img_path,k_fold_test=k_fold_test)
self.flip =iaa.SomeOf((2,4),[
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
iaa.Affine(rotate=(-30, 30)),
iaa.AdditiveGaussianNoise(scale=(0.0,0.08*255))], random_order=True)
# resize
self.resize_label = transforms.Resize(scale, Image.NEAREST)
self.resize_img = transforms.Resize(scale, Image.BILINEAR)
# normalization
self.to_tensor = transforms.ToTensor()
示例2
def main():
img = data.astronaut()
img = ia.imresize_single_image(img, (64, 64))
aug = iaa.Fliplr(0.5)
unseeded1 = aug.draw_grid(img, cols=8, rows=1)
unseeded2 = aug.draw_grid(img, cols=8, rows=1)
iarandom.seed(1000)
seeded1 = aug.draw_grid(img, cols=8, rows=1)
seeded2 = aug.draw_grid(img, cols=8, rows=1)
iarandom.seed(1000)
reseeded1 = aug.draw_grid(img, cols=8, rows=1)
reseeded2 = aug.draw_grid(img, cols=8, rows=1)
iarandom.seed(1001)
reseeded3 = aug.draw_grid(img, cols=8, rows=1)
reseeded4 = aug.draw_grid(img, cols=8, rows=1)
all_rows = np.vstack([unseeded1, unseeded2, seeded1, seeded2, reseeded1, reseeded2, reseeded3, reseeded4])
ia.imshow(all_rows)
示例3
def __init__(self, augmentation_rate):
self.augs = iaa.Sometimes(
augmentation_rate,
iaa.SomeOf(
(4, 7),
[
iaa.Affine(rotate=(-10, 10)),
iaa.Fliplr(0.2),
iaa.AverageBlur(k=(2, 10)),
iaa.Add((-10, 10), per_channel=0.5),
iaa.Multiply((0.75, 1.25), per_channel=0.5),
iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),
iaa.Crop(px=(0, 20))
],
random_order=True
)
)
示例4
def img_aug(img, mask):
mask = np.where(mask > 0, 0, 255).astype(np.uint8)
flipper = iaa.Fliplr(0.5).to_deterministic()
mask = flipper.augment_image(mask)
img = flipper.augment_image(img)
vflipper = iaa.Flipud(0.5).to_deterministic()
img = vflipper.augment_image(img)
mask = vflipper.augment_image(mask)
if random.random() < 0.5:
rot_time = random.choice([1, 2, 3])
for i in range(rot_time):
img = np.rot90(img)
mask = np.rot90(mask)
if random.random() < 0.5:
translater = iaa.Affine(translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},
shear=(-8, 8),
cval=(255)
).to_deterministic()
img = translater.augment_image(img)
mask = translater.augment_image(mask)
# if random.random() < 0.5:
# img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
mask = np.where(mask > 0, 0, 255).astype(np.uint8)
return img, mask
示例5
def create_augmenter(stage: str = "train"):
if stage == "train":
return iaa.Sequential([
iaa.Fliplr(0.5),
iaa.CropAndPad(px=(0, 112), sample_independently=False),
iaa.Affine(translate_percent={"x": (-0.4, 0.4), "y": (-0.4, 0.4)}),
iaa.SomeOf((0, 3), [
iaa.AddToHueAndSaturation((-10, 10)),
iaa.Affine(scale={"x": (0.9, 1.1), "y": (0.9, 1.1)}),
iaa.GaussianBlur(sigma=(0, 1.0)),
iaa.AdditiveGaussianNoise(scale=0.05 * 255)
])
])
elif stage == "val":
return iaa.Sequential([
iaa.CropAndPad(px=(0, 112), sample_independently=False),
iaa.Affine(translate_percent={"x": (-0.4, 0.4), "y": (-0.4, 0.4)}),
])
elif stage == "test":
return iaa.Sequential([])
示例6
def augment_flip(image, bbox):
aug = iaa.Sequential([iaa.Fliplr(1.0)])
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=bbox[0], y1=bbox[1], x2=bbox[2], y2=bbox[3])], shape=image.shape)
aug = aug.to_deterministic()
image_aug = aug.augment_image(image)
image_aug = image_aug.copy()
bbs_aug = aug.augment_bounding_boxes([bbs])[0]
b = bbs_aug.bounding_boxes
bbs_aug = [b[0].x1, b[0].y1, b[0].x2, b[0].y2]
bbs_aug = np.asarray(bbs_aug)
bbs_aug[0] = bbs_aug[0] if bbs_aug[0] > 0 else 0
bbs_aug[1] = bbs_aug[1] if bbs_aug[1] > 0 else 0
bbs_aug[2] = bbs_aug[2] if bbs_aug[2] < size else size
bbs_aug[3] = bbs_aug[3] if bbs_aug[3] < size else size
return image_aug, bbs_aug
示例7
def flip(image, bbox):
aug = iaa.Sequential([iaa.Fliplr(1.0)])
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=bbox[0], y1=bbox[1], x2=bbox[2], y2=bbox[3])], shape=image.shape)
aug = aug.to_deterministic()
image_aug = aug.augment_image(image)
image_aug = image_aug.copy()
bbs_aug = aug.augment_bounding_boxes([bbs])[0]
b = bbs_aug.bounding_boxes
bbs_aug = [b[0].x1, b[0].y1, b[0].x2, b[0].y2]
bbs_aug = np.asarray(bbs_aug)
bbs_aug[0] = bbs_aug[0] if bbs_aug[0] > 0 else 0
bbs_aug[1] = bbs_aug[1] if bbs_aug[1] > 0 else 0
bbs_aug[2] = bbs_aug[2] if bbs_aug[2] < size else size
bbs_aug[3] = bbs_aug[3] if bbs_aug[3] < size else size
return image_aug, bbs_aug
示例8
def main():
img = data.astronaut()
img = misc.imresize(img, (64, 64))
aug = iaa.Fliplr(0.5)
unseeded1 = aug.draw_grid(img, cols=8, rows=1)
unseeded2 = aug.draw_grid(img, cols=8, rows=1)
ia.seed(1000)
seeded1 = aug.draw_grid(img, cols=8, rows=1)
seeded2 = aug.draw_grid(img, cols=8, rows=1)
ia.seed(1000)
reseeded1 = aug.draw_grid(img, cols=8, rows=1)
reseeded2 = aug.draw_grid(img, cols=8, rows=1)
ia.seed(1001)
reseeded3 = aug.draw_grid(img, cols=8, rows=1)
reseeded4 = aug.draw_grid(img, cols=8, rows=1)
all_rows = np.vstack([unseeded1, unseeded2, seeded1, seeded2, reseeded1, reseeded2, reseeded3, reseeded4])
misc.imshow(all_rows)
示例9
def example_show():
print("Example: Show")
from imgaug import augmenters as iaa
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
seq = iaa.Sequential([iaa.Fliplr(0.5), iaa.GaussianBlur((0, 3.0))])
# show an image with 8*8 augmented versions of image 0
seq.show_grid(images[0], cols=8, rows=8)
# Show an image with 8*8 augmented versions of image 0 and 8*8 augmented
# versions of image 1. The identical augmentations will be applied to
# image 0 and 1.
seq.show_grid([images[0], images[1]], cols=8, rows=8)
# this example is no longer necessary as the library can now handle 2D images
示例10
def example_single_augmenters():
print("Example: Single Augmenters")
from imgaug import augmenters as iaa
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
flipper = iaa.Fliplr(1.0) # always horizontally flip each input image
images[0] = flipper.augment_image(images[0]) # horizontally flip image 0
vflipper = iaa.Flipud(0.9) # vertically flip each input image with 90% probability
images[1] = vflipper.augment_image(images[1]) # probably vertically flip image 1
blurer = iaa.GaussianBlur(3.0)
images[2] = blurer.augment_image(images[2]) # blur image 2 by a sigma of 3.0
images[3] = blurer.augment_image(images[3]) # blur image 3 by a sigma of 3.0 too
translater = iaa.Affine(translate_px={"x": -16}) # move each input image by 16px to the left
images[4] = translater.augment_image(images[4]) # move image 4 to the left
scaler = iaa.Affine(scale={"y": (0.8, 1.2)}) # scale each input image to 80-120% on the y axis
images[5] = scaler.augment_image(images[5]) # scale image 5 by 80-120% on the y axis
示例11
def _rectify_augmenter(self, augment):
import netharn as nh
if augment is True:
augment = 'simple'
if not augment:
augmenter = None
elif augment == 'simple':
augmenter = iaa.Sequential([
iaa.Crop(percent=(0, .2)),
iaa.Fliplr(p=.5)
])
elif augment == 'complex':
augmenter = iaa.Sequential([
iaa.Sometimes(0.2, nh.data.transforms.HSVShift(hue=0.1, sat=1.5, val=1.5)),
iaa.Crop(percent=(0, .2)),
iaa.Fliplr(p=.5)
])
else:
raise KeyError('Unknown augmentation {!r}'.format(augment))
return augmenter
示例12
def _rectify_augmenter(self, augmenter):
import netharn as nh
if augmenter is True:
augmenter = 'simple'
if not augmenter:
augmenter = None
elif augmenter == 'simple':
augmenter = iaa.Sequential([
iaa.Crop(percent=(0, .2)),
iaa.Fliplr(p=.5)
])
elif augmenter == 'complex':
augmenter = iaa.Sequential([
iaa.Sometimes(0.2, nh.data.transforms.HSVShift(hue=0.1, sat=1.5, val=1.5)),
iaa.Crop(percent=(0, .2)),
iaa.Fliplr(p=.5)
])
else:
raise KeyError('Unknown augmentation {!r}'.format(self.augment))
return augmenter
示例13
def _load_augmentation_aug_geometric():
return iaa.OneOf([
iaa.Sequential([iaa.Fliplr(0.5), iaa.Flipud(0.2)]),
iaa.CropAndPad(percent=(-0.05, 0.1),
pad_mode='constant',
pad_cval=(0, 255)),
iaa.Crop(percent=(0.0, 0.1)),
iaa.Crop(percent=(0.3, 0.5)),
iaa.Crop(percent=(0.3, 0.5)),
iaa.Crop(percent=(0.3, 0.5)),
iaa.Sequential([
iaa.Affine(
# scale images to 80-120% of their size,
# individually per axis
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},
# translate by -20 to +20 percent (per axis)
translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
rotate=(-45, 45), # rotate by -45 to +45 degrees
shear=(-16, 16), # shear by -16 to +16 degrees
# use nearest neighbour or bilinear interpolation (fast)
order=[0, 1],
# if mode is constant, use a cval between 0 and 255
mode='constant',
cval=(0, 255),
# use any of scikit-image's warping modes
# (see 2nd image from the top for examples)
),
iaa.Sometimes(0.3, iaa.Crop(percent=(0.3, 0.5)))])
])
示例14
def main():
image = data.astronaut()
print("image shape:", image.shape)
print("Press ENTER or wait %d ms to proceed to the next image." % (TIME_PER_STEP,))
children_all = [
("hflip", iaa.Fliplr(1)),
("add", iaa.Add(50)),
("dropout", iaa.Dropout(0.2)),
("affine", iaa.Affine(rotate=35))
]
channels_all = [
None,
0,
[],
[0],
[0, 1],
[1, 2],
[0, 1, 2]
]
cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
cv2.imshow("aug", image[..., ::-1])
cv2.waitKey(TIME_PER_STEP)
for children_title, children in children_all:
for channels in channels_all:
aug = iaa.WithChannels(channels=channels, children=children)
img_aug = aug.augment_image(image)
print("dtype", img_aug.dtype, "averages", np.average(img_aug, axis=tuple(range(0, img_aug.ndim-1))))
title = "children=%s " channels=%s" % (children_title, channels)
img_aug = ia.draw_text(img_aug, x=5, y=5, text=title)
cv2.imshow("aug", img_aug[..., ::-1]) # here with rgb2bgr
cv2.waitKey(TIME_PER_STEP)
示例15
def example_simple_training_setting():
print("Example: Simple Training Setting")
import numpy as np
import imgaug.augmenters as iaa
def load_batch(batch_idx):
# dummy function, implement this
# Return a numpy array of shape (N, height, width, #channels)
# or a list of (height, width, #channels) arrays (may have different image
# sizes).
# Images should be in RGB for colorspace augmentations.
# (cv2.imread() returns BGR!)
# Images should usually be in uint8 with values from 0-255.
return np.zeros((128, 32, 32, 3), dtype=np.uint8) + (batch_idx % 255)
def train_on_images(images):
# dummy function, implement this
pass
# Pipeline:
# (1) Crop images from each side by 1-16px, do not resize the results
# images back to the input size. Keep them at the cropped size.
# (2) Horizontally flip 50% of the images.
# (3) Blur images using a gaussian kernel with sigma between 0.0 and 3.0.
seq = iaa.Sequential([
iaa.Crop(px=(1, 16), keep_size=False),
iaa.Fliplr(0.5),
iaa.GaussianBlur(sigma=(0, 3.0))
])
for batch_idx in range(100):
images = load_batch(batch_idx)
images_aug = seq(images=images) # done by the library
train_on_images(images_aug)
# -----
# Make sure that the example really does something
if batch_idx == 0:
assert not np.array_equal(images, images_aug)
示例16
def example_visualize_augmented_images():
print("Example: Visualize Augmented Images")
import numpy as np
import imgaug.augmenters as iaa
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
seq = iaa.Sequential([iaa.Fliplr(0.5), iaa.GaussianBlur((0, 3.0))])
# Show an image with 8*8 augmented versions of image 0 and 8*8 augmented
# versions of image 1. Identical augmentations will be applied to
# image 0 and 1.
seq.show_grid([images[0], images[1]], cols=8, rows=8)
示例17
def example_using_augmenters_only_once():
print("Example: Using Augmenters Only Once")
from imgaug import augmenters as iaa
import numpy as np
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
# always horizontally flip each input image
images_aug = iaa.Fliplr(1.0)(images=images)
# vertically flip each input image with 90% probability
images_aug = iaa.Flipud(0.9)(images=images)
# blur 50% of all images using a gaussian kernel with a sigma of 3.0
images_aug = iaa.Sometimes(0.5, iaa.GaussianBlur(3.0))(images=images)
示例18
def example_multicore_augmentation():
print("Example: Multicore Augmentation")
import skimage.data
import imgaug as ia
import imgaug.augmenters as iaa
from imgaug.augmentables.batches import UnnormalizedBatch
# Number of batches and batch size for this example
nb_batches = 10
batch_size = 32
# Example augmentation sequence to run in the background
augseq = iaa.Sequential([
iaa.Fliplr(0.5),
iaa.CoarseDropout(p=0.1, size_percent=0.1)
])
# For simplicity, we use the same image here many times
astronaut = skimage.data.astronaut()
astronaut = ia.imresize_single_image(astronaut, (64, 64))
# Make batches out of the example image (here: 10 batches, each 32 times
# the example image)
batches = []
for _ in range(nb_batches):
batches.append(UnnormalizedBatch(images=[astronaut] * batch_size))
# Show the augmented images.
# Note that augment_batches() returns a generator.
for images_aug in augseq.augment_batches(batches, background=True):
ia.imshow(ia.draw_grid(images_aug.images_aug, cols=8))
示例19
def test_returns_fliplr(self):
aug = iaa.HorizontalFlip(0.5)
assert isinstance(aug, iaa.Fliplr)
assert np.allclose(aug.p.p.value, 0.5)
示例20
def create_aug(self, *args, **kwargs):
return iaa.Fliplr(*args, **kwargs)
示例21
def apply_augment_sequence(image_set_x, image_set_y):
"""
Randomly flip and rotate the images in both set with deterministic order. This turns 1 image into 8 images.
Parameters:
image_set_x: List of Images (X) to augment
image_set_y: List of corresponding Y image to augment in the same deterministic order applied to image_set_x
Returns:
image_setx_aug, image_sety_aug : augmented versions of the inputs
"""
# Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
# e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
sometimes = lambda aug: iaa.Sometimes(0.5, aug)
seq = iaa.Sequential(
[
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
sometimes(iaa.Affine(
rotate=(90, 90),
))
],
random_order=False)
seq_det = seq.to_deterministic()
image_setx_aug = seq_det.augment_images(image_set_x)
image_sety_aug = seq_det.augment_images(image_set_y)
return image_setx_aug, image_sety_aug
示例22
def augment_soft(img):
# Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
# e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
sometimes = lambda aug: iaa.Sometimes(0.5, aug)
# Define our sequence of augmentation steps that will be applied to every image
# All augmenters with per_channel=0.5 will sample one value _per image_
# in 50% of all cases. In all other cases they will sample new values
# _per channel_.
seq = iaa.Sequential(
[
# apply the following augmenters to most images
iaa.Fliplr(0.5), # horizontally flip 50% of all images
# crop images by -5% to 10% of their height/width
iaa.Crop(
percent=(0, 0.2),
),
iaa.Scale({"height": CROP_SIZE, "width": CROP_SIZE }),
],
random_order=False
)
if img.ndim == 3:
img = seq.augment_images(np.expand_dims(img, axis=0)).squeeze(axis=0)
else:
img = seq.augment_images(img)
return img
示例23
def aug_on_fly(img, det_mask, cls_mask):
"""Do augmentation with different combination on each training batch
"""
def image_basic_augmentation(image, masks, ratio_operations=0.9):
# without additional operations
# according to the paper, operations such as shearing, fliping horizontal/vertical,
# rotating, zooming and channel shifting will be apply
sometimes = lambda aug: iaa.Sometimes(ratio_operations, aug)
hor_flip_angle = np.random.uniform(0, 1)
ver_flip_angle = np.random.uniform(0, 1)
seq = iaa.Sequential([
sometimes(
iaa.SomeOf((0, 5), [
iaa.Fliplr(hor_flip_angle),
iaa.Flipud(ver_flip_angle),
iaa.Affine(shear=(-16, 16)),
iaa.Affine(scale={'x': (1, 1.6), 'y': (1, 1.6)}),
iaa.PerspectiveTransform(scale=(0.01, 0.1))
]))
])
det_mask, cls_mask = masks[0], masks[1]
seq_to_deterministic = seq.to_deterministic()
aug_img = seq_to_deterministic.augment_images(image)
aug_det_mask = seq_to_deterministic.augment_images(det_mask)
aug_cls_mask = seq_to_deterministic.augment_images(cls_mask)
return aug_img, aug_det_mask, aug_cls_mask
aug_image, aug_det_mask, aug_cls_mask = image_basic_augmentation(image=img, masks=[det_mask, cls_mask])
return aug_image, aug_det_mask, aug_cls_mask
示例24
def aug_on_fly(img, det_mask, cls_mask):
"""Do augmentation with different combination on each training batch
"""
def image_basic_augmentation(image, masks, ratio_operations=0.9):
# without additional operations
# according to the paper, operations such as shearing, fliping horizontal/vertical,
# rotating, zooming and channel shifting will be apply
sometimes = lambda aug: iaa.Sometimes(ratio_operations, aug)
hor_flip_angle = np.random.uniform(0, 1)
ver_flip_angle = np.random.uniform(0, 1)
seq = iaa.Sequential([
sometimes(
iaa.SomeOf((0, 5), [
iaa.Fliplr(hor_flip_angle),
iaa.Flipud(ver_flip_angle),
iaa.Affine(shear=(-16, 16)),
iaa.Affine(scale={'x': (1, 1.6), 'y': (1, 1.6)}),
iaa.PerspectiveTransform(scale=(0.01, 0.1))
]))
])
det_mask, cls_mask = masks[0], masks[1]
seq_to_deterministic = seq.to_deterministic()
aug_img = seq_to_deterministic.augment_images(image)
aug_det_mask = seq_to_deterministic.augment_images(det_mask)
aug_cls_mask = seq_to_deterministic.augment_images(cls_mask)
return aug_img, aug_det_mask, aug_cls_mask
aug_image, aug_det_mask, aug_cls_mask = image_basic_augmentation(image=img, masks=[det_mask, cls_mask])
return aug_image, aug_det_mask, aug_cls_mask
示例25
def main():
image = data.astronaut()
print("image shape:", image.shape)
print("Press any key or wait %d ms to proceed to the next image." % (TIME_PER_STEP,))
children_all = [
("hflip", iaa.Fliplr(1)),
("add", iaa.Add(50)),
("dropout", iaa.Dropout(0.2)),
("affine", iaa.Affine(rotate=35))
]
channels_all = [
None,
0,
[],
[0],
[0, 1],
[1, 2],
[0, 1, 2]
]
cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
cv2.imshow("aug", image[..., ::-1])
cv2.waitKey(TIME_PER_STEP)
for children_title, children in children_all:
for channels in channels_all:
aug = iaa.WithChannels(channels=channels, children=children)
img_aug = aug.augment_image(image)
print("dtype", img_aug.dtype, "averages", np.average(img_aug, axis=tuple(range(0, img_aug.ndim-1))))
#print("dtype", img_aug.dtype, "averages", img_aug.mean(axis=range(1, img_aug.ndim)))
title = "children=%s " channels=%s" % (children_title, channels)
img_aug = ia.draw_text(img_aug, x=5, y=5, text=title)
cv2.imshow("aug", img_aug[..., ::-1]) # here with rgb2bgr
cv2.waitKey(TIME_PER_STEP)
示例26
def chapter_augmenters_fliplr():
aug = iaa.Fliplr(0.5)
run_and_save_augseq(
"fliplr.jpg", aug,
[ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2
)
示例27
def example_hooks():
print("Example: Hooks")
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
# images and heatmaps, just arrays filled with value 30
images = np.ones((16, 128, 128, 3), dtype=np.uint8) * 30
heatmaps = np.ones((16, 128, 128, 21), dtype=np.uint8) * 30
# add vertical lines to see the effect of flip
images[:, 16:128-16, 120:124, :] = 120
heatmaps[:, 16:128-16, 120:124, :] = 120
seq = iaa.Sequential([
iaa.Fliplr(0.5, name="Flipper"),
iaa.GaussianBlur((0, 3.0), name="GaussianBlur"),
iaa.Dropout(0.02, name="Dropout"),
iaa.AdditiveGaussianNoise(scale=0.01*255, name="MyLittleNoise"),
iaa.AdditiveGaussianNoise(loc=32, scale=0.0001*255, name="SomeOtherNoise"),
iaa.Affine(translate_px={"x": (-40, 40)}, name="Affine")
])
# change the activated augmenters for heatmaps
def activator_heatmaps(images, augmenter, parents, default):
if augmenter.name in ["GaussianBlur", "Dropout", "MyLittleNoise"]:
return False
else:
# default value for all other augmenters
return default
hooks_heatmaps = ia.HooksImages(activator=activator_heatmaps)
seq_det = seq.to_deterministic() # call this for each batch again, NOT only once at the start
images_aug = seq_det.augment_images(images)
heatmaps_aug = seq_det.augment_images(heatmaps, hooks=hooks_heatmaps)
# -----------
ia.show_grid(images_aug)
ia.show_grid(heatmaps_aug[..., 0:3])
示例28
def example_background_augment_batches():
print("Example: Background Augmentation via augment_batches()")
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
from skimage import data
# Number of batches and batch size for this example
nb_batches = 10
batch_size = 32
# Example augmentation sequence to run in the background
augseq = iaa.Sequential([
iaa.Fliplr(0.5),
iaa.CoarseDropout(p=0.1, size_percent=0.1)
])
# For simplicity, we use the same image here many times
astronaut = data.astronaut()
astronaut = ia.imresize_single_image(astronaut, (64, 64))
# Make batches out of the example image (here: 10 batches, each 32 times
# the example image)
batches = []
for _ in range(nb_batches):
batches.append(
np.array(
[astronaut for _ in range(batch_size)],
dtype=np.uint8
)
)
# Show the augmented images.
# Note that augment_batches() returns a generator.
for images_aug in augseq.augment_batches(batches, background=True):
misc.imshow(ia.draw_grid(images_aug, cols=8))
示例29
def test_remove():
reseed()
def get_seq():
noop1 = iaa.Noop(name="Noop")
fliplr = iaa.Fliplr(name="Fliplr")
flipud = iaa.Flipud(name="Flipud")
noop2 = iaa.Noop(name="Noop2")
seq2 = iaa.Sequential([flipud, noop2], name="Seq2")
seq1 = iaa.Sequential([noop1, fliplr, seq2], name="Seq")
return seq1
augs = get_seq()
augs = augs.remove_augmenters(lambda aug, parents: aug.name == "Seq2")
seqs = augs.find_augmenters_by_name(r"Seq.*", regex=True)
assert len(seqs) == 1
assert seqs[0].name == "Seq"
augs = get_seq()
augs = augs.remove_augmenters(lambda aug, parents: aug.name == "Seq2" and len(parents) == 0)
seqs = augs.find_augmenters_by_name(r"Seq.*", regex=True)
assert len(seqs) == 2
assert seqs[0].name == "Seq"
assert seqs[1].name == "Seq2"
augs = get_seq()
augs = augs.remove_augmenters(lambda aug, parents: True)
assert augs is not None
assert isinstance(augs, iaa.Noop)
augs = get_seq()
augs = augs.remove_augmenters(lambda aug, parents: True, noop_if_topmost=False)
assert augs is None
示例30
def __init__(self):
self.imgaug_transform = iaa.Fliplr(p=1)
self.augmentor_op = Operations.Flip(probability=1, top_bottom_left_right="LEFT_RIGHT")
self.solt_stream = slc.Stream([slt.RandomFlip(p=1, axis=1)])