Python源码示例:imgaug.augmenters.Affine()
示例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 example_augment_images_and_keypoints():
print("Example: Augment Images and Keypoints")
import numpy as np
import imgaug.augmenters as iaa
images = np.zeros((2, 128, 128, 3), dtype=np.uint8) # two example images
images[:, 64, 64, :] = 255
points = [
[(10.5, 20.5)], # points on first image
[(50.5, 50.5), (60.5, 60.5), (70.5, 70.5)] # points on second image
]
seq = iaa.Sequential([
iaa.AdditiveGaussianNoise(scale=0.05*255),
iaa.Affine(translate_px={"x": (1, 5)})
])
# augment keypoints and images
images_aug, points_aug = seq(images=images, keypoints=points)
print("Image 1 center", np.argmax(images_aug[0, 64, 64:64+6, 0]))
print("Image 2 center", np.argmax(images_aug[1, 64, 64:64+6, 0]))
print("Points 1", points_aug[0])
print("Points 2", points_aug[1])
示例3
def example_augment_images_and_bounding_boxes():
print("Example: Augment Images and Bounding Boxes")
import numpy as np
import imgaug as ia
import imgaug.augmenters as iaa
images = np.zeros((2, 128, 128, 3), dtype=np.uint8) # two example images
images[:, 64, 64, :] = 255
bbs = [
[ia.BoundingBox(x1=10.5, y1=15.5, x2=30.5, y2=50.5)],
[ia.BoundingBox(x1=10.5, y1=20.5, x2=50.5, y2=50.5),
ia.BoundingBox(x1=40.5, y1=75.5, x2=70.5, y2=100.5)]
]
seq = iaa.Sequential([
iaa.AdditiveGaussianNoise(scale=0.05*255),
iaa.Affine(translate_px={"x": (1, 5)})
])
images_aug, bbs_aug = seq(images=images, bounding_boxes=bbs)
示例4
def example_augment_images_and_polygons():
print("Example: Augment Images and Polygons")
import numpy as np
import imgaug as ia
import imgaug.augmenters as iaa
images = np.zeros((2, 128, 128, 3), dtype=np.uint8) # two example images
images[:, 64, 64, :] = 255
polygons = [
[ia.Polygon([(10.5, 10.5), (50.5, 10.5), (50.5, 50.5)])],
[ia.Polygon([(0.0, 64.5), (64.5, 0.0), (128.0, 128.0), (64.5, 128.0)])]
]
seq = iaa.Sequential([
iaa.AdditiveGaussianNoise(scale=0.05*255),
iaa.Affine(translate_px={"x": (1, 5)})
])
images_aug, polygons_aug = seq(images=images, polygons=polygons)
示例5
def example_augment_images_and_heatmaps():
print("Example: Augment Images and Heatmaps")
import numpy as np
import imgaug.augmenters as iaa
# Standard scenario: You have N RGB-images and additionally 21 heatmaps per
# image. You want to augment each image and its heatmaps identically.
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
heatmaps = np.random.random(size=(16, 64, 64, 1)).astype(np.float32)
seq = iaa.Sequential([
iaa.GaussianBlur((0, 3.0)),
iaa.Affine(translate_px={"x": (-40, 40)}),
iaa.Crop(px=(0, 10))
])
images_aug, heatmaps_aug = seq(images=images, heatmaps=heatmaps)
示例6
def example_augment_images_and_segmentation_maps():
print("Example: Augment Images and Segmentation Maps")
import numpy as np
import imgaug.augmenters as iaa
# Standard scenario: You have N=16 RGB-images and additionally one segmentation
# map per image. You want to augment each image and its heatmaps identically.
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
segmaps = np.random.randint(0, 10, size=(16, 64, 64, 1), dtype=np.int32)
seq = iaa.Sequential([
iaa.GaussianBlur((0, 3.0)),
iaa.Affine(translate_px={"x": (-40, 40)}),
iaa.Crop(px=(0, 10))
])
images_aug, segmaps_aug = seq(images=images, segmentation_maps=segmaps)
示例7
def _test_cba_hooks_limit_propagation(cls, augf_name, cbaoi):
aug = iaa.BlendAlpha(
0.0,
iaa.Affine(translate_px={"x": 1}),
iaa.Affine(translate_px={"y": 1}),
name="AlphaTest")
def propagator(cbaoi_to_aug, augmenter, parents, default):
if "Alpha" in augmenter.name:
return False
else:
return default
# no hooks for polygons yet, so we use HooksKeypoints
hooks = ia.HooksKeypoints(propagator=propagator)
observed = getattr(aug, augf_name)([cbaoi], hooks=hooks)[0]
assert observed.items[0].coords_almost_equals(cbaoi.items[0])
示例8
def _test_cba_hooks_limit_propagation(cls, augf_name, cbaoi):
aug = iaa.BlendAlphaElementwise(
0.0,
iaa.Affine(translate_px={"x": 1}),
iaa.Affine(translate_px={"y": 1}),
name="AlphaTest")
def propagator(cbaoi_to_aug, augmenter, parents, default):
if "Alpha" in augmenter.name:
return False
else:
return default
# no hooks for polygons yet, so we use HooksKeypoints
hooks = ia.HooksKeypoints(propagator=propagator)
observed = getattr(aug, augf_name)([cbaoi], hooks=hooks)[0]
assert observed.items[0].coords_almost_equals(cbaoi.items[0])
示例9
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
)
)
示例10
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
示例11
def img_aug(img):
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)},
cval=(255)
).to_deterministic()
img = translater.augment_image(img)
#vertically flip
if random.random() < 0.5:
img = np.flip(img,0)
# horizontally flip
if random.random() < 0.5:
img = np.flip(img,1)
if random.random() < 0.5:
rot_time = random.choice([1, 2, 3])
img = np.rot90(img,rot_time)
return img
示例12
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([])
示例13
def amaugimg(image):
#数据增强
image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
seq = iaa.Sequential([
# iaa.Affine(rotate=(-5, 5),
# shear=(-5, 5),
# mode='edge'),
iaa.SomeOf((0, 2), #选择数据增强
[
iaa.GaussianBlur((0, 1.5)),
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.01 * 255), per_channel=0.5),
# iaa.AddToHueAndSaturation((-5, 5)), # change hue and saturation
iaa.PiecewiseAffine(scale=(0.01, 0.03)),
iaa.PerspectiveTransform(scale=(0.01, 0.1))
],
random_order=True
)
])
image = seq.augment_image(image)
image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
return image
示例14
def augment(image, bbox):
x = random.randint(-50, 50)
y = random.randint(-50, 50)
aug = iaa.Sequential([iaa.Multiply(random.uniform(0.5, 1.5)),
iaa.AdditiveGaussianNoise(random.uniform(0.01, 0.1) * 255),
iaa.Affine(translate_px={"x": x, "y": y},
scale=random.uniform(0.5, 1.5),
rotate=random.uniform(-45, 45),
cval=(0, 255))])
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)
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
示例15
def augment(image, bbox):
x = random.randint(-60, 60)
y = random.randint(-60, 60)
aug = iaa.Sequential([iaa.AdditiveGaussianNoise(scale=random.uniform(.001, .01) * 255), # gaussian noise
iaa.Multiply(random.uniform(0.5, 1.5)), # brightness
iaa.Affine(translate_px={"x": x, "y": y}, # translation
scale=random.uniform(0.5, 1.5), # zoom in and out
rotate=random.uniform(-25, 25), # rotation
shear=random.uniform(-5, 5), # shear transformation
cval=(0, 255))]) # fill the empty space with color
aug.add(iaa.Salt(.001))
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)
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
示例16
def chapter_augmenters_sequential():
aug = iaa.Sequential([
iaa.Affine(translate_px={"x":-40}),
iaa.AdditiveGaussianNoise(scale=0.2*255)
])
run_and_save_augseq(
"sequential.jpg", aug,
[ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2
)
aug = iaa.Sequential([
iaa.Affine(translate_px={"x":-40}),
iaa.AdditiveGaussianNoise(scale=0.2*255)
], random_order=True)
run_and_save_augseq(
"sequential_random_order.jpg", aug,
[ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2
)
示例17
def chapter_augmenters_sometimes():
aug = iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=2.0))
run_and_save_augseq(
"sometimes.jpg", aug,
[ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2,
seed=2
)
aug = iaa.Sometimes(
0.5,
iaa.GaussianBlur(sigma=2.0),
iaa.Sequential([iaa.Affine(rotate=45), iaa.Sharpen(alpha=1.0)])
)
run_and_save_augseq(
"sometimes_if_else.jpg", aug,
[ia.quokka(size=(64, 64)) for _ in range(16)], cols=8, rows=2
)
示例18
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
示例19
def augmentation():
# augment images with spatial transformation: Flip, Affine, Rotation, etc...
# see https://github.com/aleju/imgaug for more details
pass
示例20
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)))])
])
示例21
def main():
image = data.astronaut()
image = ia.imresize_single_image(image, (HEIGHT, WIDTH))
kps = []
for y in range(NB_ROWS):
ycoord = BB_Y1 + int(y * (BB_Y2 - BB_Y1) / (NB_COLS - 1))
for x in range(NB_COLS):
xcoord = BB_X1 + int(x * (BB_X2 - BB_X1) / (NB_ROWS - 1))
kp = (xcoord, ycoord)
kps.append(kp)
kps = set(kps)
kps = [ia.Keypoint(x=xcoord, y=ycoord) for (xcoord, ycoord) in kps]
kps = ia.KeypointsOnImage(kps, shape=image.shape)
bb = ia.BoundingBox(x1=BB_X1, x2=BB_X2, y1=BB_Y1, y2=BB_Y2)
bbs = ia.BoundingBoxesOnImage([bb], shape=image.shape)
seq = iaa.Affine(rotate=45)
seq_det = seq.to_deterministic()
image_aug = seq_det.augment_image(image)
kps_aug = seq_det.augment_keypoints([kps])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
image_before = np.copy(image)
image_before = kps.draw_on_image(image_before)
image_before = bbs.draw_on_image(image_before)
image_after = np.copy(image_aug)
image_after = kps_aug.draw_on_image(image_after)
image_after = bbs_aug.draw_on_image(image_after)
ia.imshow(np.hstack([image_before, image_after]))
imageio.imwrite("bb_aug.jpg", np.hstack([image_before, image_after]))
示例22
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)
示例23
def main():
nb_checked = 0
augs = iaa.SomeOf((1, None), [
iaa.Resize({"height": (1, 100), "width": (1, 100)}),
iaa.Affine(
scale=(0.01, 2.0),
rotate=(-360, 360),
shear=(-360, 360),
translate_px={"x": (-50, 50), "y": (-50, 50)}
),
iaa.PerspectiveTransform((0.01, 0.2))
])
height, width = 100, 200
while True:
poly = create_random_polygon(height, width, nb_checked)
psoi = PolygonsOnImage([poly], shape=(height, width, 3))
psoi_aug = augs.augment_polygons(psoi)
if not poly.is_valid or not psoi_aug.polygons[0].is_valid:
print("poly: ", poly, poly.is_valid)
print("poly_aug: ", psoi_aug.polygons[0], psoi_aug.polygons[0].is_valid)
assert poly.is_valid
assert psoi_aug.polygons[0].is_valid
nb_checked += 1
if nb_checked % 100 == 0:
print("Checked %d..." % (nb_checked,))
if nb_checked > 100000:
break
示例24
def test_heatmaps_factor_is_1_with_affines_and_per_channel(self):
for per_channel in [False, True]:
with self.subTest(per_channel=per_channel):
aug = iaa.BlendAlpha(
1,
iaa.Affine(translate_px={"x": 1}),
iaa.Affine(translate_px={"x": -1}),
per_channel=per_channel)
observed = aug.augment_heatmaps([self.heatmaps])[0]
assert observed.shape == self.heatmaps.shape
assert 0 - 1e-6 < self.heatmaps.min_value < 0 + 1e-6
assert 1 - 1e-6 < self.heatmaps.max_value < 1 + 1e-6
assert np.allclose(observed.get_arr(),
self.heatmaps_r1.get_arr())
示例25
def test_heatmaps_factor_is_0_with_affines_and_per_channel(self):
for per_channel in [False, True]:
with self.subTest(per_channel=per_channel):
aug = iaa.BlendAlpha(
0,
iaa.Affine(translate_px={"x": 1}),
iaa.Affine(translate_px={"x": -1}),
per_channel=per_channel)
observed = aug.augment_heatmaps([self.heatmaps])[0]
assert observed.shape == self.heatmaps.shape
assert 0 - 1e-6 < self.heatmaps.min_value < 0 + 1e-6
assert 1 - 1e-6 < self.heatmaps.max_value < 1 + 1e-6
assert np.allclose(observed.get_arr(),
self.heatmaps_l1.get_arr())
示例26
def test_segmaps_factor_is_0_with_affines_and_per_channel(self):
for per_channel in [False, True]:
with self.subTest(per_channel=per_channel):
aug = iaa.BlendAlpha(
0,
iaa.Affine(translate_px={"x": 1}),
iaa.Affine(translate_px={"x": -1}),
per_channel=per_channel)
observed = aug.augment_segmentation_maps([self.segmaps])[0]
assert observed.shape == self.segmaps.shape
assert np.array_equal(observed.get_arr(),
self.segmaps_l1.get_arr())
示例27
def _test_cba_factor_is_1(cls, augf_name, cbaoi):
aug = iaa.BlendAlpha(
1.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1}))
observed = getattr(aug, augf_name)([cbaoi])
assert_cbaois_equal(observed[0], cbaoi)
示例28
def _test_cba_factor_is_0501(cls, augf_name, cbaoi):
aug = iaa.BlendAlpha(0.501,
iaa.Identity(),
iaa.Affine(translate_px={"x": 1}))
observed = getattr(aug, augf_name)([cbaoi])
assert_cbaois_equal(observed[0], cbaoi)
示例29
def _test_cba_factor_is_0(cls, augf_name, cbaoi):
aug = iaa.BlendAlpha(
0.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1}))
observed = getattr(aug, augf_name)([cbaoi])
expected = cbaoi.shift(x=1)
assert_cbaois_equal(observed[0], expected)
示例30
def _test_cba_factor_is_1_and_per_channel(cls, augf_name, cbaoi):
aug = iaa.BlendAlpha(
1.0,
iaa.Identity(),
iaa.Affine(translate_px={"x": 1}),
per_channel=True)
observed = getattr(aug, augf_name)([cbaoi])
assert_cbaois_equal(observed[0], cbaoi)