rec_img_aug.py 21.6 KB
Newer Older
WenmuZhou's avatar
WenmuZhou committed
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
LDOUBLEV's avatar
LDOUBLEV committed
2
#
WenmuZhou's avatar
WenmuZhou committed
3
4
5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
LDOUBLEV's avatar
LDOUBLEV committed
6
7
8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
WenmuZhou's avatar
WenmuZhou committed
9
10
11
12
13
14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

LDOUBLEV's avatar
LDOUBLEV committed
15
16
17
import math
import cv2
import numpy as np
tink2123's avatar
tink2123 committed
18
import random
Topdu's avatar
Topdu committed
19
import copy
Topdu's avatar
Topdu committed
20
from PIL import Image
WenmuZhou's avatar
WenmuZhou committed
21
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
LDOUBLEV's avatar
LDOUBLEV committed
22

WenmuZhou's avatar
WenmuZhou committed
23
24

class RecAug(object):
littletomatodonkey's avatar
littletomatodonkey committed
25
    def __init__(self, use_tia=True, aug_prob=0.4, **kwargs):
zhoujun's avatar
zhoujun committed
26
        self.use_tia = use_tia
littletomatodonkey's avatar
littletomatodonkey committed
27
        self.aug_prob = aug_prob
WenmuZhou's avatar
WenmuZhou committed
28
29
30

    def __call__(self, data):
        img = data['image']
littletomatodonkey's avatar
littletomatodonkey committed
31
        img = warp(img, 10, self.use_tia, self.aug_prob)
WenmuZhou's avatar
WenmuZhou committed
32
33
34
35
        data['image'] = img
        return data


andyjpaddle's avatar
andyjpaddle committed
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
class RecConAug(object):
    def __init__(self,
                 prob=0.5,
                 image_shape=(32, 320, 3),
                 max_text_length=25,
                 ext_data_num=1,
                 **kwargs):
        self.ext_data_num = ext_data_num
        self.prob = prob
        self.max_text_length = max_text_length
        self.image_shape = image_shape
        self.max_wh_ratio = self.image_shape[1] / self.image_shape[0]

    def merge_ext_data(self, data, ext_data):
        ori_w = round(data['image'].shape[1] / data['image'].shape[0] *
                      self.image_shape[0])
        ext_w = round(ext_data['image'].shape[1] / ext_data['image'].shape[0] *
                      self.image_shape[0])
        data['image'] = cv2.resize(data['image'], (ori_w, self.image_shape[0]))
        ext_data['image'] = cv2.resize(ext_data['image'],
                                       (ext_w, self.image_shape[0]))
        data['image'] = np.concatenate(
            [data['image'], ext_data['image']], axis=1)
        data["label"] += ext_data["label"]
        return data

    def __call__(self, data):
        rnd_num = random.random()
        if rnd_num > self.prob:
            return data
        for idx, ext_data in enumerate(data["ext_data"]):
            if len(data["label"]) + len(ext_data[
                    "label"]) > self.max_text_length:
                break
            concat_ratio = data['image'].shape[1] / data['image'].shape[
                0] + ext_data['image'].shape[1] / ext_data['image'].shape[0]
            if concat_ratio > self.max_wh_ratio:
                break
            data = self.merge_ext_data(data, ext_data)
        data.pop("ext_data")
        return data


zhoujun's avatar
zhoujun committed
79
80
81
82
83
84
class ClsResizeImg(object):
    def __init__(self, image_shape, **kwargs):
        self.image_shape = image_shape

    def __call__(self, data):
        img = data['image']
andyjpaddle's avatar
andyjpaddle committed
85
        norm_img, _ = resize_norm_img(img, self.image_shape)
zhoujun's avatar
zhoujun committed
86
87
88
89
        data['image'] = norm_img
        return data


Topdu's avatar
Topdu committed
90
class NRTRRecResizeImg(object):
Topdu's avatar
Topdu committed
91
    def __init__(self, image_shape, resize_type, padding=False, **kwargs):
Topdu's avatar
Topdu committed
92
        self.image_shape = image_shape
Topdu's avatar
Topdu committed
93
        self.resize_type = resize_type
Topdu's avatar
Topdu committed
94
        self.padding = padding
Topdu's avatar
Topdu committed
95
96
97

    def __call__(self, data):
        img = data['image']
Topdu's avatar
Topdu committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        image_shape = self.image_shape
        if self.padding:
            imgC, imgH, imgW = image_shape
            # todo: change to 0 and modified image shape
            h = img.shape[0]
            w = img.shape[1]
            ratio = w / float(h)
            if math.ceil(imgH * ratio) > imgW:
                resized_w = imgW
            else:
                resized_w = int(math.ceil(imgH * ratio))
            resized_image = cv2.resize(img, (resized_w, imgH))
            norm_img = np.expand_dims(resized_image, -1)
            norm_img = norm_img.transpose((2, 0, 1))
            resized_image = norm_img.astype(np.float32) / 128. - 1.
            padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
            padding_im[:, :, 0:resized_w] = resized_image
            data['image'] = padding_im
            return data
Topdu's avatar
Topdu committed
118
119
120
121
122
123
124
        if self.resize_type == 'PIL':
            image_pil = Image.fromarray(np.uint8(img))
            img = image_pil.resize(self.image_shape, Image.ANTIALIAS)
            img = np.array(img)
        if self.resize_type == 'OpenCV':
            img = cv2.resize(img, self.image_shape)
        norm_img = np.expand_dims(img, -1)
Topdu's avatar
Topdu committed
125
126
127
128
        norm_img = norm_img.transpose((2, 0, 1))
        data['image'] = norm_img.astype(np.float32) / 128. - 1.
        return data

zhoujun's avatar
zhoujun committed
129

WenmuZhou's avatar
WenmuZhou committed
130
131
132
133
class RecResizeImg(object):
    def __init__(self,
                 image_shape,
                 infer_mode=False,
tink2123's avatar
tink2123 committed
134
                 character_dict_path='./ppocr/utils/ppocr_keys_v1.txt',
tink2123's avatar
tink2123 committed
135
                 padding=True,
WenmuZhou's avatar
WenmuZhou committed
136
137
138
                 **kwargs):
        self.image_shape = image_shape
        self.infer_mode = infer_mode
tink2123's avatar
tink2123 committed
139
        self.character_dict_path = character_dict_path
tink2123's avatar
tink2123 committed
140
        self.padding = padding
WenmuZhou's avatar
WenmuZhou committed
141
142
143

    def __call__(self, data):
        img = data['image']
tink2123's avatar
tink2123 committed
144
        if self.infer_mode and self.character_dict_path is not None:
andyjpaddle's avatar
andyjpaddle committed
145
146
            norm_img, valid_ratio = resize_norm_img_chinese(img,
                                                            self.image_shape)
WenmuZhou's avatar
WenmuZhou committed
147
        else:
andyjpaddle's avatar
andyjpaddle committed
148
149
            norm_img, valid_ratio = resize_norm_img(img, self.image_shape,
                                                    self.padding)
tink2123's avatar
tink2123 committed
150
        data['image'] = norm_img
andyjpaddle's avatar
andyjpaddle committed
151
        data['valid_ratio'] = valid_ratio
tink2123's avatar
tink2123 committed
152
153
154
        return data


tink2123's avatar
tink2123 committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class SRNRecResizeImg(object):
    def __init__(self, image_shape, num_heads, max_text_length, **kwargs):
        self.image_shape = image_shape
        self.num_heads = num_heads
        self.max_text_length = max_text_length

    def __call__(self, data):
        img = data['image']
        norm_img = resize_norm_img_srn(img, self.image_shape)
        data['image'] = norm_img
        [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
            srn_other_inputs(self.image_shape, self.num_heads, self.max_text_length)

        data['encoder_word_pos'] = encoder_word_pos
        data['gsrm_word_pos'] = gsrm_word_pos
        data['gsrm_slf_attn_bias1'] = gsrm_slf_attn_bias1
        data['gsrm_slf_attn_bias2'] = gsrm_slf_attn_bias2
        return data


andyjpaddle's avatar
andyjpaddle committed
175
176
177
178
179
180
181
class SARRecResizeImg(object):
    def __init__(self, image_shape, width_downsample_ratio=0.25, **kwargs):
        self.image_shape = image_shape
        self.width_downsample_ratio = width_downsample_ratio

    def __call__(self, data):
        img = data['image']
tink2123's avatar
tink2123 committed
182
183
        norm_img, resize_shape, pad_shape, valid_ratio = resize_norm_img_sar(
            img, self.image_shape, self.width_downsample_ratio)
andyjpaddle's avatar
andyjpaddle committed
184
185
186
187
188
189
190
        data['image'] = norm_img
        data['resized_shape'] = resize_shape
        data['pad_shape'] = pad_shape
        data['valid_ratio'] = valid_ratio
        return data


191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class PRENResizeImg(object):
    def __init__(self, image_shape, **kwargs):
        """
        Accroding to original paper's realization, it's a hard resize method here. 
        So maybe you should optimize it to fit for your task better.
        """
        self.dst_h, self.dst_w = image_shape

    def __call__(self, data):
        img = data['image']
        resized_img = cv2.resize(
            img, (self.dst_w, self.dst_h), interpolation=cv2.INTER_LINEAR)
        resized_img = resized_img.transpose((2, 0, 1)) / 255
        resized_img -= 0.5
        resized_img /= 0.5
        data['image'] = resized_img.astype(np.float32)
        return data


Topdu's avatar
Topdu committed
210
211
class SVTRRecResizeImg(object):
    def __init__(self,
Topdu's avatar
Topdu committed
212
213
214
215
216
                 image_shape,
                 infer_mode=False,
                 character_dict_path='./ppocr/utils/ppocr_keys_v1.txt',
                 padding=True,
                 **kwargs):
Topdu's avatar
Topdu committed
217
218
219
220
221
222
223
224
225
226
227
228
        self.image_shape = image_shape
        self.infer_mode = infer_mode
        self.character_dict_path = character_dict_path
        self.padding = padding

    def __call__(self, data):
        img = data['image']
        norm_img = resize_norm_img_svtr(img, self.image_shape, self.padding)
        data['image'] = norm_img
        return data


andyjpaddle's avatar
andyjpaddle committed
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
def resize_norm_img_sar(img, image_shape, width_downsample_ratio=0.25):
    imgC, imgH, imgW_min, imgW_max = image_shape
    h = img.shape[0]
    w = img.shape[1]
    valid_ratio = 1.0
    # make sure new_width is an integral multiple of width_divisor.
    width_divisor = int(1 / width_downsample_ratio)
    # resize
    ratio = w / float(h)
    resize_w = math.ceil(imgH * ratio)
    if resize_w % width_divisor != 0:
        resize_w = round(resize_w / width_divisor) * width_divisor
    if imgW_min is not None:
        resize_w = max(imgW_min, resize_w)
    if imgW_max is not None:
        valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
        resize_w = min(imgW_max, resize_w)
    resized_image = cv2.resize(img, (resize_w, imgH))
    resized_image = resized_image.astype('float32')
    # norm 
    if image_shape[0] == 1:
        resized_image = resized_image / 255
        resized_image = resized_image[np.newaxis, :]
    else:
        resized_image = resized_image.transpose((2, 0, 1)) / 255
    resized_image -= 0.5
    resized_image /= 0.5
    resize_shape = resized_image.shape
    padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
    padding_im[:, :, 0:resize_w] = resized_image
    pad_shape = padding_im.shape

    return padding_im, resize_shape, pad_shape, valid_ratio


tink2123's avatar
tink2123 committed
264
def resize_norm_img(img, image_shape, padding=True):
LDOUBLEV's avatar
LDOUBLEV committed
265
266
267
    imgC, imgH, imgW = image_shape
    h = img.shape[0]
    w = img.shape[1]
tink2123's avatar
tink2123 committed
268
269
270
    if not padding:
        resized_image = cv2.resize(
            img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
LDOUBLEV's avatar
LDOUBLEV committed
271
272
        resized_w = imgW
    else:
tink2123's avatar
tink2123 committed
273
274
275
276
277
278
        ratio = w / float(h)
        if math.ceil(imgH * ratio) > imgW:
            resized_w = imgW
        else:
            resized_w = int(math.ceil(imgH * ratio))
        resized_image = cv2.resize(img, (resized_w, imgH))
LDOUBLEV's avatar
LDOUBLEV committed
279
280
281
282
283
284
285
286
287
288
    resized_image = resized_image.astype('float32')
    if image_shape[0] == 1:
        resized_image = resized_image / 255
        resized_image = resized_image[np.newaxis, :]
    else:
        resized_image = resized_image.transpose((2, 0, 1)) / 255
    resized_image -= 0.5
    resized_image /= 0.5
    padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
    padding_im[:, :, 0:resized_w] = resized_image
andyjpaddle's avatar
andyjpaddle committed
289
290
    valid_ratio = min(1.0, float(resized_w / imgW))
    return padding_im, valid_ratio
LDOUBLEV's avatar
LDOUBLEV committed
291
292


tink2123's avatar
tink2123 committed
293
294
295
def resize_norm_img_chinese(img, image_shape):
    imgC, imgH, imgW = image_shape
    # todo: change to 0 and modified image shape
tink2123's avatar
tink2123 committed
296
    max_wh_ratio = imgW * 1.0 / imgH
tink2123's avatar
tink2123 committed
297
298
299
    h, w = img.shape[0], img.shape[1]
    ratio = w * 1.0 / h
    max_wh_ratio = max(max_wh_ratio, ratio)
andyjpaddle's avatar
andyjpaddle committed
300
    imgW = int(imgH * max_wh_ratio)
tink2123's avatar
tink2123 committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    if math.ceil(imgH * ratio) > imgW:
        resized_w = imgW
    else:
        resized_w = int(math.ceil(imgH * ratio))
    resized_image = cv2.resize(img, (resized_w, imgH))
    resized_image = resized_image.astype('float32')
    if image_shape[0] == 1:
        resized_image = resized_image / 255
        resized_image = resized_image[np.newaxis, :]
    else:
        resized_image = resized_image.transpose((2, 0, 1)) / 255
    resized_image -= 0.5
    resized_image /= 0.5
    padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
    padding_im[:, :, 0:resized_w] = resized_image
andyjpaddle's avatar
andyjpaddle committed
316
317
    valid_ratio = min(1.0, float(resized_w / imgW))
    return padding_im, valid_ratio
tink2123's avatar
tink2123 committed
318
319


tink2123's avatar
tink2123 committed
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
def resize_norm_img_srn(img, image_shape):
    imgC, imgH, imgW = image_shape

    img_black = np.zeros((imgH, imgW))
    im_hei = img.shape[0]
    im_wid = img.shape[1]

    if im_wid <= im_hei * 1:
        img_new = cv2.resize(img, (imgH * 1, imgH))
    elif im_wid <= im_hei * 2:
        img_new = cv2.resize(img, (imgH * 2, imgH))
    elif im_wid <= im_hei * 3:
        img_new = cv2.resize(img, (imgH * 3, imgH))
    else:
        img_new = cv2.resize(img, (imgW, imgH))

    img_np = np.asarray(img_new)
    img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    img_black[:, 0:img_np.shape[1]] = img_np
    img_black = img_black[:, :, np.newaxis]

    row, col, c = img_black.shape
    c = 1

    return np.reshape(img_black, (c, row, col)).astype(np.float32)


Topdu's avatar
Topdu committed
347
def resize_norm_img_svtr(img, image_shape, padding=False):
Topdu's avatar
Topdu committed
348
349
350
351
352
    imgC, imgH, imgW = image_shape
    h = img.shape[0]
    w = img.shape[1]
    if not padding:
        if h > 2.0 * w:
Topdu's avatar
Topdu committed
353
354
355
356
357
            image = Image.fromarray(img)
            image1 = image.rotate(90, expand=True)
            image2 = image.rotate(-90, expand=True)
            img1 = np.array(image1)
            img2 = np.array(image2)
Topdu's avatar
Topdu committed
358
        else:
Topdu's avatar
Topdu committed
359
360
361
            img1 = copy.deepcopy(img)
            img2 = copy.deepcopy(img)

Topdu's avatar
Topdu committed
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
        resized_image = cv2.resize(
            img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
        resized_image1 = cv2.resize(
            img1, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
        resized_image2 = cv2.resize(
            img2, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
        resized_w = imgW
    else:
        ratio = w / float(h)
        if math.ceil(imgH * ratio) > imgW:
            resized_w = imgW
        else:
            resized_w = int(math.ceil(imgH * ratio))
        resized_image = cv2.resize(img, (resized_w, imgH))
    resized_image = resized_image.astype('float32')
    resized_image1 = resized_image1.astype('float32')
    resized_image2 = resized_image2.astype('float32')
    if image_shape[0] == 1:
        resized_image = resized_image / 255
        resized_image = resized_image[np.newaxis, :]
    else:
        resized_image = resized_image.transpose((2, 0, 1)) / 255
        resized_image1 = resized_image1.transpose((2, 0, 1)) / 255
        resized_image2 = resized_image2.transpose((2, 0, 1)) / 255
    resized_image -= 0.5
    resized_image /= 0.5
    resized_image1 -= 0.5
    resized_image1 /= 0.5
    resized_image2 -= 0.5
    resized_image2 /= 0.5
    padding_im = np.zeros((3, imgC, imgH, imgW), dtype=np.float32)
    padding_im[0, :, :, 0:resized_w] = resized_image
    padding_im[1, :, :, 0:resized_w] = resized_image1
    padding_im[2, :, :, 0:resized_w] = resized_image2
    return padding_im


tink2123's avatar
tink2123 committed
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
def srn_other_inputs(image_shape, num_heads, max_text_length):

    imgC, imgH, imgW = image_shape
    feature_dim = int((imgH / 8) * (imgW / 8))

    encoder_word_pos = np.array(range(0, feature_dim)).reshape(
        (feature_dim, 1)).astype('int64')
    gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
        (max_text_length, 1)).astype('int64')

    gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
    gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
        [1, max_text_length, max_text_length])
    gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1,
                                  [num_heads, 1, 1]) * [-1e9]

    gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
        [1, max_text_length, max_text_length])
    gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2,
                                  [num_heads, 1, 1]) * [-1e9]

    return [
        encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
        gsrm_slf_attn_bias2
    ]


tink2123's avatar
tink2123 committed
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
def flag():
    """
    flag
    """
    return 1 if random.random() > 0.5000001 else -1


def cvtColor(img):
    """
    cvtColor
    """
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    delta = 0.001 * random.random() * flag()
    hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta)
    new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    return new_img


def blur(img):
    """
    blur
    """
    h, w, _ = img.shape
    if h > 10 and w > 10:
        return cv2.GaussianBlur(img, (5, 5), 1)
    else:
        return img


tink2123's avatar
tink2123 committed
455
def jitter(img):
tink2123's avatar
tink2123 committed
456
    """
tink2123's avatar
tink2123 committed
457
    jitter
tink2123's avatar
tink2123 committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    """
    w, h, _ = img.shape
    if h > 10 and w > 10:
        thres = min(w, h)
        s = int(random.random() * thres * 0.01)
        src_img = img.copy()
        for i in range(s):
            img[i:, i:, :] = src_img[:w - i, :h - i, :]
        return img
    else:
        return img


def add_gasuss_noise(image, mean=0, var=0.1):
472
473
474
    """
    Gasuss noise
    """
tink2123's avatar
tink2123 committed
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

    noise = np.random.normal(mean, var**0.5, image.shape)
    out = image + 0.5 * noise
    out = np.clip(out, 0, 255)
    out = np.uint8(out)
    return out


def get_crop(image):
    """
    random crop
    """
    h, w, _ = image.shape
    top_min = 1
    top_max = 8
    top_crop = int(random.randint(top_min, top_max))
491
    top_crop = min(top_crop, h - 1)
tink2123's avatar
tink2123 committed
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    crop_img = image.copy()
    ratio = random.randint(0, 1)
    if ratio:
        crop_img = crop_img[top_crop:h, :, :]
    else:
        crop_img = crop_img[0:h - top_crop, :, :]
    return crop_img


class Config:
    """
    Config
    """

zhoujun's avatar
zhoujun committed
506
    def __init__(self, use_tia):
tink2123's avatar
tink2123 committed
507
508
509
510
511
512
513
514
        self.anglex = random.random() * 30
        self.angley = random.random() * 15
        self.anglez = random.random() * 10
        self.fov = 42
        self.r = 0
        self.shearx = random.random() * 0.3
        self.sheary = random.random() * 0.05
        self.borderMode = cv2.BORDER_REPLICATE
zhoujun's avatar
zhoujun committed
515
        self.use_tia = use_tia
tink2123's avatar
tink2123 committed
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531

    def make(self, w, h, ang):
        """
        make
        """
        self.anglex = random.random() * 5 * flag()
        self.angley = random.random() * 5 * flag()
        self.anglez = -1 * random.random() * int(ang) * flag()
        self.fov = 42
        self.r = 0
        self.shearx = 0
        self.sheary = 0
        self.borderMode = cv2.BORDER_REPLICATE
        self.w = w
        self.h = h

zhoujun's avatar
zhoujun committed
532
533
534
        self.perspective = self.use_tia
        self.stretch = self.use_tia
        self.distort = self.use_tia
WenmuZhou's avatar
WenmuZhou committed
535

tink2123's avatar
tink2123 committed
536
537
538
539
        self.crop = True
        self.affine = False
        self.reverse = True
        self.noise = True
tink2123's avatar
tink2123 committed
540
        self.jitter = True
tink2123's avatar
tink2123 committed
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
        self.blur = True
        self.color = True


def rad(x):
    """
    rad
    """
    return x * np.pi / 180


def get_warpR(config):
    """
    get_warpR
    """
    anglex, angley, anglez, fov, w, h, r = \
        config.anglex, config.angley, config.anglez, config.fov, config.w, config.h, config.r
    if w > 69 and w < 112:
        anglex = anglex * 1.5

    z = np.sqrt(w**2 + h**2) / 2 / np.tan(rad(fov / 2))
    # Homogeneous coordinate transformation matrix
    rx = np.array([[1, 0, 0, 0],
                   [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [
                       0,
                       -np.sin(rad(anglex)),
                       np.cos(rad(anglex)),
                       0,
                   ], [0, 0, 0, 1]], np.float32)
    ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0],
                   [0, 1, 0, 0], [
                       -np.sin(rad(angley)),
                       0,
                       np.cos(rad(angley)),
                       0,
                   ], [0, 0, 0, 1]], np.float32)
    rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0],
                   [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0],
                   [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
    r = rx.dot(ry).dot(rz)
    # generate 4 points
    pcenter = np.array([h / 2, w / 2, 0, 0], np.float32)
    p1 = np.array([0, 0, 0, 0], np.float32) - pcenter
    p2 = np.array([w, 0, 0, 0], np.float32) - pcenter
    p3 = np.array([0, h, 0, 0], np.float32) - pcenter
    p4 = np.array([w, h, 0, 0], np.float32) - pcenter
    dst1 = r.dot(p1)
    dst2 = r.dot(p2)
    dst3 = r.dot(p3)
    dst4 = r.dot(p4)
591
    list_dst = np.array([dst1, dst2, dst3, dst4])
tink2123's avatar
tink2123 committed
592
593
594
    org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)
    dst = np.zeros((4, 2), np.float32)
    # Project onto the image plane
595
596
597
    dst[:, 0] = list_dst[:, 0] * z / (z - list_dst[:, 2]) + pcenter[0]
    dst[:, 1] = list_dst[:, 1] * z / (z - list_dst[:, 2]) + pcenter[1]

tink2123's avatar
tink2123 committed
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
    warpR = cv2.getPerspectiveTransform(org, dst)

    dst1, dst2, dst3, dst4 = dst
    r1 = int(min(dst1[1], dst2[1]))
    r2 = int(max(dst3[1], dst4[1]))
    c1 = int(min(dst1[0], dst3[0]))
    c2 = int(max(dst2[0], dst4[0]))

    try:
        ratio = min(1.0 * h / (r2 - r1), 1.0 * w / (c2 - c1))

        dx = -c1
        dy = -r1
        T1 = np.float32([[1., 0, dx], [0, 1., dy], [0, 0, 1.0 / ratio]])
        ret = T1.dot(warpR)
    except:
        ratio = 1.0
        T1 = np.float32([[1., 0, 0], [0, 1., 0], [0, 0, 1.]])
        ret = T1
    return ret, (-r1, -c1), ratio, dst


def get_warpAffine(config):
    """
    get_warpAffine
    """
    anglez = config.anglez
    rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0],
                   [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0]], np.float32)
    return rz


littletomatodonkey's avatar
littletomatodonkey committed
630
def warp(img, ang, use_tia=True, prob=0.4):
tink2123's avatar
tink2123 committed
631
632
633
634
    """
    warp
    """
    h, w, _ = img.shape
zhoujun's avatar
zhoujun committed
635
    config = Config(use_tia=use_tia)
tink2123's avatar
tink2123 committed
636
637
638
    config.make(w, h, ang)
    new_img = img

WenmuZhou's avatar
WenmuZhou committed
639
640
641
642
643
644
645
646
647
648
    if config.distort:
        img_height, img_width = img.shape[0:2]
        if random.random() <= prob and img_height >= 20 and img_width >= 20:
            new_img = tia_distort(new_img, random.randint(3, 6))

    if config.stretch:
        img_height, img_width = img.shape[0:2]
        if random.random() <= prob and img_height >= 20 and img_width >= 20:
            new_img = tia_stretch(new_img, random.randint(3, 6))

tink2123's avatar
tink2123 committed
649
    if config.perspective:
WenmuZhou's avatar
WenmuZhou committed
650
651
652
        if random.random() <= prob:
            new_img = tia_perspective(new_img)

tink2123's avatar
tink2123 committed
653
654
    if config.crop:
        img_height, img_width = img.shape[0:2]
WenmuZhou's avatar
WenmuZhou committed
655
        if random.random() <= prob and img_height >= 20 and img_width >= 20:
tink2123's avatar
tink2123 committed
656
            new_img = get_crop(new_img)
WenmuZhou's avatar
WenmuZhou committed
657

tink2123's avatar
tink2123 committed
658
    if config.blur:
WenmuZhou's avatar
WenmuZhou committed
659
        if random.random() <= prob:
tink2123's avatar
tink2123 committed
660
661
            new_img = blur(new_img)
    if config.color:
WenmuZhou's avatar
WenmuZhou committed
662
        if random.random() <= prob:
tink2123's avatar
tink2123 committed
663
            new_img = cvtColor(new_img)
tink2123's avatar
tink2123 committed
664
665
    if config.jitter:
        new_img = jitter(new_img)
tink2123's avatar
tink2123 committed
666
    if config.noise:
WenmuZhou's avatar
WenmuZhou committed
667
        if random.random() <= prob:
tink2123's avatar
tink2123 committed
668
669
            new_img = add_gasuss_noise(new_img)
    if config.reverse:
WenmuZhou's avatar
WenmuZhou committed
670
        if random.random() <= prob:
tink2123's avatar
tink2123 committed
671
672
            new_img = 255 - new_img
    return new_img