Python源码示例:imgaug.augmenters.GaussianBlur()
示例1
def _load_augmentation_aug_non_geometric():
return iaa.Sequential([
iaa.Sometimes(0.3, iaa.Multiply((0.5, 1.5), per_channel=0.5)),
iaa.Sometimes(0.2, iaa.JpegCompression(compression=(70, 99))),
iaa.Sometimes(0.2, iaa.GaussianBlur(sigma=(0, 3.0))),
iaa.Sometimes(0.2, iaa.MotionBlur(k=15, angle=[-45, 45])),
iaa.Sometimes(0.2, iaa.MultiplyHue((0.5, 1.5))),
iaa.Sometimes(0.2, iaa.MultiplySaturation((0.5, 1.5))),
iaa.Sometimes(0.34, iaa.MultiplyHueAndSaturation((0.5, 1.5),
per_channel=True)),
iaa.Sometimes(0.34, iaa.Grayscale(alpha=(0.0, 1.0))),
iaa.Sometimes(0.2, iaa.ChangeColorTemperature((1100, 10000))),
iaa.Sometimes(0.1, iaa.GammaContrast((0.5, 2.0))),
iaa.Sometimes(0.2, iaa.SigmoidContrast(gain=(3, 10),
cutoff=(0.4, 0.6))),
iaa.Sometimes(0.1, iaa.CLAHE()),
iaa.Sometimes(0.1, iaa.HistogramEqualization()),
iaa.Sometimes(0.2, iaa.LinearContrast((0.5, 2.0), per_channel=0.5)),
iaa.Sometimes(0.1, iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)))
])
示例2
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)
示例3
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)
示例4
def test_backends_called(self):
def side_effect_cv2(image, ksize, sigmaX, sigmaY, borderType):
return image + 1
def side_effect_scipy(image, sigma, mode):
return image + 1
mock_GaussianBlur = mock.Mock(side_effect=side_effect_cv2)
mock_gaussian_filter = mock.Mock(side_effect=side_effect_scipy)
image = np.arange(4*4).astype(np.uint8).reshape((4, 4))
with mock.patch('cv2.GaussianBlur', mock_GaussianBlur):
_observed = iaa.blur_gaussian_(
np.copy(image), sigma=1.0, eps=0, backend="cv2")
assert mock_GaussianBlur.call_count == 1
with mock.patch('scipy.ndimage.gaussian_filter', mock_gaussian_filter):
_observed = iaa.blur_gaussian_(
np.copy(image), sigma=1.0, eps=0, backend="scipy")
assert mock_gaussian_filter.call_count == 1
示例5
def __init__(self):
self.seq = iaa.Sequential([
iaa.Sometimes(0.5, iaa.OneOf([
iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0
iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7
iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7
])),
iaa.Sometimes(0.5, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5)),
iaa.Sometimes(0.5, iaa.Add((-10, 10), per_channel=0.5)),
iaa.Sometimes(0.5, iaa.AddToHueAndSaturation((-20, 20))),
iaa.Sometimes(0.5, iaa.FrequencyNoiseAlpha(
exponent=(-4, 0),
first=iaa.Multiply((0.5, 1.5), per_channel=True),
second=iaa.LinearContrast((0.5, 2.0))
)),
iaa.Sometimes(0.5, iaa.PiecewiseAffine(scale=(0.01, 0.05))),
iaa.Sometimes(0.5, iaa.PerspectiveTransform(scale=(0.01, 0.1)))
], random_order=True)
示例6
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([])
示例7
def init_augmentations(self):
if self.transform_probability > 0 and self.use_imgaug:
augmentations = iaa.Sometimes(
self.transform_probability,
iaa.Sequential([
iaa.SomeOf(
(1, None),
[
iaa.AddToHueAndSaturation(iap.Uniform(-20, 20), per_channel=True),
iaa.GaussianBlur(sigma=(0, 1.0)),
iaa.LinearContrast((0.75, 1.0)),
iaa.PiecewiseAffine(scale=(0.01, 0.02), mode='edge'),
],
random_order=True
),
iaa.Resize(
{"height": (16, self.image_size.height), "width": "keep-aspect-ratio"},
interpolation=imgaug.ALL
),
])
)
else:
augmentations = None
return augmentations
示例8
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
示例9
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
)
示例10
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
示例11
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
示例12
def __init__(self,data_dir, back_dir,
batch_size=50,gan=True,imsize=128,
res_x=640,res_y=480,
**kwargs):
'''
data_dir: Folder that contains cropped image+xyz
back_dir: Folder that contains random background images
batch_size: batch size for training
gan: if False, gt for GAN is not yielded
'''
self.data_dir = data_dir
self.back_dir = back_dir
self.imsize=imsize
self.batch_size = batch_size
self.gan = gan
self.backfiles = os.listdir(back_dir)
data_list = os.listdir(data_dir)
self.datafiles=[]
self.res_x=res_x
self.res_y=res_y
for file in data_list:
if(file.endswith(".npy")):
self.datafiles.append(file)
self.n_data = len(self.datafiles)
self.n_background = len(self.backfiles)
print("Total training views:", self.n_data)
self.seq_syn= iaa.Sequential([
iaa.WithChannels(0, iaa.Add((-15, 15))),
iaa.WithChannels(1, iaa.Add((-15, 15))),
iaa.WithChannels(2, iaa.Add((-15, 15))),
iaa.ContrastNormalization((0.8, 1.3)),
iaa.Multiply((0.8, 1.2),per_channel=0.5),
iaa.GaussianBlur(sigma=(0.0, 0.5)),
iaa.Sometimes(0.1, iaa.AdditiveGaussianNoise(scale=10, per_channel=True)),
iaa.Sometimes(0.5, iaa.ContrastNormalization((0.5, 2.2), per_channel=0.3)),
], random_order=True)
示例13
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)
示例14
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)
示例15
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)
示例16
def test_ksize(self):
def side_effect(image, ksize, sigmaX, sigmaY, borderType):
return image + 1
sigmas = [5.0, 5.0]
ksizes = [None, 3]
ksizes_expected = [2.6*5.0, 3]
gen = zip(sigmas, ksizes, ksizes_expected)
for (sigma, ksize, ksize_expected) in gen:
with self.subTest(sigma=sigma, ksize=ksize):
mock_GaussianBlur = mock.Mock(side_effect=side_effect)
image = np.arange(4*4).astype(np.uint8).reshape((4, 4))
with mock.patch('cv2.GaussianBlur', mock_GaussianBlur):
observed = iaa.blur_gaussian_(
np.copy(image),
sigma=sigma,
ksize=ksize,
backend="cv2")
assert np.array_equal(observed, image+1)
cargs = mock_GaussianBlur.call_args
assert mock_GaussianBlur.call_count == 1
assert np.array_equal(cargs[0][0], image)
assert isinstance(cargs[0][1], tuple)
assert np.allclose(
np.float32(cargs[0][1]),
np.float32([ksize_expected, ksize_expected]))
assert np.isclose(cargs[1]["sigmaX"], sigma)
assert np.isclose(cargs[1]["sigmaY"], sigma)
assert cargs[1]["borderType"] == cv2.BORDER_REFLECT_101
示例17
def test_sigma_is_zero(self):
# no blur, shouldnt change anything
base_img = np.array([[0, 0, 0],
[0, 255, 0],
[0, 0, 0]], dtype=np.uint8)
base_img = base_img[:, :, np.newaxis]
images = np.array([base_img])
aug = iaa.GaussianBlur(sigma=0)
observed = aug.augment_images(images)
expected = images
assert np.array_equal(observed, expected)
示例18
def test_low_sigma(self):
base_img = np.array([[0, 0, 0],
[0, 255, 0],
[0, 0, 0]], dtype=np.uint8)
base_img = base_img[:, :, np.newaxis]
images = np.array([base_img])
images_list = [base_img]
outer_pixels = ([], [])
for i in sm.xrange(base_img.shape[0]):
for j in sm.xrange(base_img.shape[1]):
if i != j:
outer_pixels[0].append(i)
outer_pixels[1].append(j)
# weak blur of center pixel
aug = iaa.GaussianBlur(sigma=0.5)
aug_det = aug.to_deterministic()
# images as numpy array
observed = aug.augment_images(images)
assert 100 < observed[0][1, 1] < 255
assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()
assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()
observed = aug_det.augment_images(images)
assert 100 < observed[0][1, 1] < 255
assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()
assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()
# images as list
observed = aug.augment_images(images_list)
assert 100 < observed[0][1, 1] < 255
assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()
assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()
observed = aug_det.augment_images(images_list)
assert 100 < observed[0][1, 1] < 255
assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()
assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()
示例19
def test_sigma_is_tuple(self):
# varying blur sigmas
base_img = np.array([[0, 0, 0],
[0, 255, 0],
[0, 0, 0]], dtype=np.uint8)
base_img = base_img[:, :, np.newaxis]
images = np.array([base_img])
aug = iaa.GaussianBlur(sigma=(0, 1))
aug_det = aug.to_deterministic()
last_aug = None
last_aug_det = None
nb_changed_aug = 0
nb_changed_aug_det = 0
nb_iterations = 1000
for i in sm.xrange(nb_iterations):
observed_aug = aug.augment_images(images)
observed_aug_det = aug_det.augment_images(images)
if i == 0:
last_aug = observed_aug
last_aug_det = observed_aug_det
else:
if not np.array_equal(observed_aug, last_aug):
nb_changed_aug += 1
if not np.array_equal(observed_aug_det, last_aug_det):
nb_changed_aug_det += 1
last_aug = observed_aug
last_aug_det = observed_aug_det
assert nb_changed_aug >= int(nb_iterations * 0.8)
assert nb_changed_aug_det == 0
示例20
def test_other_dtypes_bool_at_sigma_0(self):
# bool
aug = iaa.GaussianBlur(sigma=0)
image = np.zeros((3, 3), dtype=bool)
image[1, 1] = True
image_aug = aug.augment_image(image)
assert image_aug.dtype.type == np.bool_
assert np.all(image_aug == image)
示例21
def test_other_dtypes_uint_int_at_sigma_0(self):
aug = iaa.GaussianBlur(sigma=0)
dts = [np.uint8, np.uint16, np.uint32,
np.int8, np.int16, np.int32]
for dtype in dts:
_min_value, center_value, _max_value = \
iadt.get_value_range_of_dtype(dtype)
image = np.zeros((3, 3), dtype=dtype)
image[1, 1] = int(center_value)
image_aug = aug.augment_image(image)
assert image_aug.dtype.type == dtype
assert np.all(image_aug == image)
示例22
def test_other_dtypes_float_at_sigma_0(self):
aug = iaa.GaussianBlur(sigma=0)
dts = [np.float16, np.float32, np.float64]
for dtype in dts:
_min_value, center_value, _max_value = \
iadt.get_value_range_of_dtype(dtype)
image = np.zeros((3, 3), dtype=dtype)
image[1, 1] = center_value
image_aug = aug.augment_image(image)
assert image_aug.dtype.type == dtype
assert np.allclose(image_aug, image)
示例23
def test_other_dtypes_bool_at_sigma_060(self):
# --
# blur of bool input at sigma=0.6
# --
# here we use a special mask and sigma as otherwise the only values
# ending up with >0.5 would be the ones that
# were before the blur already at >0.5
# prototype kernel, generated via:
# mask = np.zeros((5, 5), dtype=np.float64)
# mask[1, 0] = 255
# mask[2, 0] = 255
# mask[2, 2] = 255
# mask[2, 4] = 255
# mask[3, 0] = 255
# mask = ndimage.gaussian_filter(mask, 1.0, mode="mirror")
aug = iaa.GaussianBlur(sigma=0.6)
mask_bool = np.float64([
[ 57, 14, 2, 1, 1],
[142, 42, 29, 14, 28],
[169, 69, 114, 56, 114],
[142, 42, 29, 14, 28],
[ 57, 14, 2, 1, 1]
]) / 255.0
image = np.zeros((5, 5), dtype=bool)
image[1, 0] = True
image[2, 0] = True
image[2, 2] = True
image[2, 4] = True
image[3, 0] = True
image_aug = aug.augment_image(image)
expected = mask_bool > 0.5
assert image_aug.shape == mask_bool.shape
assert image_aug.dtype.type == np.bool_
assert np.all(image_aug == expected)
示例24
def test_failure_on_invalid_dtypes(self):
# assert failure on invalid dtypes
aug = iaa.GaussianBlur(sigma=1.0)
for dt in [np.float128]:
got_exception = False
try:
_ = aug.augment_image(np.zeros((1, 1), dtype=dt))
except Exception as exc:
assert "forbidden dtype" in str(exc)
got_exception = True
assert got_exception
示例25
def test_pickleable(self):
aug = iaa.GaussianBlur((0.1, 3.0), seed=1)
runtest_pickleable_uint8_img(aug, iterations=10)
示例26
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
示例27
def chapter_augmenters_gaussianblur():
aug = iaa.GaussianBlur(sigma=(0.0, 3.0))
run_and_save_augseq(
"gaussianblur.jpg", aug,
[ia.quokka(size=(128, 128)) for _ in range(16)], cols=4, rows=4,
quality=75
)
示例28
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),
quality=25
)
示例29
def example_standard_situation():
print("Example: Standard Situation")
# -------
# dummy functions to make the example runnable here
def load_batch(batch_idx):
return np.random.randint(0, 255, (1, 16, 16, 3), dtype=np.uint8)
def train_on_images(images):
pass
# -------
from imgaug import augmenters as iaa
seq = iaa.Sequential([
iaa.Crop(px=(0, 16)), # crop images from each side by 0 to 16px (randomly chosen)
iaa.Fliplr(0.5), # horizontally flip 50% of the images
iaa.GaussianBlur(sigma=(0, 3.0)) # blur images with a sigma of 0 to 3.0
])
for batch_idx in range(1000):
# 'images' should be either a 4D numpy array of shape (N, height, width, channels)
# or a list of 3D numpy arrays, each having shape (height, width, channels).
# Grayscale images must have shape (height, width, 1) each.
# All images must have numpy's dtype uint8. Values are expected to be in
# range 0-255.
images = load_batch(batch_idx)
images_aug = seq.augment_images(images)
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)
示例30
def example_determinism():
print("Example: Determinism")
from imgaug import 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.randint(0, 255, (16, 128, 128, 21), dtype=np.uint8)
seq = iaa.Sequential([iaa.GaussianBlur((0, 3.0)), iaa.Affine(translate_px={"x": (-40, 40)})])
# Convert the stochastic sequence of augmenters to a deterministic one.
# The deterministic sequence will always apply the exactly same effects to the images.
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)
# -----
# Make sure that the example really does something
import imgaug as ia
assert not np.array_equal(images, images_aug)
assert not np.array_equal(heatmaps, heatmaps_aug)
images_show = []
for img_idx in range(len(images)):
images_show.extend([images[img_idx], images_aug[img_idx], heatmaps[img_idx][..., 0:3], heatmaps_aug[img_idx][..., 0:3]])
ia.show_grid(images_show, cols=4)