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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
#  Copyright Université de Rouen Normandie (1), INSA Rouen (2),
#  tutelles du laboratoire LITIS (1 et 2)
#  contributors :
#  - Denis Coquenet
#
#
#  This software is a computer program written in XXX whose purpose is XXX.
#
#  This software is governed by the CeCILL-C license under French law and
#  abiding by the rules of distribution of free software.  You can  use,
#  modify and/ or redistribute the software under the terms of the CeCILL-C
#  license as circulated by CEA, CNRS and INRIA at the following URL
#  "http://www.cecill.info".
#
#  As a counterpart to the access to the source code and  rights to copy,
#  modify and redistribute granted by the license, users are provided only
#  with a limited warranty  and the software's author,  the holder of the
#  economic rights,  and the successive licensors  have only  limited
#  liability.
#
#  In this respect, the user's attention is drawn to the risks associated
#  with loading,  using,  modifying and/or developing or reproducing the
#  software by the user in light of its specific status of free software,
#  that may mean  that it is complicated to manipulate,  and  that  also
#  therefore means  that it is reserved for developers  and  experienced
#  professionals having in-depth computer knowledge. Users are therefore
#  encouraged to load and test the software's suitability as regards their
#  requirements in conditions enabling the security of their systems and/or
#  data to be ensured and,  more generally, to use and operate it in the
#  same conditions as regards security.
#
#  The fact that you are presently reading this means that you have had
#  knowledge of the CeCILL-C license and that you accept its terms.

import numpy as np
from numpy import random
from PIL import Image
from cv2 import erode, dilate, normalize
import cv2
import math
from core.utils import randint, rand_uniform, rand
from torchvision.transforms import RandomPerspective, RandomCrop, ColorJitter, GaussianBlur
from torchvision.transforms.functional import InterpolationMode

"""
Each transform class defined here takes as input a PIL Image and returns the modified PIL Image
"""




class DPIAdjusting:
    """
    Resolution modification
    """

    def __init__(self, factor, preserve_ratio):
        self.factor = factor

    def __call__(self, x):
        w, h = x.size
        return x.resize((int(np.ceil(w * self.factor)), int(np.ceil(h * self.factor))), Image.BILINEAR)


class Dilation:
    """
    OCR: stroke width increasing
    """

    def __init__(self, kernel, iterations):
        self.kernel = np.ones(kernel, np.uint8)
        self.iterations = iterations

    def __call__(self, x):
        return Image.fromarray(dilate(np.array(x), self.kernel, iterations=self.iterations))


class Erosion:
    """
    OCR: stroke width decreasing
    """

    def __init__(self, kernel, iterations):
        self.kernel = np.ones(kernel, np.uint8)
        self.iterations = iterations

    def __call__(self, x):
        return Image.fromarray(erode(np.array(x), self.kernel, iterations=self.iterations))


class GaussianNoise:
    """
    Add Gaussian Noise
    """

    def __init__(self, std):
        self.std = std

    def __call__(self, x):
        x_np = np.array(x)
        mean, std = np.mean(x_np), np.std(x_np)
        std = math.copysign(max(abs(std), 0.000001), std)
        min_, max_ = np.min(x_np,), np.max(x_np)
        normal_noise = np.random.randn(*x_np.shape)
        if len(x_np.shape) == 3 and x_np.shape[2] == 3 and np.all(x_np[:, :, 0] == x_np[:, :, 1]) and np.all(x_np[:, :, 0] == x_np[:, :, 2]):
            normal_noise[:, :, 1] = normal_noise[:, :, 2] = normal_noise[:, :, 0]
        x_np = ((x_np-mean)/std + normal_noise*self.std) * std + mean
        x_np = normalize(x_np, x_np, max_, min_, cv2.NORM_MINMAX)

        return Image.fromarray(x_np.astype(np.uint8))


class Sharpen:
    """
    Add Gaussian Noise
    """

    def __init__(self, alpha, strength):
        self.alpha = alpha
        self.strength = strength

    def __call__(self, x):
        x_np = np.array(x)
        id_matrix = np.array([[0, 0, 0],
                              [0, 1, 0],
                              [0, 0, 0]]
                             )
        effect_matrix = np.array([[1, 1, 1],
                                  [1, -(8+self.strength), 1],
                                  [1, 1, 1]]
                                 )
        kernel = (1 - self.alpha) * id_matrix - self.alpha * effect_matrix
        kernel = np.expand_dims(kernel, axis=2)
        kernel = np.concatenate([kernel, kernel, kernel], axis=2)
        sharpened = cv2.filter2D(x_np, -1, kernel=kernel[:, :, 0])
        return Image.fromarray(sharpened.astype(np.uint8))


class ZoomRatio:
    """
        Crop by ratio
        Preserve dimensions if keep_dim = True (= zoom)
    """

    def __init__(self, ratio_h, ratio_w, keep_dim=True):
        self.ratio_w = ratio_w
        self.ratio_h = ratio_h
        self.keep_dim = keep_dim

    def __call__(self, x):
        w, h = x.size
        x = RandomCrop((int(h * self.ratio_h), int(w * self.ratio_w)))(x)
        if self.keep_dim:
            x = x.resize((w, h), Image.BILINEAR)
        return x


class ElasticDistortion:

    def __init__(self, kernel_size=(7, 7), sigma=5, alpha=1):

        self.kernel_size = kernel_size
        self.sigma = sigma
        self.alpha = alpha

    def __call__(self, x):
        x_np = np.array(x)

        h, w = x_np.shape[:2]

        dx = np.random.uniform(-1, 1, (h, w))
        dy = np.random.uniform(-1, 1, (h, w))

        x_gauss = cv2.GaussianBlur(dx, self.kernel_size, self.sigma)
        y_gauss = cv2.GaussianBlur(dy, self.kernel_size, self.sigma)

        n = np.sqrt(x_gauss**2 + y_gauss**2)

        nd_x = self.alpha * x_gauss / n
        nd_y = self.alpha * y_gauss / n

        ind_y, ind_x = np.indices((h, w), dtype=np.float32)

        map_x = nd_x + ind_x
        map_x = map_x.reshape(h, w).astype(np.float32)
        map_y = nd_y + ind_y
        map_y = map_y.reshape(h, w).astype(np.float32)

        dst = cv2.remap(x_np, map_x, map_y, cv2.INTER_LINEAR)
        return Image.fromarray(dst.astype(np.uint8))




def get_list_augmenters(img, aug_configs, fill_value):
    """
    Randomly select a list of data augmentation techniques to used based on aug_configs
    """
    augmenters = list()
    for aug_config in aug_configs:
        if rand() > aug_config["proba"]:
            continue
        if aug_config["type"] == "dpi":
            valid_factor = False
            while not valid_factor:
                factor = rand_uniform(aug_config["min_factor"], aug_config["max_factor"])
                valid_factor = not (("max_width" in aug_config and factor*img.size[0] > aug_config["max_width"]) or \
                               ("max_height" in aug_config and factor * img.size[1] > aug_config["max_height"]) or \
                               ("min_width" in aug_config and factor*img.size[0] < aug_config["min_width"]) or \
                               ("min_height" in aug_config and factor * img.size[1] < aug_config["min_height"]))
            augmenters.append(DPIAdjusting(factor, preserve_ratio=aug_config["preserve_ratio"]))

        elif aug_config["type"] == "zoom_ratio":
            ratio_h = rand_uniform(aug_config["min_ratio_h"], aug_config["max_ratio_h"])
            ratio_w = rand_uniform(aug_config["min_ratio_w"], aug_config["max_ratio_w"])
            augmenters.append(ZoomRatio(ratio_h=ratio_h, ratio_w=ratio_w, keep_dim=aug_config["keep_dim"]))

        elif aug_config["type"] == "perspective":
            scale = rand_uniform(aug_config["min_factor"], aug_config["max_factor"])
            augmenters.append(RandomPerspective(distortion_scale=scale, p=1, interpolation=InterpolationMode.BILINEAR, fill=fill_value))

        elif aug_config["type"] == "elastic_distortion":
            kernel_size = randint(aug_config["min_kernel_size"], aug_config["max_kernel_size"]) // 2 * 2 + 1
            sigma = rand_uniform(aug_config["min_sigma"], aug_config["max_sigma"])
            alpha= rand_uniform(aug_config["min_alpha"], aug_config["max_alpha"])
            augmenters.append(ElasticDistortion(kernel_size=(kernel_size, kernel_size), sigma=sigma, alpha=alpha))

        elif aug_config["type"] == "dilation_erosion":
            kernel_h = randint(aug_config["min_kernel"], aug_config["max_kernel"] + 1)
            kernel_w = randint(aug_config["min_kernel"], aug_config["max_kernel"] + 1)
            if randint(0, 2) == 0:
                augmenters.append(Erosion((kernel_w, kernel_h), aug_config["iterations"]))
            else:
                augmenters.append(Dilation((kernel_w, kernel_h), aug_config["iterations"]))

        elif aug_config["type"] == "color_jittering":
            augmenters.append(ColorJitter(contrast=aug_config["factor_contrast"],
                              brightness=aug_config["factor_brightness"],
                              saturation=aug_config["factor_saturation"],
                              hue=aug_config["factor_hue"],
                              ))

        elif aug_config["type"] == "gaussian_blur":
            max_kernel_h = min(aug_config["max_kernel"], img.size[1])
            max_kernel_w = min(aug_config["max_kernel"], img.size[0])
            kernel_h = randint(aug_config["min_kernel"], max_kernel_h + 1) // 2 * 2 + 1
            kernel_w = randint(aug_config["min_kernel"], max_kernel_w + 1) // 2 * 2 + 1
            sigma = rand_uniform(aug_config["min_sigma"], aug_config["max_sigma"])
            augmenters.append(GaussianBlur(kernel_size=(kernel_w, kernel_h), sigma=sigma))

        elif aug_config["type"] == "gaussian_noise":
            augmenters.append(GaussianNoise(std=aug_config["std"]))

        elif aug_config["type"] == "sharpen":
            alpha = rand_uniform(aug_config["min_alpha"], aug_config["max_alpha"])
            strength = rand_uniform(aug_config["min_strength"], aug_config["max_strength"])
            augmenters.append(Sharpen(alpha=alpha, strength=strength))

        else:
            print("Error - unknown augmentor: {}".format(aug_config["type"]))
            exit(-1)

    return augmenters


