-
Notifications
You must be signed in to change notification settings - Fork 24
/
text_utils.py
1019 lines (880 loc) · 36.6 KB
/
text_utils.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 division
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
import os.path as osp
import random, os
import cv2
import pickle as cp
import scipy.signal as ssig
import scipy.stats as sstat
import pygame, pygame.locals
from pygame import freetype
#import Image
from PIL import Image
import math
from common import *
import string
import pdb
# random.seed(1)
def sample_weighted(p_dict):
ps = list(p_dict.keys())
#print([p_dict[p] for p in ps])
return np.random.choice(ps,p=[p_dict[p] for p in ps])
def move_bb(bbs, t):
"""
Translate the bounding-boxes in by t_x,t_y.
BB : 2x4xn
T : 2-long np.array
"""
return bbs + t[:,None,None]
def crop_safe(arr, rect, bbs=[], pad=0):
"""
ARR : arr to crop
RECT: (x,y,w,h) : area to crop to
BBS : nx4 xywh format bounding-boxes
PAD : percentage to pad
Does safe cropping. Returns the cropped rectangle and
the adjusted bounding-boxes
"""
rect = np.array(rect)
rect[:2] -= pad
rect[2:] += 2*pad
v0 = [max(0,rect[0]), max(0,rect[1])]
v1 = [min(arr.shape[0], rect[0]+rect[2]), min(arr.shape[1], rect[1]+rect[3])]
arr = arr[v0[0]:v1[0],v0[1]:v1[1],...]
if len(bbs) > 0:
for i in range(len(bbs)):
bbs[i,0] -= v0[0]
bbs[i,1] -= v0[1]
return arr, bbs
else:
return arr
def GetNumber():
num_str = ""
num_set = '0123456789'
sym_set = '.,+=-_!@#$%&'
for i in range(random.randint(1, 8)):
if random.random() < 0.85 or i <= 2:
num_str += random.choice(num_set)
else:
num_str += random.choice(sym_set)
if len(num_str) >=4 and random.random() < 0.4: break
return num_str
class BaselineState(object):
curve = lambda this, a: lambda x: a*x*x
differential = lambda this, a: lambda x: 2*a*x
a = [0.50, 0.05]
def get_sample(self):
"""
Returns the functions for the curve and differential for a and b
"""
sgn = 1.0
if np.random.rand() < 0.5:
sgn = -1
a = self.a[1]*np.random.randn() + sgn*self.a[0]
return {
'curve': self.curve(a),
'diff': self.differential(a),
}
class RenderFont(object):
"""
Outputs a rasterized font sample.
Output is a binary mask matrix cropped closesly with the font.
Also, outputs ground-truth bounding boxes and text string
"""
def __init__(self, data_dir='data'):
# distribution over the type of text:
# whether to get a single word, paragraph or a line:
self.p_text = {'WORD': 0.0,
'LINE': 0.0,
'PARA': 1.0}
## TEXT PLACEMENT PARAMETERS:
self.f_shrink = 0.90
self.max_shrink_trials = 5 # 0.9^5 ~= 0.6
# the minimum number of characters that should fit in a mask
# to define the maximum font height.
self.min_nchar = 2
# self.min_font_h = 16 #px : 0.6*12 ~ 7px <= actual minimum height
# self.max_font_h = 120 #px
self.min_font_h = 8 #px : 0.6*12 ~ 7px <= actual minimum height
self.max_font_h = 30 #px
self.p_flat = 0.6
# self.p_flat = 0.10
# curved baseline:
self.p_curved = 1.0
self.baselinestate = BaselineState()
# text-source : gets english text:
self.text_source = TextSource(min_nchar=self.min_nchar,
fn=osp.join(data_dir,'newsgroup/newsgroup.txt'))
# get font-state object:
self.font_state = FontState(data_dir)
self.StoredToPath = "aaa"
self.curCnt=0
self.colorR=0
self.colorG=0
self.colorB=0
pygame.init()
def setStoredToPath(self,spath):
self.StoredToPath = spath
return #None
def setCurCnt(self,cCnt):
self.curCnt = cCnt
return #None
def setColor(self,cR,cG,cB):
self.colorR=cR
self.colorG=cG
self.colorB=cB
return
def render_multiline(self,font,text):
"""
renders multiline TEXT on the pygame surface SURF with the
font style FONT.
A new line in text is denoted by \n, no other characters are
escaped. Other forms of white-spaces should be converted to space.
returns the updated surface, words and the character bounding boxes.
"""
# get the number of lines
lines = text.split('\n')
lengths = [len(l) for l in lines]
# font parameters:
line_spacing = font.get_sized_height() + 1
# initialize the surface to proper size:
line_bounds = font.get_rect(lines[np.argmax(lengths)])
fsize = (round(2.0*line_bounds.width), round(1.25*line_spacing*len(lines)))
#print("fsize "+str(round(2.0*line_bounds.width))+" "+str(round(1.25*line_spacing*len(lines))))
surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)
bbs = []
if random.random()>0.2:
space = font.get_rect('1')
else:
space = font.get_rect('0')
x, y = 0, 0
for l in lines:
x = 0 # carriage-return
y += line_spacing # line-feed
for ch in l: # render each character
if ch.isspace(): # just shift
x += space.width
else:
# render the character
try:
ch_bounds = font.render_to(surf, (x,y), ch)
except:
print('error on font.render_to(surf, (x,y), ch)')
ch_bounds.x = x + ch_bounds.x
ch_bounds.y = y - ch_bounds.y
x += ch_bounds.width
bbs.append(np.array(ch_bounds))
# get the union of characters for cropping:
r0 = pygame.Rect(bbs[0])
rect_union = r0.unionall(bbs)
# get the words:
words = ' '.join(text.split())
# crop the surface to fit the text:
bbs = np.array(bbs)
surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5)
surf_arr = surf_arr.swapaxes(0,1)
self.visualize_bb(surf_arr,bbs)
return surf_arr, words, bbs
# def render_multiline(self,font,text):
# """
# renders multiline TEXT on the pygame surface SURF with the
# font style FONT.
# A new line in text is denoted by \n, no other characters are
# escaped. Other forms of white-spaces should be converted to space.
# returns the updated surface, words and the character bounding boxes.
# """
# # get the number of lines
# lines = text.split('\n')
# lengths = [len(l) for l in lines]
# # font parameters:
# line_spacing = font.get_sized_height() + 1
# # initialize the surface to proper size:
# line_bounds = font.get_rect(lines[np.argmax(lengths)])
# # fsize = (round(2.0*line_bounds.width), round(1.25*line_spacing*len(lines)))
# fsize = (round(1.25*line_spacing*len(lines)), round(2.0*line_bounds.width))
# #print("fsize "+str(round(2.0*line_bounds.width))+" "+str(round(1.25*line_spacing*len(lines))))
# surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)
# bbs = []
# if random.random()>0.2:
# space = font.get_rect('1')
# else:
# space = font.get_rect('0')
# x, y = 0, 0
# for l in lines:
# y = 0 # carriage-return
# x += line_spacing # line-feed
# for ch in l: # render each character
# if ch.isspace(): # just shift
# y += space.height
# else:
# # render the character
# ch_bounds = font.render_to(surf, (x,y), ch, rotation=90)
# ch_bounds.y = y + ch_bounds.y
# ch_bounds.x = x - ch_bounds.x
# y += ch_bounds.height
# bbs.append(np.array(ch_bounds))
# # get the union of characters for cropping:
# r0 = pygame.Rect(bbs[0])
# rect_union = r0.unionall(bbs)
# # get the words:
# words = ' '.join(text.split())
# # crop the surface to fit the text:
# bbs = np.array(bbs)
# surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5)
# surf_arr = surf_arr.swapaxes(0,1)
# self.visualize_bb(surf_arr,bbs)
# return surf_arr, words, bbs
# def render_multiline(self, font, text):
# """
# renders multiline TEXT on the pygame surface SURF with the
# font style FONT.
# A new line in text is denoted by \n, no other characters are
# escaped. Other forms of white-spaces should be converted to space.
# returns the updated surface, words and the character bounding boxes.
# """
# # get the number of lines
# lines = text.split('\n')
# lengths = [len(l) for l in lines]
# # font parameters:
# line_spacing = font.get_sized_height() + 1
# # initialize the surface to proper size:
# line_bounds = font.get_rect(lines[np.argmax(lengths)])
# # vertical
# fsize = (round(1.5 * line_spacing * len(lines)), round(2.0 * line_bounds.width))
# surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)
# bbs = []
# space = font.get_rect('O')
# x, y = 0, 0
# # vertical
# for l in lines:
# # x = 0 # carriage-return
# # y += line_spacing # line-feed
# # print(l)
# y = 1.5 * space.height
# x += line_spacing
# for ch in l: # render each character
# if ch.isspace(): # just shift
# # x += space.width
# # print("is space : ", space.height)
# y += space.height
# else:
# # render the character
# # print("{} : x, y : ".format(ch), x, y)
# ch_bounds = font.render_to(surf, (x, y), ch)
# # ch_bounds.x = x + ch_bounds.x
# # print("{} : before ch_bounds : ".format(ch), ch_bounds, end='\t')
# ch_bounds.y = y + ch_bounds.y - 1.5*space.height
# ch_bounds.x = x - ch_bounds.x
# # ch_bounds.y = y - ch_bounds.y
# # print("after ch_bounds : ", ch_bounds)
# # x += ch_bounds.width
# # y += ch_bounds.height
# y += 1.25 * ch_bounds.height
# bbs.append(np.array(ch_bounds))
# # get the union of characters for cropping:
# r0 = pygame.Rect(bbs[0])
# # print("r0 : ", r0)
# rect_union = r0.unionall(bbs)
# # print("rect_union : ", rect_union, type(rect_union))
# # get the words:
# words = ' '.join(text.split())
# # crop the surface to fit the text:
# bbs = np.array(bbs)
# surf_pixels_alpha = pygame.surfarray.pixels_alpha(surf)
# surf_arr, bbs = crop_safe(surf_pixels_alpha, rect_union, bbs, pad=5)
# surf_arr = surf_arr.swapaxes(0, 1)
# self.visualize_bb(surf_arr,bbs)
# return surf_arr, words, bbs
def render_curved(self, font, word_text):
"""
use curved baseline for rendering word
"""
# print("!")
wl = len(word_text)
isword = len(word_text.split())==1
# do curved iff, the length of the word <= 10
if not isword or wl > 10 or np.random.rand() > self.p_curved:
#print('multiline rendering...')
return self.render_multiline(font, word_text)
# create the surface:
lspace = font.get_sized_height() + 1
lbound = font.get_rect(word_text)
fsize = (round(2.0*lbound.width), round(3*lspace))
surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)
# baseline state
mid_idx = wl//2
BS = self.baselinestate.get_sample()
curve = [BS['curve'](i-mid_idx) for i in range(wl)]
curve[mid_idx] = -np.sum(curve) / (wl-1)
rots = [-int(math.degrees(math.atan(BS['diff'](i-mid_idx)/(font.size/2)))) for i in range(wl)]
# print("@")
bbs = []
# place middle char
rect = font.get_rect(word_text[mid_idx])
rect.centerx = surf.get_rect().centerx
rect.centery = surf.get_rect().centery + rect.height
rect.centery += curve[mid_idx]
ch_bounds = font.render_to(surf, rect, word_text[mid_idx], rotation=rots[mid_idx])
ch_bounds.x = rect.x + ch_bounds.x
ch_bounds.y = rect.y - ch_bounds.y
mid_ch_bb = np.array(ch_bounds)
# render chars to the left and right:
last_rect = rect
ch_idx = []
for i in range(wl):
#skip the middle character
if i==mid_idx:
bbs.append(mid_ch_bb)
ch_idx.append(i)
continue
if i < mid_idx: #left-chars
i = mid_idx-1-i
elif i==mid_idx+1: #right-chars begin
last_rect = rect
ch_idx.append(i)
ch = word_text[i]
newrect = font.get_rect(ch)
newrect.y = last_rect.y
if i > mid_idx:
newrect.topleft = (last_rect.topright[0]+2, newrect.topleft[1])
else:
newrect.topright = (last_rect.topleft[0]-2, newrect.topleft[1])
newrect.centery = max(newrect.height, min(fsize[1] - newrect.height, newrect.centery + curve[i]))
try:
bbrect = font.render_to(surf, newrect, ch, rotation=rots[i])
except ValueError:
bbrect = font.render_to(surf, newrect, ch)
bbrect.x = newrect.x + bbrect.x
bbrect.y = newrect.y - bbrect.y
bbs.append(np.array(bbrect))
last_rect = newrect
# print("#")
# correct the bounding-box order:
bbs_sequence_order = [None for i in ch_idx]
for idx,i in enumerate(ch_idx):
bbs_sequence_order[i] = bbs[idx]
bbs = bbs_sequence_order
# get the union of characters for cropping:
r0 = pygame.Rect(bbs[0])
rect_union = r0.unionall(bbs)
# crop the surface to fit the text:
bbs = np.array(bbs)
surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5)
surf_arr = surf_arr.swapaxes(0,1)
#print('curved rendering...')
self.visualize_bb(surf_arr,bbs)
return surf_arr, word_text, bbs
def get_nline_nchar(self,mask_size,font_height,font_width):
"""
Returns the maximum number of lines and characters which can fit
in the MASK_SIZED image.
"""
H,W = mask_size
#print("font size"+str(font_height)+" "+str(font_width))
nline = int(np.ceil(H/(2*font_height)))
nchar = int(np.floor(W/font_width))
return nline,nchar
def place_text(self, text_arrs, back_arr, bbs):
areas = [-np.prod(ta.shape) for ta in text_arrs]
order = np.argsort(areas)
locs = [None for i in range(len(text_arrs))]
out_arr = np.zeros_like(back_arr)
for i in order:
ba = np.clip(back_arr.copy().astype(np.float), 0, 255)
ta = np.clip(text_arrs[i].copy().astype(np.float), 0, 255)
ba[ba > 127] = 1e8
intersect = ssig.fftconvolve(ba,ta[::-1,::-1],mode='valid')
safemask = intersect < 1e8
if not np.any(safemask): # no collision-free position:
#warn("COLLISION!!!")
return back_arr,locs[:i],bbs[:i],order[:i]
minloc = np.transpose(np.nonzero(safemask))
loc = minloc[np.random.choice(minloc.shape[0]),:]
locs[i] = loc
# update the bounding-boxes:
bbs[i] = move_bb(bbs[i],loc[::-1])
# blit the text onto the canvas
w,h = text_arrs[i].shape
out_arr[loc[0]:loc[0]+w,loc[1]:loc[1]+h] += text_arrs[i]
return out_arr, locs, bbs, order
def robust_HW(self,mask):
m = mask.copy()
m = (~mask).astype('float')/255
rH = np.median(np.sum(m,axis=0))
rW = np.median(np.sum(m,axis=1))
return rH,rW
def sample_font_height_px(self,h_min,h_max):
if random.random() < self.p_flat:
rnd = random.random()
else:
rnd = np.random.beta(2.0,2.0)
h_range = h_max - h_min
prob_small = random.random()
if prob_small<0.2:
h_range = h_range / 4.0
elif prob_small<0.5:
h_range = h_range / 2.0
f_h = np.floor(h_min + h_range*rnd)
return f_h
def bb_xywh2coords(self,bbs):
"""
Takes an nx4 bounding-box matrix specified in x,y,w,h
format and outputs a 2x4xn bb-matrix, (4 vertices per bb).
"""
n,_ = bbs.shape
coords = np.zeros((2,4,n))
for i in range(n):
coords[:,:,i] = bbs[i,:2][:,None]
coords[0,1,i] += bbs[i,2]
coords[:,2,i] += bbs[i,2:4]
coords[1,3,i] += bbs[i,3]
return coords
def render_sample(self,font,mask):
"""
Places text in the "collision-free" region as indicated
in the mask -- 255 for unsafe, 0 for safe.
The text is rendered using FONT, the text content is TEXT.
"""
#H,W = mask.shape
# np.random.seed(3)
H,W = self.robust_HW(mask)
f_asp = self.font_state.get_aspect_ratio(font)
# find the maximum height in pixels:
max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))
max_font_h = min(max_font_h, self.max_font_h)
if max_font_h < self.min_font_h: # not possible to place any text here
return #None
# let's just place one text-instance for now
## TODO : change this to allow multiple text instances?
i = 0
while i < self.max_shrink_trials and max_font_h > self.min_font_h:
# if i > 0:
# print colorize(Color.BLUE, "shrinkage trial : %d"%i, True)
# sample a random font-height:
f_h_px = self.sample_font_height_px(self.min_font_h, max_font_h)
#print "font-height : %.2f (min: %.2f, max: %.2f)"%(f_h_px, self.min_font_h,max_font_h)
# convert from pixel-height to font-point-size:
f_h = self.font_state.get_font_size(font, f_h_px)
# update for the loop
max_font_h = f_h_px
i += 1
font.size = f_h # set the font-size
# compute the max-number of lines/chars-per-line:
nline,nchar = self.get_nline_nchar(mask.shape[:2],f_h,f_h*f_asp)
#print " > nline = %d, nchar = %d"%(nline, nchar)
assert nline >= 1 and nchar >= self.min_nchar
# sample text:
text_type = sample_weighted(self.p_text)
text = self.text_source.sample(nline,nchar,text_type)
if len(text)==0 or np.any([len(line)==0 for line in text]):
continue
#print colorize(Color.GREEN, text)
# render the text:
txt_arr,txt,bb = self.render_curved(font, text)
bb = self.bb_xywh2coords(bb)
# make sure that the text-array is not bigger than mask array:
if np.any(np.r_[txt_arr.shape[:2]] > np.r_[mask.shape[:2]]):
#warn("text-array is bigger than mask")
continue
# position the text within the mask:
text_mask,loc,bb, _ = self.place_text([txt_arr], mask, [bb])
if len(loc) > 0:#successful in placing the text collision-free:
return text_mask,loc[0],bb[0],text
return #None
#@author:brawie song
def getRandomTextImg(self,maskh,maskw):
# np.random.seed(3)
#print("Coming in GRTI")
loop_count = 0
while True:
loop_count += 1
if loop_count > 10:
return "", None
try:
font = self.font_state.sample()
font = self.font_state.init_font(font)
break
except:
print("font failed. retry...")
continue
#
f_asp = self.font_state.get_aspect_ratio(font)
#print("***")
H=maskh
W=maskw
'''
randFlag = random.random()
if randFlag<0.3:
W*=15
elif randFlag<0.6:
W*=6
else:
W*=4
H*=2
'''
max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))
max_font_h = min(max_font_h, self.max_font_h)
#if max_font_h < self.min_font_h: # not possible to place any text here
#return #None
while max_font_h < self.min_font_h:
H+=2
W+=2
max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))
max_font_h = min(max_font_h, self.max_font_h)
#print("***")
# sample a random font-height:
f_h_px = self.sample_font_height_px(self.min_font_h, max_font_h)
#print "font-height : %.2f (min: %.2f, max: %.2f)"%(f_h_px, self.min_font_h,max_font_h)
# convert from pixel-height to font-point-size:
f_h = self.font_state.get_font_size(font, f_h_px)
# print("get return")
while(f_h==-1):
#print("*")
font = self.font_state.sample()
font = self.font_state.init_font(font)
f_asp = self.font_state.get_aspect_ratio(font)
max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))
max_font_h = min(max_font_h, self.max_font_h)
#if max_font_h < self.min_font_h: # not possible to place any text here
#return #None
while max_font_h < self.min_font_h:
H+=2
W+=2
max_font_h = min(0.9*H, (1/f_asp)*W/(self.min_nchar+1))
max_font_h = min(max_font_h, self.max_font_h)
#print("***")
# sample a random font-height:
f_h_px = self.sample_font_height_px(self.min_font_h, max_font_h)
#print "font-height : %.2f (min: %.2f, max: %.2f)"%(f_h_px, self.min_font_h,max_font_h)
# convert from pixel-height to font-point-size:
f_h = self.font_state.get_font_size(font, f_h_px)
#print("***"+str(maskh)+" "+str(maskw))
# compute the max-number of lines/chars-per-line:
nline,nchar = self.get_nline_nchar([H,W],f_h,f_h*f_asp)
#print " > nline = %d, nchar = %d"%(nline, nchar)
#assert nline >= 1 and nchar >= self.min_nchar
if (nline<1):
nline = 1
if (nchar<self.min_nchar):
nchar = self.min_nchar
text_type = sample_weighted(self.p_text)
text = ''
try_times = 0
while len(text)==0:
text = self.text_source.sample(nline,nchar,text_type)
try_times += 1
if try_times>20:
break
# print("hahaha==="+str(maskh)+" "+str(maskw))
# print len(text)
# print(text)
#print("=========")
if(len(text)==0):
#
nline=1
nchar*=2
text = self.text_source.sample(nline,nchar,text_type)
text = self.text_source.sample(nline,nchar,text_type)
# print("hahaha==="+str(maskh)+" "+str(maskw))
# print len(text)
# print(text)
# print("=========")
#
#if len(text)==0 or np.any([len(line)==0 for line in text]):
# return #None
txt_arr,txt,bb = self.render_curved(font, text)
#print(bb)
#bb = self.bb_xywh2coords(bb)
#print(bb)
return txt,bb
def visualize_bb(self, text_arr, bbs):
ta = text_arr.copy()
#for r in bbs:
# cv2.rectangle(ta, (r[0],r[1]), (r[0]+r[2],r[1]+r[3]), color=128, thickness=1)
#print(ta.shape[0])
#print(ta.shape[1])
#print(ta.shape[2])
emptyImage=np.zeros((ta.shape[0],ta.shape[1],4), np.uint8)
for i in range(ta.shape[0]):
for j in range(ta.shape[1]):
#print(ta[i][j])
emptyImage[i][j][0]=int(self.colorB*(ta[i][j]/255.0)) #98.0;#115.0;#ta[i][j];
emptyImage[i][j][1]=int(self.colorG*(ta[i][j]/255.0)) #108.8#135.0;#ta[i][j];
emptyImage[i][j][2]=int(self.colorR*(ta[i][j]/255.0)) #100.6#139.0;#ta[i][j];
if ta[i][j]==0:
emptyImage[i][j][3]=0
else:
emptyImage[i][j][3]=255
overall_trans = np.random.uniform(0.70, 0.90)
pointwise_trans = np.random.uniform(0.95, 1.05, size=ta.shape) if random.random() < 0.3 else 1.0
cv2.imwrite(self.StoredToPath+'fore_text'+str(self.curCnt)+'.png',emptyImage)
cv2.imwrite(self.StoredToPath+'back_text'+str(self.curCnt)+'.png',(ta*np.clip(overall_trans*pointwise_trans, a_min=0.4, a_max=1.0)).astype(np.uint8))
#plt.imshow(ta)#,cmap='gray')
#plt.show()
class FontState(object):
"""
Defines the random state of the font rendering
"""
size = [50, 10] # normal dist mean, std
underline = 0.05
strong = 0.5
oblique = 0.2 # 一种斜体
wide = 0.5
strength = [0.05, 0.1] # 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 ## don't recapitalize : retain the capitalization of the lexicon
capsmode = [str.lower, str.upper, str.capitalize] # lower case, upper case, proper noun
curved = 0.2
random_kerning = 0.2
random_kerning_amount = 0.1
def __init__(self, data_dir='data'):
char_freq_path = osp.join(data_dir, 'models/char_freq.cp')
font_model_path = osp.join(data_dir, 'models/font_px2pt.cp')
class fakefreq(object):
def __init__(self):
pass
def __getitem__(self, index):
return 1. / len(string.printable)
def keys(self):
for c in string.printable:
yield c
def values(self):
for c in string.printable:
yield 1. / len(string.printable)
# get character-frequencies in the English language:
with open(char_freq_path,'rb') as f:
self.char_freq = fakefreq()#cp.load(f)
# get the model to convert from pixel to font pt size:
with open(font_model_path,'rb') as f:
#self.font_model = cp.load(f)
self.font_model = [10] * 10000
# get the names of fonts to use:
self.FONT_LIST = osp.join(data_dir, 'fonts/fontlist_sub.txt') # fontlist_sub has more ...
self.fonts = [os.path.join(data_dir,'fonts',f.strip()) for f in open(self.FONT_LIST).readlines()]
print(f"=== === === {len(self.fonts)} types of fonts found === === === ")
def get_aspect_ratio(self, font, size=None):
"""
Returns the median aspect ratio of each character of the font.
"""
if size is None:
size = 12 # doesn't matter as we take the RATIO
chars = ''.join(self.char_freq.keys())
w = np.array(self.char_freq.values())
# get the [height,width] of each character:
try:
sizes = font.get_metrics(chars,size)
good_idx = [i for i in range(len(sizes)) if sizes[i] is not None]
sizes,w = [sizes[i] for i in good_idx], w[good_idx]
sizes = np.array(sizes).astype('float')[:,[3,4]]
r = np.abs(sizes[:,1]/sizes[:,0]) # width/height
good = np.isfinite(r)
r = r[good]
w = w[good]
w /= np.sum(w)
r_avg = np.sum(w*r)
return r_avg
except:
return 1.0
def get_font_size(self, font, font_size_px):
"""
Returns the font-size which corresponds to FONT_SIZE_PX pixels font height.
"""
# print(font)
# print(font.name)
if font.name in self.font_model:
m = self.font_model[font.name]
return m[0]*font_size_px + m[1] #linear model
else:
return 10;
def sample(self):
"""
Samples from the font state distribution
"""
selected_id = int(np.random.randint(0, len(self.fonts)))
selected_font = self.fonts[selected_id]
# pdb.set_trace()
print(selected_font.split('/')[-1])
return {
'font': selected_font,
'size': self.size[1]*np.random.randn() + self.size[0],
'underline': np.random.rand() < self.underline,
'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1]*np.random.randn() + self.underline_adjustment[0])),
'strong': np.random.rand() < self.strong,
'oblique': np.random.rand() < self.oblique,
'strength': (self.strength[1] - self.strength[0])*np.random.rand() + self.strength[0],
'char_spacing': int(self.kerning[3]*(np.random.beta(self.kerning[0], self.kerning[1])) + self.kerning[2]),
'border': np.random.rand() < self.border,
'random_caps': np.random.rand() < self.random_caps,
'capsmode': random.choice(self.capsmode),
'curved': np.random.rand() < self.curved,
'random_kerning': np.random.rand() < self.random_kerning,
'random_kerning_amount': self.random_kerning_amount,
}
def init_font(self,fs):
"""
Initializes a pygame font.
FS : font-state sample
"""
font = freetype.Font(fs['font'], size=fs['size'])
font.underline = fs['underline']
font.underline_adjustment = fs['underline_adjustment']
font.strong = fs['strong']
font.oblique = fs['oblique']
font.strength = fs['strength']
char_spacing = fs['char_spacing']
font.antialiased = True
font.origin = True
return font
class TextSource(object):
"""
Provides text for words, paragraphs, sentences.
"""
def __init__(self, min_nchar, fn):
"""
TXT_FN : path to file containing text data.
"""
self.min_nchar = min_nchar
self.fdict = {'WORD':self.sample_word,
'LINE':self.sample_line,
'PARA':self.sample_para}
with open(fn,'r') as f:
txt = [l.strip() for l in f.readlines()]
self.vocab = list(set(' '.join(txt).split(' ')))
self.vocab_short = list(filter(lambda x:len(x)<=5, self.vocab))
self.txt = [ ]
for _ in range(len(txt)):
line = []
for _ in range(random.randint(5, 10)):
line.append(random.choice(self.vocab))
self.txt.append(' '.join(line))
# self.txt = [l.strip() for l in f.readlines()]
# self.txt = [l.split(' ') for l in self.txt]
# for i in range(len(self.txt)):
# random.shuffle(self.txt[i])
# self.txt[i] = ' '.join(self.txt[i])
# random.shuffle(self.txt)
# distribution over line/words for LINE/PARA:
self.p_line_nline = np.array([0.85, 0.10, 0.05])
self.p_line_nword = [4,3,12] # normal: (mu, std)
# self.p_line_nword = [2,1.5,6] # normal: (mu, std)
self.p_para_nline = [1.0,1.0]#[1.7,3.0] # beta: (a, b), max_nline
self.p_para_nword = [1.7,3.0,10] # beta: (a,b), max_nword
# probability to center-align a paragraph:
self.center_para = 0.5
def check_symb_frac(self, txt, f=0.35):
"""
T/F return : T iff fraction of symbol/special-charcters in
txt is less than or equal to f (default=0.25).
"""
return np.sum([not ch.isalnum() for ch in txt])/(len(txt)+0.0) <= f
def is_good(self, txt, f=0.35):
"""
T/F return : T iff the lines in txt (a list of txt lines)
are "valid".
A given line l is valid iff:
1. It is not empty.
2. symbol_fraction > f
3. Has at-least self.min_nchar characters
4. Not all characters are i,x,0,O,-
"""
def is_txt(l):
char_ex = ['i','I','o','O','0','-']
chs = [ch in char_ex for ch in l]
return not np.all(chs)
return [ (len(l)> self.min_nchar
and self.check_symb_frac(l,f)
and is_txt(l)) for l in txt ]
def center_align(self, lines):
"""
PADS lines with space to center align them
lines : list of text-lines.
"""
ls = [len(l) for l in lines]
max_l = max(ls)
for i in range(len(lines)):
l = lines[i].strip()
dl = max_l-ls[i]
lspace = dl//2
rspace = dl-lspace
lines[i] = ' '*lspace+l+' '*rspace
return lines
def get_lines(self, nline, nword, nchar_max, f=0.35, niter=100):
def h_lines(niter=100):
lines = ['']
iter = 0
while not np.all(self.is_good(lines,f)) and iter < niter:
iter += 1
line_start = np.random.choice(len(self.txt)-nline)
lines = [' '.join([random.choice([random.choice(self.vocab), random.choice(self.vocab_short)+' '+random.choice(self.vocab_short)]) if random.random() < 0.90 else GetNumber() for _ in range(random.randint(1, 5))]) for i in range(nline)]
return lines
lines = ['']
iter = 0
while not np.all(self.is_good(lines,f)) and iter < niter:
iter += 1
lines = h_lines(niter=100)
# get words per line:
nline = len(lines)
for i in range(nline):
words = lines[i].split()
dw = len(words)-nword[i]
if dw > 0:
first_word_index = random.choice(range(dw+1))
lines[i] = ' '.join(words[first_word_index:first_word_index+nword[i]])
while len(lines[i]) > nchar_max: #chop-off characters from end:
if not np.any([ch.isspace() for ch in lines[i]]):
lines[i] = ''
else:
lines[i] = lines[i][:len(lines[i])-lines[i][::-1].find(' ')].strip()
if not np.all(self.is_good(lines,f)):
return #None
else:
return lines
def sample(self, nline_max,nchar_max,kind='WORD'):
return self.fdict[kind](nline_max,nchar_max)
def sample_word(self,nline_max,nchar_max,niter=100):
rand_line = self.txt[np.random.choice(len(self.txt))]
words = rand_line.split()
rand_word = random.choice(words)
iter = 0
while iter < niter and (not self.is_good([rand_word])[0] or len(rand_word)>nchar_max):
rand_line = self.txt[np.random.choice(len(self.txt))]
words = rand_line.split()
rand_word = random.choice(words)
iter += 1
if not self.is_good([rand_word])[0] or len(rand_word)>nchar_max:
return []
else:
return rand_word
def sample_line(self,nline_max,nchar_max):
nline = nline_max+1
while nline > nline_max:
nline = np.random.choice([1,2,3], p=self.p_line_nline)
# get number of words:
nword = [self.p_line_nword[2]*sstat.beta.rvs(a=self.p_line_nword[0], b=self.p_line_nword[1])
for _ in range(nline)]
nword = [max(1,int(np.ceil(n))) for n in nword]
lines = self.get_lines(nline, nword, nchar_max, f=0.35)
if lines is not None:
return '\n'.join(lines)
else:
return []