-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_renderer.py
2137 lines (1852 loc) · 79.8 KB
/
word_renderer.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
# Max Jaderberg 12/5/14
# -*- coding:utf-8 -*-
# Module for rendering words
# BLEND MODES: http://stackoverflow.com/questions/601776/what-do-the-blend-modes-in-pygame-mean
# Rendered words have three colours - base char (0) and border/shadow (128) and background (255)
# TO RUN ON TITAN: use source ~/Work/virtual_envs/paintings_env/bin/activate
import sys
import pygame
import os
import re
from pygame.locals import *
import numpy as n
from pygame import freetype
import math
from matplotlib import pyplot
from PIL import Image
from scipy import ndimage, interpolate
import scipy.cluster
from matplotlib import cm
import random
from scipy.io import loadmat
import time
import h5py
import pandas as pd
import cv2
import json
from skimage import exposure, util
from yinhangcard import makePic,adjust3
from back_adjust import BackAdjust
def wait_key():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN and event.key == K_SPACE:
return
def rgb2gray(rgb):
# RGB -> grey-scale (as in Matlab's rgb2grey)
try:
r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
except IndexError:
try:
gray = rgb[:, :, 0]
except IndexError:
gray = rgb[:, :]
return gray
def resize_image(im, r=None, newh=None, neww=None, filtering=Image.BILINEAR):
dt = im.dtype
I = Image.fromarray(im)
if r is not None:
h = im.shape[0]
w = im.shape[1]
newh = int(round(r * h))
neww = int(round(r * w))
if neww is None:
neww = int(newh * im.shape[1] / float(im.shape[0]))
if newh > im.shape[0]:
I = I.resize([neww, newh], Image.ANTIALIAS)
else:
I.thumbnail([neww, newh], filtering)
return n.array(I).astype(dt)
def matrix_mult(A, B):
C = n.empty((A.shape[0], B.shape[1]))
for i in range(C.shape[0]):
for j in range(C.shape[1]):
C[i, j] = n.sum(A[i, :] * B[:, j])
return C
def save_screen_img(pg_surface, fn, quality=100):
imgstr = pygame.image.tostring(pg_surface, 'RGB')
im = Image.fromstring('RGB', pg_surface.get_size(), imgstr)
im.save(fn, quality=quality)
print
fn
MJBLEND_NORMAL = "normal"
MJBLEND_ADD = "add"
MJBLEND_SUB = "subtract"
MJBLEND_MULT = "multiply"
MJBLEND_MULTINV = "multiplyinv"
MJBLEND_SCREEN = "screen"
MJBLEND_DIVIDE = "divide"
MJBLEND_MIN = "min"
MJBLEND_MAX = "max"
def grey_blit1(src, dst, blend_mode=MJBLEND_NORMAL):
"""
This is for grey + alpha images
"""
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
# blending with alpha http://stackoverflow.com/questions/1613600/direct3d-rendering-2d-images-with-multiply-blending-mode-and-alpha
# blending modes from: http://www.linuxtopia.org/online_books/graphics_tools/gimp_advanced_guide/gimp_guide_node55.html
dt = dst.dtype
src = src.astype(n.single)
dst = dst.astype(n.single)
out = n.empty(src.shape, dtype='float')
alpha = n.index_exp[:, :, 1]
rgb = n.index_exp[:, :, 0]
src_a = src[alpha] / 255.0
dst_a = dst[alpha] / 255.0
out[alpha] = src_a + dst_a * (1 - src_a)
old_setting = n.seterr(invalid='ignore')
src_pre = src[rgb] * src_a
dst_pre = dst[rgb] * dst_a
# blend:
blendfuncs = {MJBLEND_NORMAL: lambda s, d, sa_: s + d * sa_,
MJBLEND_ADD: lambda s, d, sa_: n.minimum(255, s + d),
MJBLEND_SUB: lambda s, d, sa_: n.maximum(0, s - d),
MJBLEND_MULT: lambda s, d, sa_: s * d * sa_ / 255.0,
MJBLEND_MULTINV: lambda s, d, sa_: (255.0 - s) * d * sa_ / 255.0,
MJBLEND_SCREEN: lambda s, d, sa_: 255 - (1.0 / 255.0) * (255.0 - s) * (255.0 - d * sa_),
MJBLEND_DIVIDE: lambda s, d, sa_: n.minimum(255, d * sa_ * 256.0 / (s + 1.0)),
MJBLEND_MIN: lambda s, d, sa_: n.minimum(d * sa_, s),
MJBLEND_MAX: lambda s, d, sa_: n.maximum(d * sa_, s), }
out[rgb] = blendfuncs[blend_mode](src_pre, dst_pre, (1 - src_a))
out[rgb] /= out[alpha]
n.seterr(**old_setting)
out[alpha] *= 255
n.clip(out, 0, 255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype(dt)
return out
def grey_blit(src, dst, blend_mode=MJBLEND_NORMAL):
"""
This is for grey + alpha images
"""
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
# blending with alpha http://stackoverflow.com/questions/1613600/direct3d-rendering-2d-images-with-multiply-blending-mode-and-alpha
# blending modes from: http://www.linuxtopia.org/online_books/graphics_tools/gimp_advanced_guide/gimp_guide_node55.html
dt = dst.dtype
src = src.astype(n.single)
dst = dst.astype(n.single)
out = n.empty(src.shape, dtype='float')
alpha = n.index_exp[:, :, 1]
rgb = n.index_exp[:, :, 0]
src_a = src[alpha] / 255.0
dst_a = dst[alpha] / 255.0
out[alpha] = src_a + dst_a * (1 - src_a)
old_setting = n.seterr(invalid='ignore')
src_pre = src[rgb] * src_a
dst_pre = dst[rgb] * dst_a
# blend: 混合色 基色
blendfuncs = {MJBLEND_NORMAL: lambda s, d, sa_: s + d * sa_, MJBLEND_ADD: lambda s, d, sa_: n.minimum(255, s + d),
MJBLEND_SUB: lambda s, d, sa_: n.maximum(0, s - d), MJBLEND_MULT: lambda s, d, sa_: s * d * sa_ / 255.0,
MJBLEND_MULTINV: lambda s, d, sa_: (255.0 - s) * d * sa_ / 255.0,
MJBLEND_SCREEN: lambda s, d, sa_: 255 - (1.0 / 255.0) * (255.0 - s) * (255.0 - d * sa_),
MJBLEND_DIVIDE: lambda s, d, sa_: n.minimum(255, d * sa_ * 256.0 / (s + 1.0)),
MJBLEND_MIN: lambda s, d, sa_: n.minimum(d * sa_, s), MJBLEND_MAX: lambda s, d, sa_: n.maximum(d * sa_, s), }
out[rgb] = blendfuncs[blend_mode](src_pre, dst_pre, (1 - src_a))
out[rgb] /= out[alpha]
n.seterr(**old_setting)
out[alpha] *= 255
n.clip(out, 0, 255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype(dt)
return out
class Corpus(object):
"""
Defines a corpus of words
"""
# valid_ascii = [48,49,50,51,52,53,54,55,56,57,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]
valid_ascii = [36, 37, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 61, 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, 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]
def __init__(self):
pass
class TestCorpus(Corpus):
"""
Just a test corpus from a text file
"""
CORPUS_FN = "./corpus.txt"
def __init__(self, args={'unk_probability': 0}):
self.corpus_text = ""
pattern = re.compile('[^a-zA-Z0-9 ]')
for line in open(self.CORPUS_FN):
line = line.replace('\n', ' ')
line = pattern.sub('', line)
self.corpus_text = self.corpus_text + line
self.corpus_text = ''.join(c for c in self.corpus_text if c.isalnum() or c.isspace())
self.corpus_list = self.corpus_text.split()
self.unk_probability = args['unk_probability']
def get_sample(self, length=None):
"""
Return a word sample from the corpus, with optional length requirement (cropped word)
"""
sampled = False
idx = n.random.randint(0, len(self.corpus_list))
breakamount = 1000
count = 0
while not sampled:
samp = self.corpus_list[idx]
if length > 0:
if len(samp) >= length:
if len(samp) > length:
# start at a random point in this word
diff = len(samp) - length
starti = n.random.randint(0, diff)
samp = samp[starti:starti + length]
break
else:
break
idx = n.random.randint(0, len(self.corpus_list))
count += 1
if count > breakamount:
raise Exception("Unable to generate a good corpus sample")
if n.random.rand() < self.unk_probability:
# change some letters to make it random
ntries = 0
while True:
ntries += 1
if len(samp) > 2:
n_to_change = n.random.randint(2, len(samp))
else:
n_to_change = max(1, len(samp) - 1)
idx_to_change = n.random.permutation(len(samp))[0:n_to_change]
samp = list(samp)
for idx in idx_to_change:
samp[idx] = chr(random.choice(self.valid_ascii))
samp = "".join(samp)
if samp not in self.corpus_list:
idx = len(self.corpus_list)
break
if ntries > 10:
idx = self.corpus_list.index(samp)
break
return samp, idx
class SVTCorpus(TestCorpus):
CORPUS_FN = "/Users/jaderberg/Data/TextSpotting/DataDump/svt1/svt_lex_lower.txt"
class FileCorpus(TestCorpus):
def __init__(self, args):
self.CORPUS_FN = args['fn']
TestCorpus.__init__(self, args)
class NgramCorpus(TestCorpus):
"""
Spits out a word sample, dictionary label, and ngram encoding labels
"""
def __init__(self, args):
words_fn = args['encoding_fn_base'] + '_words.txt'
idx_fn = args['encoding_fn_base'] + '_idx.txt'
values_fn = args['encoding_fn_base'] + '_values.txt'
self.words = self._load_list(words_fn)
self.idx = self._load_list(idx_fn, split=' ', tp=int)
self.values = self._load_list(values_fn, split=' ', tp=int)
def get_sample(self, length=None):
"""
Return a word sample from the corpus, with optional length requirement (cropped word)
"""
sampled = False
idx = n.random.randint(0, len(self.words))
breakamount = 1000
count = 0
while not sampled:
samp = self.words[idx]
if length > 0:
if len(samp) >= length:
if len(samp) > length:
# start at a random point in this word
diff = len(samp) - length
starti = n.random.randint(0, diff)
samp = samp[starti:starti + length]
break
else:
break
idx = n.random.randint(0, len(self.words))
count += 1
if count > breakamount:
raise Exception("Unable to generate a good corpus sample")
return samp, {'word_label': idx, 'ngram_labels': self.idx[idx], 'ngram_counts': self.values[idx], }
def _load_list(self, listfn, split=None, tp=str):
arr = []
for l in open(listfn):
l = l.strip()
if split is not None:
l = [tp(x) for x in l.split(split)]
else:
l = tp(l)
arr.append(l)
return arr
class RandomCorpus(Corpus):
"""
Generates random strings
"""
def __init__(self, args={'min_length': 1, 'max_length': 23}):
self.min_length = args['min_length']
self.max_length = args['max_length']
def get_sample(self, length=None):
if length is None:
length = random.randint(self.min_length, self.max_length)
samp = ""
for i in range(length):
samp = samp + chr(random.choice(self.valid_ascii))
return samp, length
class FontState(object):
"""
Defines the random state of the font rendering
"""
#size = [60, 10] # normal dist mean, std
underline = 0.1
strong = 0.5
oblique = 0.2
wide = 0.5
strength = [0.02778, 0.05333] # uniform dist in this interval
underline_adjustment = [1.0, 2.0] # normal dist mean, std
kerning = [2, 5, 0, 20] # beta distribution alpha, beta, offset, range (mean is a/(a+b))
border = 0.25
random_caps = 1.0
capsmode = [str.lower, str.upper, str.capitalize] # lower case, upper case, proper noun
curved = 1
random_kerning = 0.2
random_kerning_amount = 0.1
def __init__(self, path="/home/ubuntu/Datasets/SVT/",fontSize=25,isRandom=False,fontPic=False):
self.fonts = [os.path.join(path, f.strip()) for f in os.listdir(path)]
self.size=[fontSize,fontSize]
self.isRandom=isRandom
if fontPic:
result = {}
for file in os.listdir(path):
filePath = os.path.join(path, file)
if os.path.isdir(filePath):
temp = []
for subfile in os.listdir(filePath):
temp.append(os.path.join(filePath, subfile))
result[file.decode("utf-8")] = temp
if result.has_key("point"):
result[u"."] = result.pop("point")
self.fontPic = result
def get_sample(self):
"""
Samples from the font state distribution
"""
if not self.isRandom:
return {'font': self.fonts[int(n.random.randint(0, len(self.fonts)))],
'size': self.size[0], 'underline': False,
'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1] * n.random.randn() +
self.underline_adjustment[0])),
'strong': False, 'oblique': False,
'strength': self.strength[0],
'char_spacing': 0,
'border': False, 'random_caps': False,
'capsmode': random.choice(self.capsmode), 'curved': False,
'random_kerning': False,
'random_kerning_amount': self.random_kerning_amount, }
else:
return {'font': self.fonts[int(n.random.randint(0, len(self.fonts)))],
'size': self.size[0], 'underline': n.random.rand() < self.underline,
'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1] * n.random.randn() +
self.underline_adjustment[0])),
'strong': n.random.rand() < self.strong, 'oblique': n.random.rand() < self.oblique,
'strength': (self.strength[1] - self.strength[0]) * n.random.rand() + self.strength[0],
'char_spacing': int(self.kerning[3] * (n.random.beta(self.kerning[0], self.kerning[1])) + self.kerning[2]),
'border': n.random.rand() < self.border, 'random_caps': n.random.rand() < self.random_caps,
'capsmode': random.choice(self.capsmode), 'curved': n.random.rand() < self.curved,
'random_kerning': n.random.rand() < self.random_kerning,
'random_kerning_amount': self.random_kerning_amount, }
class AffineTransformState(object):
"""
Defines the random state for an affine transformation
"""
proj_type = Image.AFFINE
rotation = [0, 5] # rotate normal dist mean, std
skew = [0, 0] # skew normal dist mean, std
def sample_transformation(self, imsz):
#theta = math.radians(self.rotation[1] * n.random.randn() + self.rotation[0])
theta = math.radians(random.uniform(-5,5))
ca = math.cos(theta)
sa = math.sin(theta)
R = n.zeros((3, 3))
R[0, 0] = ca
R[0, 1] = -sa
R[1, 0] = sa
R[1, 1] = ca
R[2, 2] = 1
S = n.eye(3, 3)
S[0, 1] = math.tan(math.radians(self.skew[1] * n.random.randn() + self.skew[0]))
A = matrix_mult(R, S)
x = imsz[1] / 2
y = imsz[0] / 2
return (A[0, 0], A[0, 1], -x * A[0, 0] - y * A[0, 1] + x, A[1, 0], A[1, 1], -x * A[1, 0] - y * A[1, 1] + y)
class PerspectiveTransformState(object):
"""
Defines teh random state for a perspective transformation
Might need to use http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil
"""
proj_type = Image.PERSPECTIVE
a_dist = [1, 0.01]
b_dist = [0, 0.005]
c_dist = [0, 0.005]
d_dist = [1, 0.01]
e_dist = [0, 0.0005]
f_dist = [0, 0.0005]
def v(self, dist):
return dist[1] * n.random.randn() + dist[0]
def sample_transformation(self, imsz):
x = imsz[1] / 2
y = imsz[0] / 2
a = self.v(self.a_dist)
b = self.v(self.b_dist)
c = self.v(self.c_dist)
d = self.v(self.d_dist)
e = self.v(self.e_dist)
f = self.v(self.f_dist)
# scale a and d so scale kept same
# a = 1 - e*x
# d = 1 - f*y
z = -e * x - f * y + 1
A = n.zeros((3, 3))
A[0, 0] = a + e * x
A[0, 1] = b + f * x
A[0, 2] = -a * x - b * y - e * x * x - f * x * y + x
A[1, 0] = c + e * y
A[1, 1] = d + f * y
A[1, 2] = -c * x - d * y - e * x * y - f * y * y + y
A[2, 0] = e
A[2, 1] = f
A[2, 2] = z
# print a,b,c,d,e,f
# print z
A = A / z
#(A[0, 0], A[0, 1], A[0, 2], A[1, 0], A[1, 1], A[1, 2], A[2, 0], A[2, 1])
import numpy as np
return np.float64(A)
class ElasticDistortionState(object):
"""
Defines a random state for elastic distortions
"""
displacement_range = 1
alpha_dist = [[15, 30], [0, 2]]
sigma = [[8, 2], [0.2, 0.2]]
min_sigma = [4, 0]
def sample_transformation(self, imsz):
choices = len(self.alpha_dist)
c = int(n.random.randint(0, choices))
sigma = max(self.min_sigma[c], n.abs(self.sigma[c][1] * n.random.randn() + self.sigma[c][0]))
alpha = n.random.uniform(self.alpha_dist[c][0], self.alpha_dist[c][1])
dispmapx = n.random.uniform(-1 * self.displacement_range, self.displacement_range, size=imsz)
dispmapy = n.random.uniform(-1 * self.displacement_range, self.displacement_range, size=imsz)
dispmapx = alpha * ndimage.gaussian_filter(dispmapx, sigma)
dispmaxy = alpha * ndimage.gaussian_filter(dispmapy, sigma)
return dispmapx, dispmaxy
class BorderState(object):
outset = 0.5
width = [4, 4] # normal dist
position = [[0, 0], [-1, -1], [-1, 1], [1, 1], [1, -1]]
def get_sample(self):
p = self.position[int(n.random.randint(0, len(self.position)))]
w = max(1, int(self.width[1] * n.random.randn() + self.width[0]))
return {'outset': n.random.rand() < self.outset, 'width': w,
'position': [int(-1 * n.random.uniform(0, w * p[0] / 1.5)), int(-1 * n.random.uniform(0, w * p[1] / 1.5))]}
class ColourState(object):
"""
Gives the foreground, background, and optionally border colourstate.
Does this by sampling from a training set of images, and clustering in to desired number of colours
(http://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image)
"""
IMFN = "/home/ubuntu/Datasets/text-renderer/image_24_results.png"
def __init__(self):
self.im = rgb2gray(n.array(Image.open(self.IMFN)))
def get_sample(self, n_colours):
# print 'Inside Color State'
a = self.im.flatten()
codes, dist = scipy.cluster.vq.kmeans(a, n_colours)
# get std of centres
vecs, dist = scipy.cluster.vq.vq(a, codes)
colours = []
for i in range(n_colours):
try:
code = codes[i]
std = n.std(a[vecs == i])
colours.append(std * n.random.randn() + code)
except IndexError:
print
"\tcolour error"
colours.append(int(sum(colours) / float(len(colours))))
# choose randomly one of each colour
return n.random.permutation(colours)
class TrainingCharsColourState(object):
"""
Gives the foreground, background, and optionally border colourstate.
Does this by sampling from a training set of images, and clustering in to desired number of colours
(http://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image)
"""
def __init__(self, matfn="/home/ubuntu/Datasets/SVT/icdar_2003_train.txt"):
# self.ims = loadmat(matfn)['images']
# with open(matfn) as f: self.ims = f.read().splitlines()
#list_fn = list(pd.read_csv(matfn, sep='\t')['Image_Path'])
list_fn=[os.path.join(matfn,file.strip()) for file in os.listdir(matfn) if file.endswith(".jpg")]
self.ims = list_fn
def get_sample(self, n_colours):
curs = 0
while True:
curs += 1
if curs > 1000:
print
"problem with colours"
break
# im_sample=cv2.imread(random.choice(self.ims),0)
# im = cv2.normalize(im_sample.astype('float'), None, 0.0, 1.0, cv2.NORM_MINMAX) # Convert to normalized floating point
imfn = random.choice(self.ims)
im = rgb2gray(n.array(Image.open(imfn)))
# im = self.ims[...,n.random.randint(0, self.ims.shape[2])]
a = im.flatten()
codes, dist = scipy.cluster.vq.kmeans(a, n_colours)
if len(codes) != n_colours:
continue
# get std of centres
vecs, dist = scipy.cluster.vq.vq(a, codes)
colours = []
for i, code in enumerate(codes):
std = n.std(a[vecs == i])
colours.append(std * n.random.randn() + code)
break
# choose randomly one of each colour
return n.random.permutation(colours)
class FillImageState(object):
"""
Handles the images used for filling the background, foreground, and border surfaces
"""
DATA_DIR = '/home/ubuntu/Pictures/'
IMLIST = ['maxresdefault.jpg', 'alexis-sanchez-arsenal-wallpaper-phone.jpg', 'alexis.jpeg']
blend_amount = [0.0, 0.25] # normal dist mean, std
blend_modes = [MJBLEND_NORMAL, MJBLEND_ADD, MJBLEND_MULTINV, MJBLEND_SCREEN, MJBLEND_MAX]
blend_order = 0.5
min_textheight = 16.0 # minimum pixel height that you would find text in an image
def get_sample(self, surfarr):
"""
The image sample returned should not have it's aspect ratio changed, as this would never happen in real world.
It can still be resized of course.
"""
# load image
imfn = random.choice(self.IMLIST)
baseim = n.array(Image.open(imfn))
# choose a colour channel or rgb2gray
if baseim.ndim == 3:
if n.random.rand() < 0.25:
baseim = rgb2gray(baseim)
else:
baseim = baseim[..., n.random.randint(0, 3)]
else:
assert (baseim.ndim == 2)
imsz = baseim.shape
surfsz = surfarr.shape
# don't resize bigger than if at the original size, the text was less than min_textheight
max_factor = float(surfsz[0]) / self.min_textheight
# don't resize smaller than it is smaller than a dimension of the surface
min_factor = max(float(surfsz[0] + 5) / float(imsz[0]), float(surfsz[1] + 5) / float(imsz[1]))
# sample a resize factor
factor = max(min_factor, min(max_factor, ((max_factor - min_factor) / 1.5) * n.random.randn() + max_factor))
sampleim = resize_image(baseim, factor)
imsz = sampleim.shape
# sample an image patch
good = False
curs = 0
while not good:
curs += 1
if curs > 1000:
print
"difficulty getting sample"
break
try:
x = n.random.randint(0, imsz[1] - surfsz[1])
y = n.random.randint(0, imsz[0] - surfsz[0])
good = True
except ValueError:
# resample factor
factor = max(min_factor,
min(max_factor, ((max_factor - min_factor) / 1.5) * n.random.randn() + max_factor))
sampleim = resize_image(baseim, factor)
imsz = sampleim.shape
imsample = (n.zeros(surfsz) + 255).astype(surfarr.dtype)
imsample[..., 0] = sampleim[y:y + surfsz[0], x:x + surfsz[1]]
imsample[..., 1] = surfarr[..., 1].copy()
#imsample[..., 1] = sampleim[y:y + surfsz[0], x:x + surfsz[1]]
#imsample[..., 2] = sampleim[y:y + surfsz[0], x:x + surfsz[1]]
return {'image': imsample, 'blend_mode': random.choice(self.blend_modes),
'blend_amount': min(1.0, n.abs(self.blend_amount[1] * n.random.randn() + self.blend_amount[0])),
'blend_order': n.random.rand() < self.blend_order, }
# class SVTFillImageState(FillImageState):
# def __init__(self, data_dir, gtmat_fn):
# self.DATA_DIR = data_dir
# gtmat = loadmat(gtmat_fn)['gt']
# with open(gtmat_fn) as f: self.IMLIST = f.read().splitlines()
class SVTFillImageState(FillImageState):
def __init__(self, label_data_dir,random_data_dir,isNoise):
list_fn = []
if os.path.exists(label_data_dir):
for file in os.listdir(label_data_dir):
if file.endswith(".jpg"):
list_fn.append(os.path.join(label_data_dir,file))
self.label_back = list_fn
if isNoise:
list_fn = []
if os.path.exists(random_data_dir):
for file in os.listdir(random_data_dir):
if file.endswith(".jpg"):
list_fn.append(os.path.join(random_data_dir, file))
self.IMLIST = list_fn
# print list_fn
# for gtmat_fn in list_fn:
# with open(gtmat_fn) as f:
# self.IMLIST += (f.read().splitlines())
# print self.IMLIST
def get_sample_p(self, surfarr1,outconfig=None):
import numpy as np
try :
fileimge = random.choice(self.label_back)
img = Image.open(fileimge)
except Exception:
if len(surfarr1)>1:
return None
surfarr=surfarr1[0]
surfarr=surfarr.astype(np.uint8)
surfarr[:] = 255 - surfarr[:]
surfarr = surfarr.reshape((surfarr.shape[0], surfarr.shape[1], 1))
return np.concatenate((surfarr, surfarr, surfarr), axis=2)
faldl = fileimge.replace(".jpg", ".lar")
boxs=[]
#设置粘贴区域
try:
with open(faldl, 'rb') as f:
setting = json.load(f, "gbk")
print setting[0]["rect"]
for tt in setting[:len(surfarr1)]:
if len(tt["rect"].split(",")) != 4:
# img.show
return
left = int(tt["rect"].split(",")[0])
up = int(tt["rect"].split(",")[1])
right = int(tt["rect"].split(",")[2])
down = int(tt["rect"].split(",")[3])
boxs.append((left, up, right, down))
except Exception:
(left, up, right, down)=(2,2,img.size[0], img.size[1])
boxs.append((left, up, right, down))
char_shape_list=[surfarr.shape for surfarr in surfarr1]
boxslist=boxs
if len(boxs)>2:
boxslist=adjust3(char_shape_list,boxs)
for surfarr,(left, up, right, down) in zip(surfarr1,boxslist):
box0 = (left, up, right, down)
#背景调整
try:
adjust=BackAdjust(img,charSize=surfarr.shape[:2],oriBox=box0,Height=outconfig["output_height"],Width=outconfig["output_width"])
adjust_fun=getattr(adjust,outconfig["back_adjust"])
img, (left, up, right, down)=adjust_fun()
except Exception:
#未设置背景调整
pass
h, w = surfarr.shape[:2]
if up + h > down or left + w > right:
print("error:the font size is too big")
#粘贴区域不足以容下字符图
raise ValueError
#生成随机区域
if outconfig["ver_random"]:
down = random.randint(up + h, down)
up = down - h
else:down=up+h
if outconfig["hor_random"]:
right = random.randint(left + w, right)
left = right - w
else:right=left+w
alpha = surfarr
#转成白底黑字
alpha[:] = 255 - alpha[:]
alpha = alpha.reshape((alpha.shape[0], alpha.shape[1], 1))
surfarr = np.concatenate((alpha, alpha, alpha), axis=2)
region = img.crop((left, up, right, down))
region = np.array(region)
surfarr = surfarr.astype(np.float32)
surfarr[:] = surfarr[:] / 255.0
if outconfig["red"]:
surfarr[...,0]=1
region=region*surfarr
print(region.shape[0])
region = region.astype(np.uint8)
img.paste(Image.fromarray(region), (left, up, right, down))
#img.show()
if not outconfig["keep_label"] and False:
a = random.randint( 0, 3)
b = random.randint( 0, 3)
c = random.randint( 0, 3)
d = random.randint( 0, 3)
left=max(left-a,0)
up = max(up - b, 1)
right=min(img.size[0],right+ c)
down = min(img.size[1], down + d)
img = img.crop(( left, up, right,down))
return np.array(img)
return np.array(img)
def get_sample_p_blur(self, surfarr):
fileimge=random.choice(self.IMLIST)
#return surfarr
h,w = surfarr.shape[:2]
if not self.isRandom:
faldl = fileimge.replace(".jpg", ".lar")
with open(faldl, 'rb') as f:
setting = json.load(f, "gbk")
print setting[0]["rect"]
tt = setting[0]
if len(tt["rect"].split(",")) != 4:
# img.show
return
left = int(tt["rect"].split(",")[0])
up = int(tt["rect"].split(",")[1])
right = int(tt["rect"].split(",")[2])
down = int(tt["rect"].split(",")[3])
if up + h>=down:
print("error:the font size is too big")
heheight = random.randint(up + h, down)
down = heheight
up = heheight - h
import numpy as np
img = Image.open(fileimge)
#surfarr=Image.fromarray(surfarr)
#surfarr = surfarr.convert('L')
#surfarr=np.array(surfarr)
height_want = down - up
r = float(height_want) / h
surfarr=np.reshape(surfarr,(height_want, int(w * r),surfarr.shape[2]))
if w < right -left:
right = left +w
region = img.crop((left, up, right, down))
region=np.array(region)
rr=np.max(surfarr[:,:,0])
rr2 = np.max(surfarr[:, :, 1])
rr3 = np.max(surfarr[:, :, 2])
surfarr=Image.fromarray(surfarr)
surfarr=np.array(surfarr)
surfarr = rgb2gray(surfarr)
temp=np.reshape(surfarr,(surfarr.shape[0],surfarr.shape[1],1))
surfarr=np.concatenate((temp,np.zeros(temp.shape),np.zeros(temp.shape)),axis=2)
#mean=np.mean(surfarr)
surfarr[surfarr>35]=255-surfarr[surfarr>35]
surfarr[surfarr <= 35] = 255
#surfarr[:]=255-surfarr[:]
surfarr[:]=surfarr[:]/255.0
#surfarr=np.concatenate((surfarr, np.ones((surfarr.shape[0],surfarr.shape[1],1))), axis=2)
if surfarr.shape[:2]==region.shape[:2]:
region=region*surfarr
region=region.astype(np.uint8)
img.paste(Image.fromarray(region), (left, up, right, down))
#返回3通道图像
return np.array(img)
else:return None
class DistortionState(object):
blur = [0, 1]
sharpen = 0
sharpen_amount = [30, 10]
noise = 4
resample = 0.1
resample_range = [24, 32]
def get_sample(self):
return {'blur': n.abs(self.blur[1] * n.random.randn() + self.blur[0]),
'sharpen': n.random.rand() < self.sharpen,
'sharpen_amount': self.sharpen_amount[1] * n.random.randn() + self.sharpen_amount[0], 'noise': self.noise,
'resample': n.random.rand() < self.resample,
'resample_height': int(n.random.uniform(self.resample_range[0], self.resample_range[1]))}
class SurfaceDistortionState(DistortionState):
noise = 8
resample = 0
class BaselineState(object):
curve = lambda this, a: lambda x: a * x * x
differential = lambda this, a: lambda x: 2 * a * x
a = [1, 0.1]
def get_sample(self):
"""
Returns the functions for the curve and differential for a and b
"""
a = self.a[1] * n.random.randn() + self.a[0]
return {'curve': self.curve(a), 'diff': self.differential(a), }
class WordRenderer(object):
def __init__(self, sz=(800, 200), corpus=TestCorpus, fontstate=FontState, colourstate=ColourState,
fillimstate=FillImageState,info=None):
# load corpus
self.corpus = corpus() if isinstance(corpus, type) else corpus
# load fonts
self.fontstate = fontstate() if isinstance(fontstate, type) else fontstate
# init renderer
pygame.init()
self.sz = sz
self.screen = None
self.perspectivestate = PerspectiveTransformState()
self.affinestate = AffineTransformState()
self.borderstate = BorderState()
self.colourstate = colourstate() if isinstance(colourstate, type) else colourstate
self.fillimstate = fillimstate() if isinstance(fillimstate, type) else fillimstate
self.diststate = DistortionState()
self.surfdiststate = SurfaceDistortionState()
self.baselinestate = BaselineState()
self.elasticstate = ElasticDistortionState()
self.extraInfo=info
def invert_surface(self, surf):
pixels = pygame.surfarray.pixels2d(surf)
pixels ^= 2 ** 32 - 1
del pixels
def invert_arr(self, arr):
arr ^= 2 ** 32 - 1
return arr
def apply_perspective_surf(self, surf):
self.invert_surface(surf)
data = pygame.image.tostring(surf, 'RGBA')
img = Image.fromstring('RGBA', surf.get_size(), data)
img = img.transform(img.size, self.affinestate.proj_type, self.affinestate.sample_transformation(img.size),
Image.BICUBIC)
img = img.transform(img.size, self.perspectivestate.proj_type,
self.perspectivestate.sample_transformation(img.size), Image.BICUBIC)
im = n.array(img)
# pyplot.imshow(im)
# pyplot.show()
surf = pygame.surfarray.make_surface(im[..., 0:3].swapaxes(0, 1))
self.invert_surface(surf)
return surf
def get_rect(self,w,h,angle):
halfW=w/2.0
halfH=h/2.0
#angle1=math.atan(float(h)/w)
#try:
# angle = self.extraInfo["noise_config"]["rotateAngle"]
#except Exception:
# angle=5
#random_angle=random.uniform(0,angle)
random_angle=math.radians(angle)
length=halfW*math.tan(random_angle)
#length=random.randint(-1,1)*length
point1=[0,length]
point2=[w-1,0]
point3 = [0, h+length]
point4 = [w-1, h -1]
import numpy as np
return np.float32([point1,point2,point3,point4])
def fandom_dlt_ratio(self, maxdlt, deno, orilen):
return n.random.randint(-maxdlt, maxdlt) / (1.0*deno)*orilen
def apply_perspective_arr(self, arr,pts31, filtering=Image.BICUBIC):
img = Image.fromarray(arr)
arr = n.array(img)
#tmp = sum(arr[0, :])
#if tmp != 0:
# raise ValueError('Wrong Pic')
#img = img.transform(img.size, self.affinestate.proj_type, affstate, filtering)
#img = img.transform(img.size, self.perspectivestate.proj_type, perstate, filtering)
import numpy as np
i = 0
# while i < 10000:
# i = i+1
# abc=
# print abc
maxdlt = 100
dltx0 = self.fandom_dlt_ratio( maxdlt, 1000, img.width)
dltx1 = self.fandom_dlt_ratio( maxdlt, 1000, img.width)
dltx2 = self.fandom_dlt_ratio(maxdlt, 1000, img.width)
dltx3 = self.fandom_dlt_ratio(maxdlt, 1000, img.width)
dlty0 = self.fandom_dlt_ratio(maxdlt, 1000, img.height)
dlty1 = self.fandom_dlt_ratio(maxdlt, 1000, img.height)
dlty2 = self.fandom_dlt_ratio(maxdlt, 1000, img.height)
dlty3 = self.fandom_dlt_ratio(maxdlt, 1000, img.height)
#dlty2 = self.get_rect(img.width, img.height, 5)
#dlty3 = self.get_rect(img.width, img.height, 5)
#pts3 = np.float32([ [dltx0, dlty0], [img.width*(1.0 -n.random.randint(-maxdlt,maxdlt)/1000.0) , 0], [0, img.height*(1.0- n.random.randint(-maxdlt,maxdlt)/1000.0) ], [img.width*(1.0 -n.random.randint(-maxdlt,maxdlt)/1000.0), img.height*(1.0 - n.random.rand() ] ])
if dltx0 < 0:
dltx0 = 0
if dlty0 <= 0:
dlty0 = 0
if dlty1 <= 0:
dlty1 = 0
if img.width+dltx1 < img.width:
dltx1 = 0
if img.height + dlty3 > img.height: