forked from aleju/imgaug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_documentation_images.py
3186 lines (2713 loc) · 103 KB
/
generate_documentation_images.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, division
import imgaug as ia
from imgaug import augmenters as iaa
from imgaug import parameters as iap
import numpy as np
import imageio
#from skimage import data
#import matplotlib.pyplot as plt
#from matplotlib import gridspec
#import six
#import six.moves as sm
import os
import PIL.Image
import math
from skimage import data
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
DOCS_IMAGES_BASE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"docs",
"images"
)
PARAMETERS_DEFAULT_SIZE = (350, 350)
PARAMETER_DEFAULT_QUALITY = 25
def main():
chapter_examples_basics()
chapter_examples_keypoints()
chapter_examples_bounding_boxes()
chapter_examples_heatmaps()
chapter_examples_segmentation_maps()
chapter_augmenters()
chapter_parameters()
chapter_alpha()
def save(chapter_dir, filename, image, quality=None):
dir_fp = os.path.join(DOCS_IMAGES_BASE_PATH, chapter_dir)
if not os.path.exists(dir_fp):
os.makedirs(dir_fp)
file_fp = os.path.join(dir_fp, filename)
image_jpg = compress_to_jpg(image, quality=quality)
image_jpg_decompressed = decompress_jpg(image_jpg)
# If the image file already exists and is (practically) identical,
# then don't save it again to avoid polluting the repository with tons
# of image updates.
# Not that we have to compare here the results AFTER jpg compression
# and then decompression. Otherwise we compare two images of which
# image (1) has never been compressed while image (2) was compressed and
# then decompressed.
if os.path.isfile(file_fp):
image_saved = imageio.imread(file_fp, pilmode="RGB")
#print("arrdiff", arrdiff(image_jpg_decompressed, image_saved))
same_shape = (image_jpg_decompressed.shape == image_saved.shape)
d_avg = arrdiff(image_jpg_decompressed, image_saved) if same_shape else -1
if same_shape and d_avg <= 1.0:
print("[INFO] Did not save image '%s/%s', because the already saved image is basically identical (d_avg=%.4f)" % (chapter_dir, filename, d_avg,))
return
with open(file_fp, "w") as f:
f.write(image_jpg)
def arrdiff(arr1, arr2):
nb_cells = np.prod(arr2.shape)
d_avg = np.sum(np.power(np.abs(arr1 - arr2), 2)) / nb_cells
return d_avg
def compress_to_jpg(image, quality=75):
quality = quality if quality is not None else 75
im = PIL.Image.fromarray(image)
out = BytesIO()
im.save(out, format="JPEG", quality=quality)
jpg_string = out.getvalue()
out.close()
return jpg_string
def decompress_jpg(image_compressed):
img_compressed_buffer = BytesIO()
img_compressed_buffer.write(image_compressed)
img = imageio.imread(img_compressed_buffer.getvalue(), pilmode="RGB", format="jpg")
img_compressed_buffer.close()
return img
def grid(images, rows, cols, border=1, border_color=255):
nb_images = len(images)
cell_height = max([image.shape[0] for image in images])
cell_width = max([image.shape[1] for image in images])
channels = set([image.shape[2] for image in images])
assert len(channels) == 1
nb_channels = list(channels)[0]
if rows is None and cols is None:
rows = cols = int(math.ceil(math.sqrt(nb_images)))
elif rows is not None:
cols = int(math.ceil(nb_images / rows))
elif cols is not None:
rows = int(math.ceil(nb_images / cols))
assert rows * cols >= nb_images
cell_height = cell_height + 1 * border
cell_width = cell_width + 1 * border
width = cell_width * cols
height = cell_height * rows
grid = np.zeros((height, width, nb_channels), dtype=np.uint8)
cell_idx = 0
for row_idx in range(rows):
for col_idx in range(cols):
if cell_idx < nb_images:
image = images[cell_idx]
border_top = border_right = border_bottom = border_left = border
#if row_idx > 1:
border_top = 0
#if col_idx > 1:
border_left = 0
image = np.pad(image, ((border_top, border_bottom), (border_left, border_right), (0, 0)), mode="constant", constant_values=border_color)
cell_y1 = cell_height * row_idx
cell_y2 = cell_y1 + image.shape[0]
cell_x1 = cell_width * col_idx
cell_x2 = cell_x1 + image.shape[1]
grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image
cell_idx += 1
grid = np.pad(grid, ((border, 0), (border, 0), (0, 0)), mode="constant", constant_values=border_color)
return grid
def checkerboard(size):
img = data.checkerboard()
img3d = np.tile(img[..., np.newaxis], (1, 1, 3))
return ia.imresize_single_image(img3d, size)
###############################
# Examples: Basics
###############################
def chapter_examples_basics():
"""Generate all example images for the chapter `Examples: Basics`
in the documentation."""
chapter_examples_basics_simple()
chapter_examples_basics_heavy()
def chapter_examples_basics_simple():
import imgaug as ia
from imgaug import augmenters as iaa
# Example batch of images.
# The array has shape (32, 64, 64, 3) and dtype uint8.
images = np.array(
[ia.quokka(size=(64, 64)) for _ in range(32)],
dtype=np.uint8
)
seq = iaa.Sequential([
iaa.Fliplr(0.5), # horizontal flips
iaa.Crop(percent=(0, 0.1)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all images.
iaa.Sometimes(0.5,
iaa.GaussianBlur(sigma=(0, 0.5))
),
# Strengthen or weaken the contrast in each image.
iaa.ContrastNormalization((0.75, 1.5)),
# Add gaussian noise.
# For 50% of all images, we sample the noise once per pixel.
# For the other 50% of all images, we sample the noise per pixel AND
# channel. This can change the color (not only brightness) of the
# pixels.
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5),
# Make some images brighter and some darker.
# In 20% of all cases, we sample the multiplier once per channel,
# which can end up changing the color of the images.
iaa.Multiply((0.8, 1.2), per_channel=0.2),
# Apply affine transformations to each image.
# Scale/zoom them, translate/move them, rotate them and shear them.
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=(-25, 25),
shear=(-8, 8)
)
], random_order=True) # apply augmenters in random order
ia.seed(1)
images_aug = seq.augment_images(images)
# ------------
save(
"examples_basics",
"simple.jpg",
grid(images_aug, cols=8, rows=4)
)
def chapter_examples_basics_heavy():
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
# Example batch of images.
# The array has shape (32, 64, 64, 3) and dtype uint8.
images = np.array(
[ia.quokka(size=(64, 64)) for _ in range(32)],
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.
sometimes = lambda aug: iaa.Sometimes(0.5, aug)
# Define our sequence of augmentation steps that will be applied to every image.
seq = 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
# crop some of the images by 0-10% of their height/width
sometimes(iaa.Crop(percent=(0, 0.1))),
# Apply affine transformations to some of the images
# - scale to 80-120% of image height/width (each axis independently)
# - translate by -20 to +20 relative to height/width (per axis)
# - rotate by -45 to +45 degrees
# - shear by -16 to +16 degrees
# - order: use nearest neighbour or bilinear interpolation (fast)
# - mode: use any available mode to fill newly created pixels
# see API or scikit-image for which modes are available
# - cval: if the mode is constant, then use a random brightness
# for the newly created pixels (e.g. sometimes black,
# sometimes white)
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=(-45, 45),
shear=(-16, 16),
order=[0, 1],
cval=(0, 255),
mode=ia.ALL
)),
#
# 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),
[
# Convert some images into their superpixel representation,
# sample between 20 and 200 superpixels per image, but do
# not replace all superpixels with their average, only
# some of them (p_replace).
sometimes(
iaa.Superpixels(
p_replace=(0, 1.0),
n_segments=(20, 200)
)
),
# Blur each image with varying strength using
# gaussian blur (sigma between 0 and 3.0),
# average/uniform blur (kernel size between 2x2 and 7x7)
# median blur (kernel size between 3x3 and 11x11).
iaa.OneOf([
iaa.GaussianBlur((0, 3.0)),
iaa.AverageBlur(k=(2, 7)),
iaa.MedianBlur(k=(3, 11)),
]),
# Sharpen each image, overlay the result with the original
# image using an alpha between 0 (no sharpening) and 1
# (full sharpening effect).
iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),
# Same as sharpen, but for an embossing effect.
iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),
# Search in some images either for all edges or for
# directed edges. These edges are then marked in a black
# and white image and overlayed with the original image
# using an alpha of 0 to 0.7.
sometimes(iaa.OneOf([
iaa.EdgeDetect(alpha=(0, 0.7)),
iaa.DirectedEdgeDetect(
alpha=(0, 0.7), direction=(0.0, 1.0)
),
])),
# Add gaussian noise to some images.
# In 50% of these cases, the noise is randomly sampled per
# channel and pixel.
# In the other 50% of all cases it is sampled once per
# pixel (i.e. brightness change).
iaa.AdditiveGaussianNoise(
loc=0, scale=(0.0, 0.05*255), per_channel=0.5
),
# Either drop randomly 1 to 10% of all pixels (i.e. set
# them to black) or drop them on an image with 2-5% percent
# of the original size, leading to large dropped
# rectangles.
iaa.OneOf([
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
),
]),
# Invert each image's chanell with 5% probability.
# This sets each pixel value v to 255-v.
iaa.Invert(0.05, per_channel=True), # invert color channels
# Add a value of -10 to 10 to each pixel.
iaa.Add((-10, 10), per_channel=0.5),
# Change brightness of images (50-150% of original value).
iaa.Multiply((0.5, 1.5), per_channel=0.5),
# Improve or worsen the contrast of images.
iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),
# Convert each image to grayscale and then overlay the
# result with the original with random alpha. I.e. remove
# colors with varying strengths.
iaa.Grayscale(alpha=(0.0, 1.0)),
# In some images move pixels locally around (with random
# strengths).
sometimes(
iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)
),
# In some images distort local areas with varying strength.
sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05)))
],
# do all of the above augmentations in random order
random_order=True
)
],
# do all of the above augmentations in random order
random_order=True
)
ia.seed(1)
images_aug = seq.augment_images(images)
# ------------
save(
"examples_basics",
"heavy.jpg",
grid(images_aug, cols=8, rows=4)
)
###############################
# Examples: Keypoints
###############################
def chapter_examples_keypoints():
"""Generate all example images for the chapter `Examples: Keypoints`
in the documentation."""
chapter_examples_keypoints_simple()
def chapter_examples_keypoints_simple():
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(1)
image = ia.quokka(size=(256, 256))
keypoints = ia.KeypointsOnImage([
ia.Keypoint(x=65, y=100),
ia.Keypoint(x=75, y=200),
ia.Keypoint(x=100, y=100),
ia.Keypoint(x=200, y=80)
], shape=image.shape)
seq = iaa.Sequential([
iaa.Multiply((1.2, 1.5)), # change brightness, doesn't affect keypoints
iaa.Affine(
rotate=10,
scale=(0.5, 0.7)
) # rotate by exactly 10deg and scale to 50-70%, affects keypoints
])
# Make our sequence deterministic.
# We can now apply it to the image and then to the keypoints and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the
# exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
# augment keypoints and images
image_aug = seq_det.augment_images([image])[0]
keypoints_aug = seq_det.augment_keypoints([keypoints])[0]
# print coordinates before/after augmentation (see below)
for i in range(len(keypoints.keypoints)):
before = keypoints.keypoints[i]
after = keypoints_aug.keypoints[i]
print("Keypoint %d: (%d, %d) -> (%d, %d)" % (
i, before.x, before.y, after.x, after.y)
)
# image with keypoints before/after augmentation (shown below)
image_before = keypoints.draw_on_image(image, size=7)
image_after = keypoints_aug.draw_on_image(image_aug, size=7)
# ------------
save(
"examples_keypoints",
"simple.jpg",
grid([image_before, image_after], cols=2, rows=1),
quality=90
)
###############################
# Examples: Bounding Boxes
###############################
def chapter_examples_bounding_boxes():
"""Generate all example images for the chapter `Examples: Bounding Boxes`
in the documentation."""
chapter_examples_bounding_boxes_simple()
chapter_examples_bounding_boxes_rotation()
chapter_examples_bounding_boxes_ooi()
chapter_examples_bounding_boxes_shift()
chapter_examples_bounding_boxes_projection()
chapter_examples_bounding_boxes_iou()
def chapter_examples_bounding_boxes_simple():
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(1)
image = ia.quokka(size=(256, 256))
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=65, y1=100, x2=200, y2=150),
ia.BoundingBox(x1=150, y1=80, x2=200, y2=130)
], shape=image.shape)
seq = iaa.Sequential([
iaa.Multiply((1.2, 1.5)), # change brightness, doesn't affect BBs
iaa.Affine(
translate_px={"x": 40, "y": 60},
scale=(0.5, 0.7)
) # translate by 40/60px on x/y axis, and scale to 50-70%, affects BBs
])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the
# exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the
# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([image])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
# print coordinates before/after augmentation (see below)
for i in range(len(bbs.bounding_boxes)):
before = bbs.bounding_boxes[i]
after = bbs_aug.bounding_boxes[i]
print("BB %d: (%d, %d, %d, %d) -> (%d, %d, %d, %d)" % (
i,
before.x1, before.y1, before.x2, before.y2,
after.x1, after.y1, after.x2, after.y2)
)
# image with BBs before/after augmentation (shown below)
image_before = bbs.draw_on_image(image, thickness=2)
image_after = bbs_aug.draw_on_image(image_aug, thickness=2, color=[0, 0, 255])
# ------------
save(
"examples_bounding_boxes",
"simple.jpg",
grid([image_before, image_after], cols=2, rows=1),
quality=75
)
def chapter_examples_bounding_boxes_rotation():
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(1)
image = ia.quokka(size=(256, 256))
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=65, y1=100, x2=200, y2=150),
ia.BoundingBox(x1=150, y1=80, x2=200, y2=130)
], shape=image.shape)
seq = iaa.Sequential([
iaa.Multiply((1.2, 1.5)), # change brightness, doesn't affect BBs
iaa.Affine(
rotate=45,
)
])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the
# exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the
# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([image])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
# print coordinates before/after augmentation (see below)
for i in range(len(bbs.bounding_boxes)):
before = bbs.bounding_boxes[i]
after = bbs_aug.bounding_boxes[i]
print("BB %d: (%d, %d, %d, %d) -> (%d, %d, %d, %d)" % (
i,
before.x1, before.y1, before.x2, before.y2,
after.x1, after.y1, after.x2, after.y2)
)
# image with BBs before/after augmentation (shown below)
image_before = bbs.draw_on_image(image, thickness=2)
image_after = bbs_aug.draw_on_image(image_aug, thickness=2, color=[0, 0, 255])
# ------------
save(
"examples_bounding_boxes",
"rotation.jpg",
grid([image_before, image_after], cols=2, rows=1),
quality=75
)
def chapter_examples_bounding_boxes_ooi():
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
ia.seed(1)
GREEN = [0, 255, 0]
ORANGE = [255, 140, 0]
RED = [255, 0, 0]
# Pad image with a 1px white and (BY-1)px black border
def pad(image, by):
if by <= 0:
return image
image_border1 = np.pad(
image, ((1, 1), (1, 1), (0, 0)),
mode="constant", constant_values=255
)
image_border2 = np.pad(
image_border1, ((by-1, by-1), (by-1, by-1), (0, 0)),
mode="constant", constant_values=0
)
return image_border2
# Draw BBs on an image
# and before doing that, extend the image plane by BORDER pixels.
# Mark BBs inside the image plane with green color, those partially inside
# with orange and those fully outside with red.
def draw_bbs(image, bbs, border):
image_border = pad(image, border)
for bb in bbs.bounding_boxes:
if bb.is_fully_within_image(image.shape):
color = GREEN
elif bb.is_partly_within_image(image.shape):
color = ORANGE
else:
color = RED
image_border = bb.shift(left=border, top=border)\
.draw_on_image(image_border, thickness=2, color=color)
return image_border
# Define example image with three small square BBs next to each other.
# Augment these BBs by shifting them to the right.
image = ia.quokka(size=(256, 256))
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=25, x2=75, y1=25, y2=75),
ia.BoundingBox(x1=100, x2=150, y1=25, y2=75),
ia.BoundingBox(x1=175, x2=225, y1=25, y2=75)
], shape=image.shape)
seq = iaa.Affine(translate_px={"x": 120})
seq_det = seq.to_deterministic()
image_aug = seq_det.augment_images([image])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
# Draw the BBs (a) in their original form, (b) after augmentation,
# (c) after augmentation and removing those fully outside the image,
# (d) after augmentation and removing those fully outside the image and
# cutting those partially inside the image so that they are fully inside.
image_before = draw_bbs(image, bbs, 100)
image_after1 = draw_bbs(image_aug, bbs_aug, 100)
image_after2 = draw_bbs(image_aug, bbs_aug.remove_out_of_image(), 100)
image_after3 = draw_bbs(image_aug, bbs_aug.remove_out_of_image().cut_out_of_image(), 100)
# ------------
save(
"examples_bounding_boxes",
"ooi.jpg",
grid([image_before, image_after1, np.zeros_like(image_before), image_after2, np.zeros_like(image_before), image_after3], cols=2, rows=3),
#grid([image_before, image_after1], cols=2, rows=1),
quality=75
)
def chapter_examples_bounding_boxes_shift():
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(1)
# Define image and two bounding boxes
image = ia.quokka(size=(256, 256))
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=25, x2=75, y1=25, y2=75),
ia.BoundingBox(x1=100, x2=150, y1=25, y2=75)
], shape=image.shape)
# Move both BBs 25px to the right and the second BB 25px down
bbs_shifted = bbs.shift(left=25)
bbs_shifted.bounding_boxes[1] = bbs_shifted.bounding_boxes[1].shift(top=25)
# Draw images before/after moving BBs
image = bbs.draw_on_image(image, color=[0, 255, 0], thickness=2, alpha=0.75)
image = bbs_shifted.draw_on_image(image, color=[0, 0, 255], thickness=2, alpha=0.75)
# ------------
save(
"examples_bounding_boxes",
"shift.jpg",
grid([image], cols=1, rows=1),
quality=75
)
def chapter_examples_bounding_boxes_projection():
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(1)
# Define image with two bounding boxes
image = ia.quokka(size=(256, 256))
bbs = ia.BoundingBoxesOnImage([
ia.BoundingBox(x1=25, x2=75, y1=25, y2=75),
ia.BoundingBox(x1=100, x2=150, y1=25, y2=75)
], shape=image.shape)
# Rescale image and bounding boxes
image_rescaled = ia.imresize_single_image(image, (512, 512))
bbs_rescaled = bbs.on(image_rescaled)
# Draw image before/after rescaling and with rescaled bounding boxes
image_bbs = bbs.draw_on_image(image, thickness=2)
image_rescaled_bbs = bbs_rescaled.draw_on_image(image_rescaled, thickness=2)
# ------------
save(
"examples_bounding_boxes",
"projection.jpg",
grid([image_bbs, image_rescaled_bbs], cols=2, rows=1),
quality=75
)
def chapter_examples_bounding_boxes_iou():
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
ia.seed(1)
# Define image with two bounding boxes.
image = ia.quokka(size=(256, 256))
bb1 = ia.BoundingBox(x1=50, x2=100, y1=25, y2=75)
bb2 = ia.BoundingBox(x1=75, x2=125, y1=50, y2=100)
# Compute intersection, union and IoU value
# Intersection and union are both bounding boxes. They are here
# decreased/increased in size purely for better visualization.
bb_inters = bb1.intersection(bb2).extend(all_sides=-1)
bb_union = bb1.union(bb2).extend(all_sides=2)
iou = bb1.iou(bb2)
# Draw bounding boxes, intersection, union and IoU value on image.
image_bbs = np.copy(image)
image_bbs = bb1.draw_on_image(image_bbs, thickness=2, color=[0, 255, 0])
image_bbs = bb2.draw_on_image(image_bbs, thickness=2, color=[0, 255, 0])
image_bbs = bb_inters.draw_on_image(image_bbs, thickness=2, color=[255, 0, 0])
image_bbs = bb_union.draw_on_image(image_bbs, thickness=2, color=[0, 0, 255])
image_bbs = ia.draw_text(
image_bbs, text="IoU=%.2f" % (iou,),
x=bb_union.x2+10, y=bb_union.y1+bb_union.height//2,
color=[255, 255, 255], size=13
)
# ------------
save(
"examples_bounding_boxes",
"iou.jpg",
grid([image_bbs], cols=1, rows=1),
quality=75
)
###############################
# Examples: Heatmaps
###############################
def chapter_examples_heatmaps():
"""Generate all example images for the chapter `Examples: Heatmaps`
in the documentation."""
chapter_examples_heatmaps_simple()
chapter_examples_heatmaps_multiple_small()
chapter_examples_heatmaps_arr_small()
chapter_examples_heatmaps_scaling()
chapter_examples_heatmaps_padding()
def chapter_examples_heatmaps_simple():
import imgaug as ia
from imgaug import augmenters as iaa
import imageio
import numpy as np
ia.seed(1)
# Load an example image (uint8, 128x128x3).
image = ia.quokka(size=(128, 128), extract="square")
# Create an example depth map (float32, 128x128).
# Here, we use a simple gradient that has low values (around 0.0) towards the left of the image
# and high values (around 50.0) towards the right. This is obviously a very unrealistic depth
# map, but makes the example easier.
heatmap = np.linspace(0, 50, 128).astype(np.float32) # 128 values from 0.0 to 50.0
heatmap = np.tile(heatmap.reshape(1, 128), (128, 1)) # change to a horizontal gradient
# We add a cross to the center of the depth map, so that we can more easily see the
# effects of augmentations.
heatmap[64-2:64+2, 16:128-16] = 0.75 * 50.0 # line from left to right
heatmap[16:128-16, 64-2:64+2] = 1.0 * 50.0 # line from top to bottom
# Convert our numpy array depth map to a heatmap object.
# We have to add the shape of the underlying image, as that is necessary for some
# augmentations.
heatmap = ia.HeatmapsOnImage(heatmap, shape=image.shape, min_value=0.0, max_value=50.0)
# To save some computation time, we want our models to perform downscaling and
# hence need the ground truth depth maps to be at a resolution of 64x64 instead of
# the 128x128 of the input image.
# Here, we use simple average pooling to perform the downscaling.
heatmap = heatmap.avg_pool(2)
# Define our augmentation pipeline.
seq = iaa.Sequential([
iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels
iaa.Sharpen((0.0, 1.0)), # sharpen the image
iaa.Affine(rotate=(-45, 45)), # rotate by -45 to 45 degrees (affects heatmaps)
iaa.ElasticTransformation(alpha=50, sigma=5) # apply water effect (affects heatmaps)
], random_order=True)
# Augment images and heatmaps.
images_aug = []
heatmaps_aug = []
for _ in range(5):
seq_det = seq.to_deterministic()
images_aug.append(seq_det.augment_image(image))
heatmaps_aug.append(seq_det.augment_heatmaps([heatmap])[0])
# We want to generate an image of original input images and heatmaps before/after augmentation.
# It is supposed to have five columns: (1) original image, (2) augmented image,
# (3) augmented heatmap on top of augmented image, (4) augmented heatmap on its own in jet
# color map, (5) augmented heatmap on its own in intensity colormap,
# We now generate the cells of these columns.
#
# Note that we add a [0] after each heatmap draw command. That's because the heatmaps object
# can contain many sub-heatmaps and hence we draw command returns a list of drawn sub-heatmaps.
# We only used one sub-heatmap, so our lists always have one entry.
cells = []
for image_aug, heatmap_aug in zip(images_aug, heatmaps_aug):
cells.append(image) # column 1
cells.append(image_aug) # column 2
cells.append(heatmap_aug.draw_on_image(image_aug)[0]) # column 3
cells.append(heatmap_aug.draw(size=image_aug.shape[:2])[0]) # column 4
cells.append(heatmap_aug.draw(size=image_aug.shape[:2], cmap=None)[0]) # column 5
# Convert cells to grid image and save.
grid_image = ia.draw_grid(cells, cols=5)
#imageio.imwrite("example_heatmaps.jpg", grid_image)
save(
"examples_heatmaps",
"simple.jpg",
grid_image,
quality=75
)
def chapter_examples_heatmaps_multiple_full():
import imgaug as ia
from imgaug import augmenters as iaa
import imageio
import numpy as np
ia.seed(1)
# Load an image and generate a heatmap array with three sub-heatmaps.
# Each sub-heatmap contains just three horizontal lines, with one of them having a higher
# value (1.0) than the other two (0.2).
image = ia.quokka(size=(128, 128), extract="square")
heatmap = np.zeros((128, 128, 3), dtype=np.float32)
for i in range(3):
heatmap[1*30-5:1*30+5, 10:-10, i] = 1.0 if i == 0 else 0.5
heatmap[2*30-5:2*30+5, 10:-10, i] = 1.0 if i == 1 else 0.5
heatmap[3*30-5:3*30+5, 10:-10, i] = 1.0 if i == 2 else 0.5
# Convert heatmap array to heatmap object.
heatmap = ia.HeatmapsOnImage(heatmap, shape=image.shape)
# Define our augmentation pipeline.
seq = iaa.Sequential([
iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels
iaa.Sharpen((0.0, 1.0)), # sharpen the image
iaa.Affine(rotate=(-45, 45)), # rotate by -45 to 45 degrees (affects heatmaps)
iaa.ElasticTransformation(alpha=50, sigma=5) # apply water effect (affects heatmaps)
], random_order=True)
# Augment images and heatmaps.
images_aug = []
heatmaps_aug = []
for _ in range(5):
seq_det = seq.to_deterministic()
images_aug.append(seq_det.augment_image(image))
heatmaps_aug.append(seq_det.augment_heatmaps([heatmap])[0])
# We want to generate an image of inputs before/after augmentation.
# It is supposed to have five columns: (1) original image, (2) augmented image,
# (3) augmented heatmap on top of augmented image, (4) augmented heatmap on its own in jet
# color map, (5) augmented heatmap on its own in intensity colormap,
# We now generate the cells of these columns.
cells = []
for image_aug, heatmap_aug in zip(images_aug, heatmaps_aug):
subheatmaps_drawn = heatmap_aug.draw_on_image(image_aug)
cells.append(image) # column 1
cells.append(image_aug) # column 2
cells.append(subheatmaps_drawn[0]) # column 3
cells.append(subheatmaps_drawn[1]) # column 4
cells.append(subheatmaps_drawn[2]) # column 5
# Convert cells to grid image and save.
grid_image = ia.draw_grid(cells, cols=5)
#imageio.imwrite("example_multiple_heatmaps.jpg", grid_image)
save(
"examples_heatmaps",
"multiple_full.jpg",
grid_image,
quality=75
)
def chapter_examples_heatmaps_multiple_small():
import imgaug as ia
import imageio
import numpy as np
# Load an image and generate a heatmap array with three sub-heatmaps.
# Each sub-heatmap contains just three horizontal lines, with one of them having a higher
# value (1.0) than the other two (0.2).
image = ia.quokka(size=(128, 128), extract="square")
heatmap = np.zeros((128, 128, 3), dtype=np.float32)
for i in range(3):
heatmap[1*30-5:1*30+5, 10:-10, i] = 1.0 if i == 0 else 0.5
heatmap[2*30-5:2*30+5, 10:-10, i] = 1.0 if i == 1 else 0.5
heatmap[3*30-5:3*30+5, 10:-10, i] = 1.0 if i == 2 else 0.5
heatmap = ia.HeatmapsOnImage(heatmap, shape=image.shape)
# Draw image and the three sub-heatmaps on it.
# We draw four columns: (1) image, (2-4) heatmaps one to three drawn on top of the image.
subheatmaps_drawn = heatmap.draw_on_image(image)
cells = [image, subheatmaps_drawn[0], subheatmaps_drawn[1], subheatmaps_drawn[2]]
grid_image = np.hstack(cells) # Horizontally stack the images
#imageio.imwrite("example_multiple_heatmaps.jpg", grid_image)
save(
"examples_heatmaps",
"multiple_small.jpg",
grid_image,
quality=75
)
def chapter_examples_heatmaps_arr_full():
import imgaug as ia
from imgaug import augmenters as iaa
import imageio
import numpy as np
ia.seed(1)
# Load an image and generate a heatmap array with three sub-heatmaps.
# Each sub-heatmap contains just three horizontal lines, with one of them having a higher
# value (1.0) than the other two (0.2).
image = ia.quokka(size=(128, 128), extract="square")
heatmap = np.zeros((128, 128, 1), dtype=np.float32)
heatmap[64-4:64+4, 10:-10, 0] = 1.0
# Convert heatmap array to heatmap object.
heatmap = ia.HeatmapsOnImage(heatmap, shape=image.shape)
# Define our augmentation pipeline.
seq = iaa.Sequential([
iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels
iaa.Sharpen((0.0, 1.0)), # sharpen the image
iaa.Affine(rotate=(-45, 45)), # rotate by -45 to 45 degrees (affects heatmaps)
iaa.ElasticTransformation(alpha=50, sigma=5) # apply water effect (affects heatmaps)
], random_order=True)
# Augment images and heatmaps.
images_aug = []
heatmaps_aug = []
for _ in range(5):
seq_det = seq.to_deterministic()
images_aug.append(seq_det.augment_image(image))
heatmaps_aug.append(seq_det.augment_heatmaps([heatmap])[0])
# We want to generate an image of inputs before/after augmentation.
# It is supposed to have five columns: (1) original image, (2) augmented image,
# (3) augmented heatmap on top of augmented image, (4) augmented heatmap on top of augmented
# image with a vertical line added to the heatmap *after* augmentation.
# We now generate the cells of these columns.
cells = []
for image_aug, heatmap_aug in zip(images_aug, heatmaps_aug):
arr = heatmap_aug.get_arr() # float32, shape (128, 128, 1)
arr[10:-10, 64-4:64+4] = 0.5
arr_heatmap = ia.HeatmapsOnImage(arr, shape=image_aug.shape)
cells.append(image) # column 1
cells.append(image_aug) # column 2
cells.append(heatmap_aug.draw_on_image(image_aug)[0]) # column 3
cells.append(arr_heatmap.draw_on_image(image_aug)[0]) # column 4
# Convert cells to grid image and save.
grid_image = ia.draw_grid(cells, cols=4)
#imageio.imwrite("example_heatmaps_arr.jpg", grid_image)
save(
"examples_heatmaps",
"arr_full.jpg",
grid_image,
quality=75
)
def chapter_examples_heatmaps_arr_small():
import imgaug as ia
import imageio
import numpy as np
# Load an image and generate a heatmap array containing one horizontal line.
image = ia.quokka(size=(128, 128), extract="square")
heatmap = np.zeros((128, 128, 1), dtype=np.float32)
heatmap[64-4:64+4, 10:-10, 0] = 1.0
heatmap1 = ia.HeatmapsOnImage(heatmap, shape=image.shape)
# Extract the heatmap array from the heatmap object, change it and create a second heatmap.
arr = heatmap1.get_arr()
arr[10:-10, 64-4:64+4] = 0.5
heatmap2 = ia.HeatmapsOnImage(arr, shape=image.shape)
# Draw image and heatmaps before/after changing the array.
# We draw three columns: (1) original image, (2) heatmap drawn on image, (3) heatmap drawn
# on image with some changes made to the heatmap array.
cells = [image, heatmap1.draw_on_image(image)[0], heatmap2.draw_on_image(image)[0]]
grid_image = np.hstack(cells) # Horizontally stack the images
#imageio.imwrite("example_heatmaps_arr.jpg", grid_image)