-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhwr_data.py
More file actions
1237 lines (1114 loc) · 128 KB
/
Copy pathhwr_data.py
File metadata and controls
1237 lines (1114 loc) · 128 KB
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
import res.dictionary as dictionary
import os
from os import walk
import numpy as np
import struct
from PIL import Image,ImageDraw
import pickle
import re
import time
import pandas as pd
import ast
import argparse
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib
import cv2
from imgaug import augmenters as iaa
import sys
RDM = np.random
class DataGenerator:
def __init__(self,hwdb_trn_dir,hwdb_tst_dir,hcl_dir,background_dir,default_bg_path,corpus_path,off_corpus,hcl_ratio,img_height,img_width,const_char_num=False,max_char_num=12,line_mix=False,test_mode=False,true_write_type=True,true_write_type_ratio=1):
self.char_dict = dict(dictionary.char_dict)
self.char_dict_reverse = {v: k for k, v in self.char_dict.items()}
## 第一次构建HWDB
self.hwdb_trn_dir = hwdb_trn_dir # HWDB train 资源目录(第一使用构建HWDB生成)
self.hwdb_tst_dir = hwdb_tst_dir # HWDB test 资源目录(第一使用构建HWDB生成)
self.hcl_dir = hcl_dir
self.background_dir = background_dir
self.default_bg_path = default_bg_path
self.corpus_path = corpus_path
self.hcl_ratio = hcl_ratio
self.img_height = img_height
self.img_width = img_width
self.const_char_num = const_char_num
self.max_char_num = max_char_num
self.line_mix=line_mix
self.off_corpus = off_corpus
self.test_mode = test_mode
self.true_write_type = true_write_type
self.temp_true_type = self.true_write_type
self.true_write_type_ratio = true_write_type_ratio
print("DataGenerator init...")
print("---hwdb_trn_dir:", self.hwdb_trn_dir)
print("---hwdb_tst_dir:", self.hwdb_tst_dir)
print("---hcl_dir:", self.hcl_dir)
print("---background_dir:", self.background_dir)
print("---default_bg_path:", self.default_bg_path)
print("---corpus_path:", self.corpus_path)
print("---hcl_ratio:", self.hcl_ratio)
print("---img_height:", self.img_height)
print("---img_width:", self.img_width)
print("---const_char_num:", self.const_char_num)
print("---max_char_num:", self.max_char_num)
print("---line_mix:", self.line_mix)
print("---off_corpus:", self.off_corpus)
print("---true_write_type:", self.true_write_type)
print("---true_write_type_ratio:", self.true_write_type_ratio)
print("---test_mode:", self.test_mode)
self.which = ""
self.gen_data_num = 0
self.data_dir = ""
self.data_augment = ""
self.temp_data_augment = ""
def gen_single_character_from_HWDB(self,init_hwdb_trn_dir,init_hwdb_tst_dir):
'''
获取单张图片数据集
HWDB训练数据集路径train_data_dir
HWDB测试数据集路径test_data_dir
:return:
'''
train_counter = 0
test_counter = 0
print("gen_single_character_from_HWDB--第一次需要构建HWDB")
train_data_dir = init_hwdb_trn_dir
test_data_dir = init_hwdb_tst_dir
train_save_path = self.hwdb_trn_dir
test_save_path = self.hwdb_tst_dir
if not os.path.exists(train_save_path):
os.makedirs(train_save_path)
if not os.path.exists(test_save_path):
os.makedirs(test_save_path)
for image, tagcode in self._read_from_gnt_dir(gnt_dir=train_data_dir):
tagcode_unicode = struct.pack('>H', tagcode).decode('gb2312')
im = Image.fromarray(image)
# %0.5d
dir_name = os.path.join(train_save_path ,'%d' % self.char_dict[tagcode_unicode])
if not os.path.exists(dir_name):
os.mkdir(dir_name)
im.convert('RGB').save(os.path.join(dir_name ,str(train_counter) + '.png'))
print("train_counter=", train_counter)
train_counter += 1
if is_test:
if train_counter > 10240:
break
# 0-897757
for image, tagcode in self._read_from_gnt_dir(gnt_dir=test_data_dir):
tagcode_unicode = struct.pack('>H', tagcode).decode('gb2312')
im = Image.fromarray(image)
dir_name = os.path.join(test_save_path , '%d' % self.char_dict[tagcode_unicode])
if not os.path.exists(dir_name):
os.mkdir(dir_name)
im.convert('RGB').save(os.path.join(dir_name , str(test_counter) + '.png'))
print("test_counter=", test_counter)
test_counter += 1
if is_test:
if test_counter > 10240:
break
# 0-223990
print("gen_single_character_from_HWDB--构建HWDB完成")
def _read_from_gnt_dir(self, gnt_dir):
'''
获取HWDB1.1trn_gnt和HWDB1.1tst_gnt的图片数据
:param gnt_dir:gnt路径
:return:image, tagcode
'''
def one_file(f):
header_size = 10
while True:
header = np.fromfile(f, dtype='uint8', count=header_size)
if not header.size: break
sample_size = header[0] + (header[1] << 8) + (header[2] << 16) + (header[3] << 24)
tagcode = header[5] + (header[4] << 8)
width = header[6] + (header[7] << 8)
height = header[8] + (header[9] << 8)
if header_size + width * height != sample_size:
break
image = np.fromfile(f, dtype='uint8', count=width * height).reshape((height, width))
yield image, tagcode
for file_name in os.listdir(gnt_dir):
if file_name.endswith('.gnt'):
file_path = os.path.join(gnt_dir, file_name)
with open(file_path, 'rb') as f:
for image, tagcode in one_file(f):
yield image, tagcode
def _get_root_dir_file(self, file_dir):
'''
遍历文件路径
:param file_dir:
:return:
'''
for root, dirs, files in walk(file_dir):
return root, dirs, files
def _normalizer_image(self, img_path):
img = cv2.imread(img_path, 0)
ar = np.array(img)
max_width = 568
# for hcl max 15 cha width = 484
shape_offset = (max_width - ar.shape[1])
# BLACK = [0,0,0]
img = cv2.copyMakeBorder(img, 0, 0, shape_offset, 0, cv2.BORDER_CONSTANT, value=[255, 255, 255])
# 根据需求再改
return img
def _get_scrapy_random_text(self):
'''
从爬虫获取的语料库选取文本数据
:return:
'''
text_dict_path = self.corpus_path
text_dict = {}
with open(text_dict_path, 'r', encoding='utf-8') as f1:
text_dict = eval(f1.read())
return text_dict
def _trans_augment_parameter(self, aug):
"""
line单行数据增强: l-画线; p-仿射变换; b-模糊(高斯、均匀、中值中随机); n-噪声(高斯噪声、弹性变换中随机); e-(浮雕、对比度中随机); c-像素(Dropout、加减、乘除中随机).
char单字符数据增强: m-单字符随机上下; r-单字符随机大小; a-单字符随机倾斜
"""
aug_str = ""
if aug.find("l")>=0:
aug_str += "-画线"
if aug.find("p")>=0:
aug_str += "-仿射变换"
if aug.find("b")>=0:
aug_str += "-模糊(高斯、均匀、中值中随机)"
if aug.find("n")>=0:
aug_str += "-噪声(高斯噪声、弹性变换中随机)"
if aug.find("e")>=0:
aug_str += "-浮雕、对比度中随机"
if aug.find("c")>=0:
aug_str += "-像素(Dropout、加减、乘除中随机)"
if aug.find("m")>=0:
aug_str += "-单字符随机上下"
if aug.find("r")>=0:
aug_str += "-单字符随机大小"
if aug.find("a")>=0:
aug_str += "-单字符随机倾斜"
if aug.find("g")>=0:
aug_str += "-背景"
# if aug.find("0")>=0:
# aug_str += "-单字符真实化"
return aug_str
def _show_image(self,image_list,label_list,filename="test_mode"):
# if image.shape[2] ==1:
# image = np.squeeze(image,axis=2)
if len(image_list)==1:
image = image_list[0]
image_label = label_list[0]
f = plt.figure()
ax = f.add_subplot(111)
zhfont = matplotlib.font_manager.FontProperties(
fname="/Library/Fonts/Songti.ttc") # 字体
ax.text(0.1, 0.9, image_label, ha='center', va='center',
transform=ax.transAxes, fontproperties=zhfont)
plt.imshow(image)
if self.test_mode:
img_name = image_label + '.png'
# save_addr = img_gen_dir_path + '/' + img_name
save_addr = os.path.join(self.gen_image_dir, img_name)
# print(save_addr)
plt.savefig(save_addr)
plt.show()
elif len(image_list)==2:
# img_org,img_aug = image_list[0],image_list[1]
# label_org, label_aug = label_list[0], label_list[1]
# f = plt.figure()
zhfont = matplotlib.font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc") # 字体
# 行、列、索引
for i in range(len(image_list)):
# ax = f.add_subplot(211)
# ax.text(0.1, 0.9, image_label, ha='center', va='center',transform=ax.transAxes, fontproperties=zhfont)
# plt.imshow(image)
plt.subplot(len(image_list), 1, i + 1)
plt.subplots_adjust(bottom=0.1,top=0.9,wspace=0.01, hspace=0.01)
plt.imshow(image_list[i])
plt.title(label_list[i], fontsize=8,fontproperties=zhfont)
plt.xticks([])
plt.yticks([])
if self.test_mode:
img_name = filename + '.png'
# save_addr = img_gen_dir_path + '/' + img_name
save_addr = os.path.join(self.gen_image_dir, img_name)
# print(save_addr)
plt.savefig(save_addr)
plt.show()
def _read_data_from_res(self, path,mode="None"):
if mode == "Image":
try:
image = Image.open(path)
return image
except FileNotFoundError:
print("Error, No such file or directory:",path)
sys.exit(1)
else:
print("Error, wrong mode :", mode)
return None
def _get_char_img(self, char,char_type="HWDB"):
'''
生成单字图片
:param char:
:return: char_img
'''
# hcl
# xx001-xx700 训练集
# hh001-hh300 测试集
char_dir = str(self.char_dict[char])
## 字符图片矫正,
# 替换HCL里的 一 为 HWDB中的一
if char == "一":
char = '一'
# print("矫正,char:",char)
if self.which == 'test':
char_dir, _, char_file = self._get_root_dir_file(os.path.join(self.hwdb_tst_dir, char_dir))
else:
char_dir, _, char_file = self._get_root_dir_file(os.path.join(self.hwdb_trn_dir, char_dir))
char_path = os.path.join(char_dir, RDM.choice(char_file))
# print("get_char_img--train--HCL,char_dir:", char_dir)
# index = RDM.randint(1, 701)
# index = str(index).zfill(3)
# # char_path = hcl_char_img_root+'/xx' + index + '/xx' + index + '_' + char + '.png'
# char_path = os.path.join(self.hcl_dir, "xx" + index, "xx" + index + '_' + char + '.png')
char_type="HWDB"
else:
if self.line_mix:
## 根据预先设置的hcl ration 来源比例,随机个数字,数字小于threshold,就从HCL取,否则从HWDB取
threshold = 1000 * self.hcl_ratio
rdm = RDM.randint(0, 999)
if rdm>=threshold:
char_type = "HWDB"
else:
char_type = "HCL"
if self.which == 'train':
if char_type=="HWDB":
# print("get_char_img--train--HWDB,char_dir:", char_dir)
# char_dir, _, char_file = self.get_root_dir_file(hwdb_train_char_img_root + '/' + char_dir)
char_dir, _, char_file = self._get_root_dir_file(os.path.join(self.hwdb_trn_dir,char_dir))
# char_path = char_dir + '/' + RDM.choice(char_file)
if not self.test_mode:
char_path = os.path.join(char_dir, RDM.choice(char_file))
else:
char_path = os.path.join(char_dir, char_file[10])
else:
# print("get_char_img--train--HCL,char_dir:", char_dir)
if not self.test_mode:
index = RDM.randint(1, 701)
index = str(index).zfill(3)
# char_path = hcl_char_img_root+'/xx' + index + '/xx' + index + '_' + char + '.png'
char_path = os.path.join(self.hcl_dir, "xx" + index, "xx" + index + '_' + char + '.png')
else:
index = 256
index = str(index).zfill(3)
char_path = os.path.join(self.hcl_dir,"xx"+index,"xx"+index+'_' + char + '.png')
elif self.which == 'test':
if char_type=="HWDB":
# print("get_char_img--test--HWDB,char_dir:", char_dir)
# char_dir, _, char_file = self.get_root_dir_file('./data/train' + '/' + char_dir)
char_dir, _, char_file = self._get_root_dir_file(os.path.join(self.hwdb_tst_dir,char_dir))
# char_path = char_dir + '/' + RDM.choice(char_file)
char_path = os.path.join(char_dir, RDM.choice(char_file))
else:
# print("get_char_img--test--HCL,char_dir:", char_dir)
index = RDM.randint(1, 301)
index = str(index).zfill(3)
# char_path = '/Users/xbb1973/PycharmProjects/res/hcl_writer_rgba/xx' + index + '/xx' + index + '_' + char + '.png'
char_path = os.path.join(self.hcl_dir, "xx" + index, "xx" + index + '_' + char + '.png')
elif self.which == 'valid':
if char_type=="HWDB":
# print("get_char_img--valid--HWDB,char_dir:", char_dir)
char_dir, _, char_file = self._get_root_dir_file(os.path.join(self.hwdb_trn_dir,char_dir))
char_path = os.path.join(char_dir,RDM.choice(char_file))
else:
# print("get_char_img--valid--HCL,char_dir:", char_dir)
index = RDM.randint(1, 701)
index = str(index).zfill(3)
# char_path = hcl_char_img_root+'/xx' + index + '/xx' + index + '_' + char + '.png'
char_path = os.path.join(self.hcl_dir, "xx" + index, "xx" + index + '_' + char + '.png')
else:
print("Error,get_char_img-Unknown which:",self.which)
exit(0)
# print(char_path)
# char_img = Image.open(char_path)
char_img = self._read_data_from_res(path=char_path,mode="Image")
if char_type=="HWDB" and self.temp_data_augment.find("g")>=0: ## 去除HWDB的白色背景
char_img = char_img.convert("RGBA")
pixdata = char_img.load()
for y in range(char_img.size[1]):
for x in range(char_img.size[0]):
if pixdata[x, y][0] > 220 and pixdata[x, y][1] > 220 and pixdata[x, y][2] > 220 and pixdata[x, y][3] > 220:
pixdata[x, y] = (255, 255, 255, 0)
# img_height = char_img.height
# img_width = char_img.width
# print("char_img.height=", img_height," , char_img.width=",img_width)
# test_image = np.array(char_img)
# # test_image[:,:,3]=0
# # HCL.shape=(64, 64, 4)
# print("test_image.shape=",test_image.shape)
# str_img = Image.new('RGBA',
# (img_width, img_height),
# (255, 255, 255, 0))
# print("test_image[:,:,3]=",test_image[:,:,3])
# test_image[:, :, 3] = 0
# char_img = Image.fromarray(test_image)
# char_img = char_img.convert("RGBA")
# r, g, b, a = char_img.split()
# char_img.paste(char_img, (0, 0), mask=a)
# img = np.array(char_img)
# img[:,:,3] = 126
# print("char_img.shape:",img.shape)
# char_img = Image.fromarray(img,mode="RGBA")
char_size = int(self.img_height - 1)
if char_img.height > char_img.width:
size_rate = char_size / char_img.height
else:
size_rate = char_size / char_img.width
char_img = char_img.resize(
(int(char_img.width * size_rate), int(char_img.height * size_rate)))
# 拼接RGBA文件需要原图片的alph通道提取出的mask
background = Image.new('RGBA', (int(char_img.width), char_img.height),
(255, 255, 255, 0))
Image.isImageType('RGBA')
try:
r, g, b, alph = char_img.split()
background.paste(char_img, mask=alph)
except:
background.paste(char_img)
return background,char_type
def _get_str_img(self, str_gen):
'''
生成文本行图片
:param str_gen:
:return: str_img
'''
# width=字符串长度*2*self.height*2
# str_img_width = int(len(str_gen) * (2)) * self.height * 2
str_img_width = len(str_gen) * self.img_height + (len(str_gen) - 1) * self.chars_gap_width
if len(str_gen) <= 4:
str_img_width+= (self.img_height//2)
str_img_height = self.img_height
str_img = Image.new('RGBA',
(str_img_width, str_img_height),
(255, 255, 255, 0))
str_img_aug = str_img.copy()
if self.img_width>=100:
bg_width = self.img_width
else:
bg_width = len(str_gen) * self.img_height + (len(str_gen) - 1) * self.chars_gap_width
bg_height = self.img_height
# print("-------str_img_width=",str_img_width)
## 背景处理
if not self.test_mode: ## 正常模式
if self.which=="train":
if self.temp_data_augment.find("g") >= 0:
bg_filename_list = os.listdir(self.background_dir)
# print("get_str_img---,bg_filename_list:",bg_filename_list)
bg_filename = RDM.choice(bg_filename_list)
back = self._read_data_from_res(path=os.path.join(self.background_dir, bg_filename),mode="Image")
# back = Image.open(os.path.join(self.background_dir, bg_filename))
else:
# 指定白色背景
# bg_filename = str(back_index) + '.png'
back = self._read_data_from_res(path=self.default_bg_path, mode="Image")
# back = Image.open(self.default_bg_path)
# default_bg_path
# print("get_str_img---,bg_filename:", bg_filename)
# back = Image.open(os.path.join(self.background_dir, bg_filename))
## 从背景图片中随机截取背景区域
back = back.resize((back.width +bg_width+6,back.height + bg_height+6))
bg_rdm_height = RDM.randint(5,back.height - bg_height-6)
bg_rdm_width = RDM.randint(5,back.width - bg_width-6)
# crop(x1,y1,x2,y2) x-width,y-height
back = back.crop((bg_rdm_width, bg_rdm_height, bg_rdm_width+bg_width, bg_rdm_height+bg_height))
# print("-------back.size=",back.size)
else:
# 非训练集指定白色背景
# back_index = 11
# back_filename = str(back_index) + '.png'
# back = Image.open(os.path.join(self.background_dir, back_filename))
back = self._read_data_from_res(path=self.default_bg_path, mode="Image")
bg_rdm_height = RDM.randint(5, back.height - bg_height - 6)
bg_rdm_width = RDM.randint(5, back.width - bg_width - 6)
# crop(x1,y1,x2,y2) x-width,y-height
back = back.crop(
(bg_rdm_width, bg_rdm_height, bg_rdm_width + bg_width, bg_rdm_height + bg_height))
# print("-------back.size=", back.size)
back_aug = back.crop()
else: ## test_mode 测试模式
if self.temp_data_augment.find("g") >= 0:
bg_filename_list = os.listdir(self.background_dir)
# print("get_str_img---,bg_filename_list:",bg_filename_list)
bg_filename = RDM.choice(bg_filename_list)
back_aug = self._read_data_from_res(path=os.path.join(self.background_dir, bg_filename), mode="Image")
else:
# 指定白色背景
# back_index = 11
# bg_filename = str(back_index) + '.png'
back_aug = self._read_data_from_res(path=self.default_bg_path, mode="Image")
# back_aug = Image.open(os.path.join(self.background_dir, bg_filename))
## 从背景图片中随机截取背景区域
back_aug = back_aug.resize((back_aug.width + bg_width + 6, back_aug.height + bg_height + 6))
bg_rdm_height = RDM.randint(5, back_aug.height - bg_height - 6)
bg_rdm_width = RDM.randint(5, back_aug.width - bg_width - 6)
# crop(x1,y1,x2,y2) x-width,y-height
back_aug = back_aug.crop((bg_rdm_width, bg_rdm_height, bg_rdm_width + bg_width, bg_rdm_height + bg_height))
# print("-------back_aug.size=",back_aug.size)
# 指定白色背景
# back_index = 11
# back_filename = str(back_index) + '.png'
# back = Image.open(os.path.join(self.background_dir, back_filename))
back = self._read_data_from_res(path=self.default_bg_path, mode="Image")
bg_rdm_height = RDM.randint(5, back.height - bg_height - 6)
bg_rdm_width = RDM.randint(5, back.width - bg_width - 6)
# crop(x1,y1,x2,y2) x-width,y-height
back = back.crop(
(bg_rdm_width, bg_rdm_height, bg_rdm_width + bg_width, bg_rdm_height + bg_height))
# print("-------back.size=", back.size)
## 上面获取到了行背景和文字背景后,往文字背景贴字。贴完字后,把文字背景贴到行背景,最终生成数据。
# char width
char_width = 0
char_aug_width = 0
if self.true_write_type:
true_type_threshold = 1000 * self.true_write_type_ratio
true_type_rdm = RDM.randint(0, 999)
if true_type_rdm >= true_type_threshold:
self.temp_true_type=False
else:
self.temp_true_type = True
## 根据预先设置的hcl ration 来源比例,随机个数字,数字小于threshold,就从HCL取,否则从HWDB取
hcl_ration_threshold = 1000 * self.hcl_ratio
hcl_ration_rdm = RDM.randint(0, 999)
str_from = ""
for char in str_gen:
if not self.line_mix:
if hcl_ration_rdm >= hcl_ration_threshold:
char_img,char_from = self._get_char_img(char,"HWDB")
str_from = "HWDB"
else:
char_img,char_from = self._get_char_img(char, "HCL")
str_from = "HCL"
else:
char_img,char_from = self._get_char_img(char,"line_mix")
str_from = "MIX"
## 对单字进行数据增强
char_img_aug = char_img.copy()
## 先真实化再数据增强
if self.true_write_type and self.temp_true_type: # 首先对单字符图片进行真实化处理
char_img_aug = self._true_write_type_data(char_img_aug, char_from)
char_img_aug = self._char_image_data_augment(char_img_aug,char_from)
char_top_margin = 0
if self.temp_data_augment.find("m")>=0:
char_top_margin = RDM.randint(1,str_img_aug.height//8)
try:
r, g, b, alph = char_img.split()
# 拼接汉字字符,这里可以控制间距进行数据增强
# augment place
str_img.paste(char_img, (char_width, int((str_img.height - char_img.height) / 2)), mask=alph)
str_img_aug.paste(char_img_aug, (char_aug_width, int((str_img.height - char_img.height) / 2)+char_top_margin), mask=alph)
# back.paste(char_img, (char_width, int((str_img.height - char_img.height) / 2)), mask=alph)
except:
str_img.paste(char_img, (char_width, int((str_img.height - char_img.height) / 2)))
str_img_aug.paste(char_img_aug, (char_aug_width, int((str_img.height - char_img.height) / 2)+char_top_margin))
# back.paste(char_img, (char_width, int((str_img.height - char_img.height) / 2)))
char_width += char_img.width+self.chars_gap_width
char_aug_width += char_img_aug.width+self.chars_gap_width
str_img_aug = str_img_aug.resize(back_aug.size)
r, g, b, a = str_img_aug.split()
back_aug.paste(str_img_aug, (5, 0), mask=a)
str_img = str_img.resize(back.size)
r, g, b, a = str_img.split()
back.paste(str_img, (5, 0),mask = a)
return back_aug,back,str_from
def _get_char_list(self, str):
'''
分解str,获得单个char,再根据char_dict得到每一个char的对应编号,最终等到char_list
:param str:
:return:char_list:str中每个char的编号列表
'''
char_list = []
new_str = ''
for char in str:
try:
char_list.append(self.char_dict[char])
new_str += char
except:
rd = RDM.randint(0, 3755)
char_list.append(rd)
new_str += list(self.char_dict.keys())[list(self.char_dict.values()).index(rd)]
return new_str, char_list
def _true_write_type_data(self,img,char_from):
# if char_from=="HWDB": ## HWDB数据真实化效果不好,先跳过。只对HCL进行真实化
# return img
img_h = img.height
img_w = img.width
if char_from=="HCL":
head_augmenter = []
tail_augmenter = []
head_augmenter.append(iaa.Invert(1, per_channel=True))
# aug_pwa = iaa.Resize((0.7, 1)) # 将w和h在0.5-1.5倍范围内resize
head_augmenter.append(iaa.Sharpen(alpha=(1, 1), lightness=(1, 1))) # 锐化处理
# augmenter.append(iaa.ContrastNormalization((1.5, 1.5), per_channel=0.5)) # 对比度
head_seq = iaa.Sequential(head_augmenter)
tail_augmenter.append(iaa.Invert(1, per_channel=True))
tail_seq = iaa.Sequential(tail_augmenter)
# img为opencv,image为PIL,二者进行转化
# PIL->opencv
# img_cv = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2BGRA)
image_aug = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2GRAY)
image_aug = cv2.resize(image_aug, (128, 128))
# + cv2.THRESH_OTSU
# print("_true_write_type_data--char_from=",char_from)
# ret3, image_aug = cv2.threshold(image_aug, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
head_imglist = []
head_imglist.append(image_aug)
images_aug = head_seq.augment_images(head_imglist)
image_aug = images_aug[0]
ret3, image_aug = cv2.threshold(image_aug, 245, 255, cv2.THRESH_BINARY)
#
kernel = np.ones((4, 4), np.uint8)
# image_aug = cv2.erode(image_aug, kernel, iterations=1)
# image_aug = cv2.dilate(image_aug, kernel, iterations=2)
image_aug = cv2.dilate(image_aug, kernel, iterations=1)
# image_aug = cv2.erode(image_aug, kernel, iterations=1)
image_aug = cv2.erode(image_aug, kernel, iterations=1)
#
# image_aug = cv2.Canny(image_aug, 0, 100)
#
# seq = iaa.Sequential([iaa.Invert(1, per_channel=True)])
# images_aug = seq.augment_images([image_aug])
# image_aug = images_aug[0]
# image_aug = cv2.morphologyEx(image_aug, cv2.MORPH_OPEN, kernel)
tail_imglist = []
tail_imglist.append(image_aug)
images_aug = tail_seq.augment_images(tail_imglist)
image_aug = images_aug[0]
# image_aug = Image.fromarray(cv2.cvtColor(image_aug, cv2.COLOR_BGRA2RGBA))
image_aug = cv2.resize(image_aug, (img_w, img_h))
image = Image.fromarray(cv2.cvtColor(image_aug, cv2.COLOR_GRAY2RGBA))
else: ## HWDB
head_augmenter = []
tail_augmenter = []
head_augmenter.append(iaa.Invert(1, per_channel=True))
# aug_pwa = iaa.Resize((0.7, 1)) # 将w和h在0.5-1.5倍范围内resize
head_augmenter.append(iaa.Sharpen(alpha=(1, 1), lightness=(1, 1))) # 锐化处理
# augmenter.append(iaa.ContrastNormalization((1.5, 1.5), per_channel=0.5)) # 对比度
head_seq = iaa.Sequential(head_augmenter)
tail_augmenter.append(iaa.Invert(1, per_channel=True))
tail_seq = iaa.Sequential(tail_augmenter)
# img为opencv,image为PIL,二者进行转化
# PIL->opencv
# img_cv = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2BGRA)
image = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2GRAY)
image_aug = cv2.resize(image,(128,128))
# print("image_aug.shape=",image_aug.shape)
# image_aug = cv2.bilateralFilter(image_aug, 9, 75, 75)
# image_aug = cv2.GaussianBlur(image_aug, ksize=(3, 3), sigmaX=0, sigmaY=0)
# + cv2.THRESH_OTSU
# print("_true_write_type_data--char_from=",char_from)
ret3, image_aug = cv2.threshold(image_aug, 245, 255, cv2.THRESH_BINARY)
# ret3, image_aug = cv2.threshold(image_aug, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
head_imglist = []
head_imglist.append(image_aug)
images_aug = head_seq.augment_images(head_imglist)
image_aug = images_aug[0]
#
kernel = np.ones((2, 2), np.uint8)
# image_aug = cv2.erode(image_aug, kernel, iterations=1)
# image_aug = cv2.dilate(image_aug, kernel, iterations=2)
# image_aug = cv2.dilate(image_aug, kernel, iterations=2)
# image_aug = cv2.erode(image_aug, kernel, iterations=1)
#
# image_aug = cv2.Canny(image_aug, 0, 100)
#
# seq = iaa.Sequential([iaa.Invert(1, per_channel=True)])
# images_aug = seq.augment_images([image_aug])
# image_aug = images_aug[0]
# image_aug = cv2.morphologyEx(image_aug, cv2.MORPH_OPEN, kernel)
tail_imglist = []
tail_imglist.append(image_aug)
images_aug = head_seq.augment_images(tail_imglist)
image_aug = images_aug[0]
# image_aug = Image.fromarray(cv2.cvtColor(image_aug, cv2.COLOR_BGRA2RGBA))
image = cv2.resize(image_aug, (img_w, img_h))
image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_GRAY2RGBA))
return image
def _char_image_data_augment(self, img,char_from):
# if self.true_write_type: # 首先对单字符图片进行真实化处理
# img = self._true_write_type_data(img,char_from)
height = img.height
width = img.width
# print("_char_image_data_augment,image.height=",height," ,width=",width)
augmenter = []
if self.temp_data_augment.find("r")>=0:
aug_pwa = iaa.Resize((0.7,1)) # 将w和h在0.5-1.5倍范围内resize
augmenter.append(aug_pwa)
if self.temp_data_augment.find("a")>=0:
aug_pwa = iaa.Affine( #对一部分图像做仿射变换
# scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},#图像缩放为80%到120%之间
# translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, #平移±20%之间
# rotate=(-20, 20), #旋转±45度之间
shear=(-25, 25), #剪切变换±16度,(矩形变平行四边形)
order=[0, 1], #使用最邻近差值或者双线性差值
# cval=(0, 255), #全白全黑填充
)
augmenter.append(aug_pwa)
seq = iaa.Sequential(augmenter)
# img为opencv,image为PIL,二者进行转化
# PIL->opencv
img_cv = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2BGRA)
imglist = []
imglist.append(img_cv)
images_aug = seq.augment_images(imglist)
image = Image.fromarray(cv2.cvtColor(images_aug[0], cv2.COLOR_BGRA2RGBA))
return image
def _line_image_data_augment(self,img,char_num):
height = img.height
width = img.width
# print("_line_image_data_augment,image.height=",height," ,width=",width)
augmenter = []
if self.temp_data_augment.find("l")>=0:
image = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# print("_line_image_data_augment---line")
line_num = RDM.randint(4,8)
line_length = RDM.randint(width//4, width//2)
# draw = ImageDraw.Draw(img)
for x in range(line_num):
startX = RDM.randint(0,int(width*(3/4)))
startY = RDM.randint(0,height)
if startX+line_length > width:
endX = width
else:
endX = startX+line_length
endY = RDM.randint(0,height)
# draw.line([(startX, startY), (endX, endY)], fill="gray", width=1)
cv2.line(image, (startX, startY), (endX, endY), (190, 190, 190),thickness=1, lineType=8)
img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
if self.temp_data_augment.find("p")>=0:
width_num = char_num + 2
height_num = 6
if self.test_mode:
draw = ImageDraw.Draw(img)
for x in range(int(width_num)):
startX = img.size[0] / int(width_num) * (x + 1)
startY = 0
endX = startX
endY = img.size[1]
draw.line([(startX, startY), (endX, endY)], fill="gray", width=1)
for x in range(int(height_num)):
startX = 0
startY = img.size[1] / int(height_num) * (x + 1)
endX = img.size[0]
endY = startY
draw.line([(startX, startY), (endX, endY)], fill="gray", width=1)
# 整体流程为:定义变换序列(Sequential)→读入图片(imread)→执行变换(augment_images)→保存图片(imwrite)
# imgaug test
# StochasticParameter
aug_pwa = iaa.PiecewiseAffine(scale=(0.02, 0.04), nb_rows=(2, height_num), nb_cols=(2, width_num),
order=1, cval=0, mode='constant',
absolute_scale=False, polygon_recoverer=None, name=None,
deterministic=False, random_state=None)
augmenter.append(aug_pwa)
# 在每个图像上放置规则的点网格,然后将每个点随机地移动2 - 3%
# aug = iaa.PiecewiseAffine(scale=(0.02, 0.03))
if self.temp_data_augment.find("b")>=0:
# 用高斯模糊,均值模糊,中值模糊中的一种增强。
aug_pwa = iaa.OneOf([
iaa.GaussianBlur(sigma=(0.4,0.7)), # 高斯模糊
iaa.AverageBlur(k=(2, 7)), # 均匀模糊,核大小2~7之间,k=((5, 7), (1, 3))时,核高度5~7,宽度1~3
iaa.MedianBlur(k=(3, 11)) # 中值模糊
])
augmenter.append(aug_pwa)
if self.temp_data_augment.find("n") >= 0:
aug_pwa = iaa.OneOf([
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # 高斯噪声
iaa.ElasticTransformation(alpha=(0.4, 0.4), sigma=0.25), # 弹性变换,把像素移动到周围的地方。这个方法在mnist数据集增强中有见到
])
augmenter.append(aug_pwa)
if self.temp_data_augment.find("e") >= 0:
aug_pwa = iaa.OneOf([
iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), #浮雕效果
iaa.ContrastNormalization((0.5, 1.2), per_channel=0.5) # 对比度
])
augmenter.append(aug_pwa)
if self.temp_data_augment.find("c") >= 0:
aug_pwa = iaa.OneOf([
iaa.Dropout((0.01, 0.02), per_channel=0.5), # 将1%到2%的像素设置为黑色
iaa.Add((-10, 10), per_channel=0.5), # 每个像素随机加减-10到10之间的数
iaa.Multiply((0.8, 1.2), per_channel=0.5) # 像素乘上0.8或者1.2之间的数字.
])
augmenter.append(aug_pwa)
if self.temp_data_augment.find("f")>=0:
aug_pwa = iaa.Affine( #对一部分图像做仿射变换
# scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},#图像缩放为80%到120%之间
# translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, #平移±20%之间
# rotate=(-20, 20), #旋转±45度之间
shear=(-25, 25), #剪切变换±16度,(矩形变平行四边形)
order=[0, 1], #使用最邻近差值或者双线性差值
# cval=(0, 255), #全白全黑填充
)
augmenter.append(aug_pwa)
seq = iaa.Sequential(augmenter)
# img = cv2.imread('./gen_images/0.png')
# img为opencv,image为PIL,二者进行转化
# PIL->opencv
img_cv = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2BGRA)
imglist = []
imglist.append(img_cv)
# img_arr = np.asarray(img)
images_aug = seq.augment_images(imglist)
image = Image.fromarray(cv2.cvtColor(images_aug[0], cv2.COLOR_BGRA2RGBA))
return image
def _gen_data_with_img_and_label(self, str):
'''
获取最终数据
:param str:文本行
:param img_name:图片保存名称
:param data_path:图片保存地址
:param augment:是否启用数据增强
:param is_test:是否为测试状态
:return:img, label
'''
str, char_list = self._get_char_list(str)
# if self.test_mode:
# str = "数据真实化效果图"
# str = "刽寝镇勒"
# str = "另一种意见则认为"
# str = "以否定丑来达到间接肯定美"
img_aug,img,str_from = self._get_str_img(str)
image_aug = self._line_image_data_augment(img_aug,len(str))
# print("gen_data_with_img_and_label,image_aug.shape=",image_aug.shape)
if self.test_mode:
image_aug = np.array(image_aug, dtype=np.int32)
image_list = []
image_list.append(img)
image_list.append(image_aug)
label_list = []
aug_str = self._trans_augment_parameter(self.temp_data_augment)
if self.true_write_type and self.temp_true_type:
aug_str += "_真实化"
label_list.append(str+"_"+"original"+"_"+str_from)
label_list.append(str+"_"+"augment"+aug_str+"_"+str_from)
self._show_image(image_list,label_list,filename=str_from+"_"+aug_str+"_"+str)
# self._show_image(image_aug, str+"_"+"augment_"+self.temp_data_augment)
return image_aug,str, char_list
def run(self, which, gen_data_num, gen_image_dir, gen_info_path, gen_frequency_list_path,write_types,
chars_gap_width, data_augment,data_augment_percent):
self.which = which
self.gen_data_num = gen_data_num
self.gen_image_dir = gen_image_dir
self.gen_info_path = gen_info_path
self.gen_frequency_list_path = gen_frequency_list_path
self.write_types = write_types
self.chars_gap_width = chars_gap_width
self.data_augment = data_augment # 是整个Train上应用的效果
self.temp_data_augment = self.data_augment # 临时作为每个样本的增强效果
self.temp_true_type = self.true_write_type # 临时作为每个样本的真实化
self.data_augment_percent = data_augment_percent
if not os.path.exists(self.gen_image_dir):
os.makedirs(self.gen_image_dir)
data_dir = self.gen_info_path.rsplit("/", 1)[0]
if not os.path.exists(data_dir):
os.makedirs(data_dir)
data_dir = self.gen_frequency_list_path.rsplit("/", 1)[0]
if not os.path.exists(data_dir):
os.makedirs(data_dir)
print("which:",self.which)
print("gen_data_num:", self.gen_data_num)
print("gen_image_dir:", self.gen_image_dir)
print("gen_info_path:", self.gen_info_path)
print("gen_frequency_list_path:", self.gen_frequency_list_path)
print("write_types:", self.write_types)
print("chars_gap_width:", self.chars_gap_width)
print("data_augment:", self.data_augment)
print("data_augment_percent:", self.data_augment_percent)
word_frequency_dict = dict()
# 初始化word_frequency_dict,否则会出现key error
for key in self.char_dict.keys():
word_frequency_dict[key] = 0
word_frequency_dict['keyError'] = 0
if not self.off_corpus: # 使用语料库
text_dict = self._get_scrapy_random_text()
# while gen_data_count < self.gen_data_num:
gen_data_count = 0
# epochs = (self.gen_data_num+1)//self.write_types
# if epochs == 0:
# epochs=1
with tqdm(range(self.gen_data_num)) as pbar:
## for write_types
str_gen=""
for gen_data_count,_ in enumerate(pbar):
if self.const_char_num:
## 固定单个图片中字符个数
random_char_max_num = self.max_char_num
else:
## 否则随机个数
random_char_max_num = RDM.randint(2, self.max_char_num)
labels = []
if gen_data_count % self.write_types == 0:
if not self.off_corpus: # 使用语料库
char_num = gen_data_count % 3755
text_list = list(text_dict[self.char_dict_reverse[char_num]])
random_text_pos = RDM.randint(0, len(text_list))
str_gen = text_list[random_text_pos]
else:
str_gen = ''
for i in range(random_char_max_num):
str_gen += self.char_dict_reverse[RDM.randint(0, 3755)]
# 异常字符处理,暂时随机生成
key_error_count = 0
new_str = ''
# print("test----gen_data_count=",gen_data_count," ,str_gen=",str_gen)
# continue
for char_item in str_gen:
try:
char_file_dir = self.char_dict[char_item]
new_str += char_item
try:
word_frequency_dict[char_item] += 1
except KeyError:
word_frequency_dict['keyError'] += 1
except:
pass
except KeyError:
key_error_count += 1
# print('key_error_count--begin')
# print(str_gen)
# print(char_item)
# print(key_error_count)
# print('key_error_count--end')
char_file_dir = RDM.randint(0, 3755)
char_item = self.char_dict_reverse[char_file_dir]
new_str += char_item
try:
word_frequency_dict[char_item] += 1
except KeyError:
word_frequency_dict['keyError'] += 1
except:
pass
str_gen = new_str
# # 同一个文本行输出write_types种不同写法,暂时不加入数据增强部分。
# for i in range(write_types):
## 随机选取 data_augment_of_all 中参数应用效果,应用在data_augment
if not self.test_mode and self.data_augment!="":
if self.data_augment_percent<=1 and self.data_augment_percent>=0:
threshold = 1000 * self.data_augment_percent
rdm = RDM.randint(0, 999)
if rdm>=threshold: