Python源码示例:imgaug.augmenters.Grayscale()
示例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 test_grayscale_drops_different_colors(self):
image = np.uint8([
[255, 0, 0],
[0, 255, 0],
[0, 0, 255],
[255, 255, 0],
[255, 0, 255],
[0, 255, 255],
[255, 128, 128],
[128, 255, 128],
[128, 128, 255]
]).reshape((1, 9, 3))
image_gray = iaa.Grayscale(1.0)(image=image)
aug = iaa.BlendAlphaSomeColors(iaa.Grayscale(1.0),
nb_bins=256, smoothness=0)
nb_grayscaled = []
for _ in sm.xrange(50):
image_aug = aug(image=image)
grayscaled = np.sum((image_aug == image_gray).astype(np.int32),
axis=2)
assert np.all(np.logical_or(grayscaled == 0, grayscaled == 3))
nb_grayscaled.append(np.sum(grayscaled == 3))
assert len(set(nb_grayscaled)) >= 5
示例3
def test_alpha_is_0(self):
aug = iaa.Grayscale(0.0)
observed = aug.augment_image(self.base_img)
expected = np.copy(self.base_img)
assert np.allclose(observed, expected)
示例4
def test_alpha_is_1(self):
aug = iaa.Grayscale(1.0)
observed = aug.augment_image(self.base_img)
luminosity = self._compute_luminosity(10, 20, 30)
expected = np.zeros_like(self.base_img) + luminosity
assert np.allclose(observed, expected.astype(np.uint8))
示例5
def test_alpha_is_050(self):
aug = iaa.Grayscale(0.5)
observed = aug.augment_image(self.base_img)
luminosity = self._compute_luminosity(10, 20, 30)
expected = 0.5 * self.base_img + 0.5 * luminosity
assert np.allclose(observed, expected.astype(np.uint8))
示例6
def test_alpha_is_tuple(self):
aug = iaa.Grayscale((0.0, 1.0))
base_img = np.uint8([255, 0, 0]).reshape((1, 1, 3))
base_img_float = base_img.astype(np.float64) / 255.0
base_img_gray = iaa.Grayscale(1.0)\
.augment_image(base_img)\
.astype(np.float64) / 255.0
distance_max = np.linalg.norm(base_img_gray.flatten()
- base_img_float.flatten())
nb_iterations = 1000
distances = []
for _ in sm.xrange(nb_iterations):
observed = aug.augment_image(base_img).astype(np.float64) / 255.0
distance = np.linalg.norm(
observed.flatten() - base_img_float.flatten()) / distance_max
distances.append(distance)
assert 0 - 1e-4 < min(distances) < 0.1
assert 0.4 < np.average(distances) < 0.6
assert 0.9 < max(distances) < 1.0 + 1e-4
nb_bins = 5
hist, _ = np.histogram(
distances, bins=nb_bins, range=(0.0, 1.0), density=False)
density_expected = 1.0/nb_bins
density_tolerance = 0.05
for nb_samples in hist:
density = nb_samples / nb_iterations
assert np.isclose(density, density_expected,
rtol=0, atol=density_tolerance)
示例7
def chapter_augmenters_grayscale():
aug = iaa.Grayscale(alpha=(0.0, 1.0))
run_and_save_augseq(
"grayscale.jpg", aug,
[ia.quokka(size=(128, 128)) for _ in range(8)], cols=4, rows=2
)
#alphas = [1/8*i for i in range(8)]
alphas = np.linspace(0, 1.0, num=8)
run_and_save_augseq(
"grayscale_vary_alpha.jpg",
[iaa.Grayscale(alpha=alpha) for alpha in alphas],
[ia.quokka(size=(64, 64)) for _ in range(8)], cols=8, rows=1,
quality=75
)
示例8
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)
示例9
def __init__(self):
self.augmentor_op = Operations.Greyscale(probability=1)
self.imgaug_transform = iaa.Grayscale(alpha=1.0)
self.solt_stream = slc.Stream([slt.ImageColorTransform(mode="rgb2gs")])
示例10
def greyscale(images, alpha):
transformer = iaa.Grayscale(alpha=(0.0, alpha), deterministic=True)
images = [impr.invert_image(img) for img in images]
return keep_L_channel(augment_on_df(images, transformer))
示例11
def _create_augment_pipeline():
from imgaug import augmenters as iaa
### augmentors by https://github.com/aleju/imgaug
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_.
aug_pipe = iaa.Sequential(
[
# apply the following augmenters to most images
#iaa.Fliplr(0.5), # horizontally flip 50% of all images
#iaa.Flipud(0.2), # vertically flip 20% of all images
#sometimes(iaa.Crop(percent=(0, 0.1))), # crop images by 0-10% of their height/width
sometimes(iaa.Affine(
#scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis
#translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)
#rotate=(-5, 5), # rotate by -45 to +45 degrees
#shear=(-5, 5), # shear by -16 to +16 degrees
#order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)
#cval=(0, 255), # if mode is constant, use a cval between 0 and 255
#mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)
)),
# execute 0 to 5 of the following (less important) augmenters per image
# don't execute all of them, as that would often be way too strong
iaa.SomeOf((0, 5),
[
#sometimes(iaa.Superpixels(p_replace=(0, 1.0), n_segments=(20, 200))), # convert images into their superpixel representation
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.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), # sharpen images
#iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # emboss images
# search either for all edges or for directed edges
#sometimes(iaa.OneOf([
# iaa.EdgeDetect(alpha=(0, 0.7)),
# iaa.DirectedEdgeDetect(alpha=(0, 0.7), direction=(0.0, 1.0)),
#])),
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # add gaussian noise to images
iaa.OneOf([
iaa.Dropout((0.01, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels
#iaa.CoarseDropout((0.03, 0.15), size_percent=(0.02, 0.05), per_channel=0.2),
]),
#iaa.Invert(0.05, per_channel=True), # invert color channels
iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)
iaa.Multiply((0.5, 1.5), per_channel=0.5), # change brightness of images (50-150% of original value)
iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast
#iaa.Grayscale(alpha=(0.0, 1.0)),
#sometimes(iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)), # move pixels locally around (with random strengths)
#sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05))) # sometimes move parts of the image around
],
random_order=True
)
],
random_order=True
)
return aug_pipe
示例12
def medium(image_iteration):
iteration = image_iteration/(120*1.5)
frequency_factor = 0.05 + float(iteration)/1000000.0
color_factor = float(iteration)/1000000.0
dropout_factor = 0.198667 + (0.03856658 - 0.198667) / (1 + (iteration / 196416.6) ** 1.863486)
blur_factor = 0.5 + (0.5*iteration/100000.0)
add_factor = 10 + 10*iteration/150000.0
multiply_factor_pos = 1 + (2.5*iteration/500000.0)
multiply_factor_neg = 1 - (0.91 * iteration / 500000.0)
contrast_factor_pos = 1 + (0.5*iteration/500000.0)
contrast_factor_neg = 1 - (0.5 * iteration / 500000.0)
#print 'Augment Status ',frequency_factor,color_factor,dropout_factor,blur_factor,add_factor,\
# multiply_factor_pos,multiply_factor_neg,contrast_factor_pos,contrast_factor_neg
augmenter = iaa.Sequential([
iaa.Sometimes(frequency_factor, iaa.GaussianBlur((0, blur_factor))),
# blur images with a sigma between 0 and 1.5
iaa.Sometimes(frequency_factor, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0,dropout_factor ),
per_channel=color_factor)),
# add gaussian noise to images
iaa.Sometimes(frequency_factor, iaa.CoarseDropout((0.0, dropout_factor), size_percent=(
0.08, 0.2), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor, iaa.Dropout((0.0, dropout_factor), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor,
iaa.Add((-add_factor, add_factor), per_channel=color_factor)),
# change brightness of images (by -X to Y of original value)
iaa.Sometimes(frequency_factor,
iaa.Multiply((multiply_factor_neg, multiply_factor_pos), per_channel=color_factor)),
# change brightness of images (X-Y% of original value)
iaa.Sometimes(frequency_factor, iaa.ContrastNormalization((contrast_factor_neg, contrast_factor_pos),
per_channel=color_factor)),
# improve or worsen the contrast
iaa.Sometimes(frequency_factor, iaa.Grayscale((0.0, 1))), # put grayscale
],
random_order=True # do all of the above in random order
)
return augmenter
示例13
def soft(image_iteration):
iteration = image_iteration/(120*1.5)
frequency_factor = 0.05 + float(iteration)/1200000.0
color_factor = float(iteration)/1200000.0
dropout_factor = 0.198667 + (0.03856658 - 0.198667) / (1 + (iteration / 196416.6) ** 1.863486)
blur_factor = 0.5 + (0.5*iteration/120000.0)
add_factor = 10 + 10*iteration/170000.0
multiply_factor_pos = 1 + (2.5*iteration/800000.0)
multiply_factor_neg = 1 - (0.91 * iteration / 800000.0)
contrast_factor_pos = 1 + (0.5*iteration/800000.0)
contrast_factor_neg = 1 - (0.5 * iteration / 800000.0)
#print ('iteration',iteration,'Augment Status ',frequency_factor,color_factor,dropout_factor,blur_factor,add_factor,
# multiply_factor_pos,multiply_factor_neg,contrast_factor_pos,contrast_factor_neg)
augmenter = iaa.Sequential([
iaa.Sometimes(frequency_factor, iaa.GaussianBlur((0, blur_factor))),
# blur images with a sigma between 0 and 1.5
iaa.Sometimes(frequency_factor, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0,dropout_factor ),
per_channel=color_factor)),
# add gaussian noise to images
iaa.Sometimes(frequency_factor, iaa.CoarseDropout((0.0, dropout_factor), size_percent=(
0.08, 0.2), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor, iaa.Dropout((0.0, dropout_factor), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor,
iaa.Add((-add_factor, add_factor), per_channel=color_factor)),
# change brightness of images (by -X to Y of original value)
iaa.Sometimes(frequency_factor,
iaa.Multiply((multiply_factor_neg, multiply_factor_pos), per_channel=color_factor)),
# change brightness of images (X-Y% of original value)
iaa.Sometimes(frequency_factor, iaa.ContrastNormalization((contrast_factor_neg, contrast_factor_pos),
per_channel=color_factor)),
# improve or worsen the contrast
iaa.Sometimes(frequency_factor, iaa.Grayscale((0.0, 1))), # put grayscale
],
random_order=True # do all of the above in random order
)
return augmenter
示例14
def high(image_iteration):
iteration = image_iteration/(120*1.5)
frequency_factor = 0.05 + float(iteration)/800000.0
color_factor = float(iteration)/800000.0
dropout_factor = 0.198667 + (0.03856658 - 0.198667) / (1 + (iteration / 196416.6) ** 1.863486)
blur_factor = 0.5 + (0.5*iteration/80000.0)
add_factor = 10 + 10*iteration/120000.0
multiply_factor_pos = 1 + (2.5*iteration/350000.0)
multiply_factor_neg = 1 - (0.91 * iteration / 400000.0)
contrast_factor_pos = 1 + (0.5*iteration/350000.0)
contrast_factor_neg = 1 - (0.5 * iteration / 400000.0)
#print ('iteration',iteration,'Augment Status ',frequency_factor,color_factor,dropout_factor,blur_factor,add_factor,
# multiply_factor_pos,multiply_factor_neg,contrast_factor_pos,contrast_factor_neg)
augmenter = iaa.Sequential([
iaa.Sometimes(frequency_factor, iaa.GaussianBlur((0, blur_factor))),
# blur images with a sigma between 0 and 1.5
iaa.Sometimes(frequency_factor, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0,dropout_factor ),
per_channel=color_factor)),
# add gaussian noise to images
iaa.Sometimes(frequency_factor, iaa.CoarseDropout((0.0, dropout_factor), size_percent=(
0.08, 0.2), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor, iaa.Dropout((0.0, dropout_factor), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor,
iaa.Add((-add_factor, add_factor), per_channel=color_factor)),
# change brightness of images (by -X to Y of original value)
iaa.Sometimes(frequency_factor,
iaa.Multiply((multiply_factor_neg, multiply_factor_pos), per_channel=color_factor)),
# change brightness of images (X-Y% of original value)
iaa.Sometimes(frequency_factor, iaa.ContrastNormalization((contrast_factor_neg, contrast_factor_pos),
per_channel=color_factor)),
# improve or worsen the contrast
iaa.Sometimes(frequency_factor, iaa.Grayscale((0.0, 1))), # put grayscale
],
random_order=True # do all of the above in random order
)
return augmenter
示例15
def medium_harder(image_iteration):
iteration = image_iteration / 120
frequency_factor = 0.05 + float(iteration)/1000000.0
color_factor = float(iteration)/1000000.0
dropout_factor = 0.198667 + (0.03856658 - 0.198667) / (1 + (iteration / 196416.6) ** 1.863486)
blur_factor = 0.5 + (0.5*iteration/100000.0)
add_factor = 10 + 10*iteration/150000.0
multiply_factor_pos = 1 + (2.5*iteration/500000.0)
multiply_factor_neg = 1 - (0.91 * iteration / 500000.0)
contrast_factor_pos = 1 + (0.5*iteration/500000.0)
contrast_factor_neg = 1 - (0.5 * iteration / 500000.0)
#print 'Augment Status ',frequency_factor,color_factor,dropout_factor,blur_factor,add_factor,\
# multiply_factor_pos,multiply_factor_neg,contrast_factor_pos,contrast_factor_neg
augmenter = iaa.Sequential([
iaa.Sometimes(frequency_factor, iaa.GaussianBlur((0, blur_factor))),
# blur images with a sigma between 0 and 1.5
iaa.Sometimes(frequency_factor, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0,dropout_factor ),
per_channel=color_factor)),
# add gaussian noise to images
iaa.Sometimes(frequency_factor, iaa.CoarseDropout((0.0, dropout_factor), size_percent=(
0.08, 0.2), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor, iaa.Dropout((0.0, dropout_factor), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor,
iaa.Add((-add_factor, add_factor), per_channel=color_factor)),
# change brightness of images (by -X to Y of original value)
iaa.Sometimes(frequency_factor,
iaa.Multiply((multiply_factor_neg, multiply_factor_pos), per_channel=color_factor)),
# change brightness of images (X-Y% of original value)
iaa.Sometimes(frequency_factor, iaa.ContrastNormalization((contrast_factor_neg, contrast_factor_pos),
per_channel=color_factor)),
# improve or worsen the contrast
iaa.Sometimes(frequency_factor, iaa.Grayscale((0.0, 1))), # put grayscale
],
random_order=True # do all of the above in random order
)
return augmenter
示例16
def hard_harder(image_iteration):
iteration = image_iteration / 120
frequency_factor = min(0.05 + float(iteration)/200000.0, 1.0)
color_factor = float(iteration)/1000000.0
dropout_factor = 0.198667 + (0.03856658 - 0.198667) / (1 + (iteration / 196416.6) ** 1.863486)
blur_factor = 0.5 + (0.5*iteration/100000.0)
add_factor = 10 + 10*iteration/100000.0
multiply_factor_pos = 1 + (2.5*iteration/200000.0)
multiply_factor_neg = 1 - (0.91 * iteration / 500000.0)
contrast_factor_pos = 1 + (0.5*iteration/500000.0)
contrast_factor_neg = 1 - (0.5 * iteration / 500000.0)
#print 'Augment Status ',frequency_factor,color_factor,dropout_factor,blur_factor,add_factor,\
# multiply_factor_pos,multiply_factor_neg,contrast_factor_pos,contrast_factor_neg
augmenter = iaa.Sequential([
iaa.Sometimes(frequency_factor, iaa.GaussianBlur((0, blur_factor))),
# blur images with a sigma between 0 and 1.5
iaa.Sometimes(frequency_factor, iaa.AdditiveGaussianNoise(loc=0, scale=(0.0,dropout_factor ),
per_channel=color_factor)),
# add gaussian noise to images
iaa.Sometimes(frequency_factor, iaa.CoarseDropout((0.0, dropout_factor), size_percent=(
0.08, 0.2), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor, iaa.Dropout((0.0, dropout_factor), per_channel=color_factor)),
# randomly remove up to X% of the pixels
iaa.Sometimes(frequency_factor,
iaa.Add((-add_factor, add_factor), per_channel=color_factor)),
# change brightness of images (by -X to Y of original value)
iaa.Sometimes(frequency_factor,
iaa.Multiply((multiply_factor_neg, multiply_factor_pos), per_channel=color_factor)),
# change brightness of images (X-Y% of original value)
iaa.Sometimes(frequency_factor, iaa.ContrastNormalization((contrast_factor_neg, contrast_factor_pos),
per_channel=color_factor)),
# improve or worsen the contrast
iaa.Sometimes(frequency_factor, iaa.Grayscale((0.0, 1))), # put grayscale
],
random_order=True # do all of the above in random order
)
return augmenter
示例17
def example_heavy_augmentations():
print("Example: Heavy Augmentations")
import imgaug as ia
from imgaug import augmenters as iaa
# random example images
images = np.random.randint(0, 255, (16, 128, 128, 3), dtype=np.uint8)
# 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.
st = 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([
iaa.Fliplr(0.5), # horizontally flip 50% of all images
iaa.Flipud(0.5), # vertically flip 50% of all images
st(iaa.Crop(percent=(0, 0.1))), # crop images by 0-10% of their height/width
st(iaa.GaussianBlur((0, 3.0))), # blur images with a sigma between 0 and 3.0
st(iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5)), # add gaussian noise to images
st(iaa.Dropout((0.0, 0.1), per_channel=0.5)), # randomly remove up to 10% of the pixels
st(iaa.Add((-10, 10), per_channel=0.5)), # change brightness of images (by -10 to 10 of original value)
st(iaa.Multiply((0.5, 1.5), per_channel=0.5)), # change brightness of images (50-150% of original value)
st(iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5)), # improve or worsen the contrast
st(iaa.Grayscale((0.0, 1.0))), # blend with grayscale image
st(iaa.Affine(
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis
translate_px={"x": (-16, 16), "y": (-16, 16)}, # translate by -16 to +16 pixels (per axis)
rotate=(-45, 45), # rotate by -45 to +45 degrees
shear=(-16, 16), # shear by -16 to +16 degrees
order=[0, 1], # use scikit-image's interpolation orders 0 (nearest neighbour) and 1 (bilinear)
cval=(0, 255), # if mode is constant, use a cval between 0 and 1.0
mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)
)),
st(iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)) # apply elastic transformations with random strengths
],
random_order=True # do all of the above in random order
)
images_aug = seq.augment_images(images)
# -----
# Make sure that the example really does something
assert not np.array_equal(images, images_aug)
示例18
def main():
args = parse_args()
package_versions = get_package_versions()
if args.print_package_versions:
print(package_versions)
images_per_second = defaultdict(dict)
libraries = args.libraries
data_dir = args.data_dir
paths = list(sorted(os.listdir(data_dir)))
paths = paths[: args.images]
imgs_cv2 = [read_img_cv2(os.path.join(data_dir, path)) for path in paths]
imgs_pillow = [read_img_pillow(os.path.join(data_dir, path)) for path in paths]
benchmarks = [
HorizontalFlip(),
VerticalFlip(),
Rotate(),
ShiftScaleRotate(),
Brightness(),
Contrast(),
BrightnessContrast(),
ShiftRGB(),
ShiftHSV(),
Gamma(),
Grayscale(),
RandomCrop64(),
PadToSize512(),
Resize512(),
RandomSizedCrop_64_512(),
Posterize(),
Solarize(),
Equalize(),
Multiply(),
MultiplyElementwise(),
]
for library in libraries:
imgs = imgs_pillow if library in ("torchvision", "augmentor", "pillow") else imgs_cv2
pbar = tqdm(total=len(benchmarks))
for benchmark in benchmarks:
pbar.set_description("Current benchmark: {} | {}".format(library, benchmark))
benchmark_images_per_second = None
if benchmark.is_supported_by(library):
timer = Timer(lambda: benchmark.run(library, imgs))
run_times = timer.repeat(number=1, repeat=args.runs)
benchmark_images_per_second = [1 / (run_time / args.images) for run_time in run_times]
images_per_second[library][str(benchmark)] = benchmark_images_per_second
pbar.update(1)
pbar.close()
pd.set_option("display.width", 1000)
df = pd.DataFrame.from_dict(images_per_second)
df = df.applymap(lambda r: format_results(r, args.show_std))
df = df[libraries]
augmentations = [str(i) for i in benchmarks]
df = df.reindex(augmentations)
if args.markdown:
makedown_generator = MarkdownGenerator(df, package_versions)
makedown_generator.print()
else:
print(df.head(len(augmentations)))