def apply_data_augmentation(img, da_config):
    """
    Apply data augmentation strategy on input image
    """
    applied_da = list()
    if da_config["proba"] != 1 and rand() > da_config["proba"]:
        return img, applied_da

    # Convert to PIL Image
    img = img[:, :, 0] if img.shape[2] == 1 else img
    img = Image.fromarray(img)

    fill_value = da_config["fill_value"] if "fill_value" in da_config else 255
    augmenters = get_list_augmenters(img, da_config["augmentations"], fill_value=fill_value)
    if da_config["order"] == "random":
        random.shuffle(augmenters)

    for augmenter in augmenters:
        img = augmenter(img)
        applied_da.append(type(augmenter).__name__)

    # convert to numpy array
    img = np.array(img)
    img = np.expand_dims(img, axis=2) if len(img.shape) == 2 else img
    return img, applied_da




def line_aug_config(proba_use_da, p):
    return {
        "order": "random",
        "proba": proba_use_da,
        "augmentations": [
            {
                "type": "dpi",
                "proba": p,
                "min_factor": 0.5,
                "max_factor": 1.5,
                "preserve_ratio": True,
            },
            {
                "type": "perspective",
                "proba": p,
                "min_factor": 0,
                "max_factor": 0.4,
            },
            {
                "type": "elastic_distortion",
                "proba": p,
                "min_alpha": 0.5,
                "max_alpha": 1,
                "min_sigma": 1,
                "max_sigma": 10,
                "min_kernel_size": 3,
                "max_kernel_size": 9,
            },
            {
                "type": "dilation_erosion",
                "proba": p,
                "min_kernel": 1,
                "max_kernel": 3,
                "iterations": 1,
            },
            {
                "type": "color_jittering",
                "proba": p,
                "factor_hue": 0.2,
                "factor_brightness": 0.4,
                "factor_contrast": 0.4,
                "factor_saturation": 0.4,
            },
            {
                "type": "gaussian_blur",
                "proba": p,
                "min_kernel": 3,
                "max_kernel": 5,
                "min_sigma": 3,
                "max_sigma": 5,
            },
            {
                "type": "gaussian_noise",
                "proba": p,
                "std": 0.5,
            },
            {
                "type": "sharpen",
                "proba": p,
                "min_alpha": 0,
                "max_alpha": 1,
                "min_strength": 0,
                "max_strength": 1,
            },
            {
                "type": "zoom_ratio",
                "proba": p,
                "min_ratio_h": 0.8,
                "max_ratio_h": 1,
                "min_ratio_w": 0.99,
                "max_ratio_w": 1,
                "keep_dim": True
            },
        ]
    }


def aug_config(proba_use_da, p):
    return {
        "order": "random",
        "proba": proba_use_da,
        "augmentations": [
            {
                "type": "dpi",
                "proba": p,
                "min_factor": 0.75,
                "max_factor": 1,
                "preserve_ratio": True,
            },
            {
                "type": "perspective",
                "proba": p,
                "min_factor": 0,
                "max_factor": 0.4,
            },
            {
                "type": "elastic_distortion",
                "proba": p,
                "min_alpha": 0.5,
                "max_alpha": 1,
                "min_sigma": 1,
                "max_sigma": 10,
                "min_kernel_size": 3,
                "max_kernel_size": 9,
            },
            {
                "type": "dilation_erosion",
                "proba": p,
                "min_kernel": 1,
                "max_kernel": 3,
                "iterations": 1,
            },
            {
                "type": "color_jittering",
                "proba": p,
                "factor_hue": 0.2,
                "factor_brightness": 0.4,
                "factor_contrast": 0.4,
                "factor_saturation": 0.4,
            },
            {
                "type": "gaussian_blur",
                "proba": p,
                "min_kernel": 3,
                "max_kernel": 5,
                "min_sigma": 3,
                "max_sigma": 5,
            },
            {
                "type": "gaussian_noise",
                "proba": p,
                "std": 0.5,
            },
            {
                "type": "sharpen",
                "proba": p,
                "min_alpha": 0,
                "max_alpha": 1,
                "min_strength": 0,
                "max_strength": 1,
            },
        ]
    }