forked from clovaai/deep-text-recognition-benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
1912 lines (1484 loc) · 78.5 KB
/
dataset.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
import os
import sys
import re
import six
import math
import lmdb
import random
import torch
from natsort import natsorted
from PIL import Image
import numpy as np
from torch.utils.data import Dataset, ConcatDataset, Subset
from torch._utils import _accumulate
import torchvision.transforms as transforms
from utils import SynthGenerator
import phoc
import pdb
class Batch_Balanced_Dataset(object):
def __init__(self, opt):
"""
Modulate the data ratio in the batch.
For example, when select_data is "MJ-ST" and batch_ratio is "0.5-0.5",
the 50% of the batch is filled with MJ and the other 50% of the batch is filled with ST.
"""
log = open(os.path.join(opt.exp_dir,opt.exp_name,'log_dataset.txt'), 'a')
dashed_line = '-' * 80
print(dashed_line)
log.write(dashed_line + '\n')
print(f'dataset_root: {opt.train_data}\nopt.select_data: {opt.select_data}\nopt.batch_ratio: {opt.batch_ratio}')
log.write(f'dataset_root: {opt.train_data}\nopt.select_data: {opt.select_data}\nopt.batch_ratio: {opt.batch_ratio}\n')
assert len(opt.select_data) == len(opt.batch_ratio)
_AlignCollate = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)
self.data_loader_list = []
self.dataloader_iter_list = []
batch_size_list = []
Total_batch_size = 0
for selected_d, batch_ratio_d in zip(opt.select_data, opt.batch_ratio):
_batch_size = max(round(opt.batch_size * float(batch_ratio_d)), 1)
print(dashed_line)
log.write(dashed_line + '\n')
_dataset, _dataset_log = hierarchical_dataset(root=opt.train_data, opt=opt, select_data=[selected_d])
total_number_dataset = len(_dataset)
log.write(_dataset_log)
"""
The total number of data can be modified with opt.total_data_usage_ratio.
ex) opt.total_data_usage_ratio = 1 indicates 100% usage, and 0.2 indicates 20% usage.
See 4.2 section in our paper.
"""
number_dataset = int(total_number_dataset * float(opt.total_data_usage_ratio))
dataset_split = [number_dataset, total_number_dataset - number_dataset]
indices = range(total_number_dataset)
_dataset, _ = [Subset(_dataset, indices[offset - length:offset])
for offset, length in zip(_accumulate(dataset_split), dataset_split)]
selected_d_log = f'num total samples of {selected_d}: {total_number_dataset} x {opt.total_data_usage_ratio} (total_data_usage_ratio) = {len(_dataset)}\n'
selected_d_log += f'num samples of {selected_d} per batch: {opt.batch_size} x {float(batch_ratio_d)} (batch_ratio) = {_batch_size}'
print(selected_d_log)
log.write(selected_d_log + '\n')
batch_size_list.append(str(_batch_size))
Total_batch_size += _batch_size
_data_loader = torch.utils.data.DataLoader(
_dataset, batch_size=_batch_size,
shuffle=True,
num_workers=int(opt.workers),
collate_fn=_AlignCollate, pin_memory=True)
self.data_loader_list.append(_data_loader)
self.dataloader_iter_list.append(iter(_data_loader))
Total_batch_size_log = f'{dashed_line}\n'
batch_size_sum = '+'.join(batch_size_list)
Total_batch_size_log += f'Total_batch_size: {batch_size_sum} = {Total_batch_size}\n'
Total_batch_size_log += f'{dashed_line}'
opt.batch_size = Total_batch_size
print(Total_batch_size_log)
log.write(Total_batch_size_log + '\n')
log.close()
self.pairText = opt.pairText
self.lexicons=[]
out_of_char = f'[^{opt.character}]'
if opt.pairText == True:
#read lexicons file
with open(opt.lexFile,'r') as lexF:
for line in lexF:
lexWord = line[:-1]
if opt.fixedString and len(lexWord)!=opt.batch_exact_length:
continue
if len(lexWord) <= opt.batch_max_length and not(re.search(out_of_char, lexWord.lower())) and len(lexWord) >= opt.batch_min_length:
self.lexicons.append(lexWord)
def get_batch(self):
balanced_batch_images = []
balanced_batch_texts = []
for i, data_loader_iter in enumerate(self.dataloader_iter_list):
try:
image, text = data_loader_iter.next()
balanced_batch_images.append(image)
balanced_batch_texts += text
except StopIteration:
self.dataloader_iter_list[i] = iter(self.data_loader_list[i])
image, text = self.dataloader_iter_list[i].next()
balanced_batch_images.append(image)
balanced_batch_texts += text
except ValueError:
pass
balanced_batch_images = torch.cat(balanced_batch_images, 0)
if self.pairText:
return balanced_batch_images, balanced_batch_texts, random.sample(self.lexicons,len(balanced_batch_texts))
else:
return balanced_batch_images, balanced_batch_texts
def hierarchical_dataset(root, opt, select_data='/'):
""" select_data='/' contains all sub-directory of root directory """
dataset_list = []
dataset_log = f'dataset_root: {root}\t dataset: {select_data[0]}'
print(dataset_log)
dataset_log += '\n'
for dirpath, dirnames, filenames in os.walk(root+'/'):
if not dirnames:
select_flag = False
for selected_d in select_data:
if selected_d in dirpath:
select_flag = True
break
if select_flag:
if opt.style_input:
if opt.style_content_input:
dataset = LmdbStyleContentDataset(dirpath, opt)
else:
dataset = LmdbStyleDataset(dirpath, opt)
else:
dataset = LmdbDataset(dirpath, opt)
sub_dataset_log = f'sub-directory:\t/{os.path.relpath(dirpath, root)}\t num samples: {len(dataset)}'
print(sub_dataset_log)
dataset_log += f'{sub_dataset_log}\n'
dataset_list.append(dataset)
concatenated_dataset = ConcatDataset(dataset_list)
return concatenated_dataset, dataset_log
class LmdbDataset(Dataset):
def __init__(self, root, opt):
self.root = root
self.opt = opt
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
if not self.env:
print('cannot create lmdb from %s' % (root))
sys.exit(0)
with self.env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'.encode()))
self.nSamples = nSamples
print('nSamples:::::::::::::',nSamples)
if self.opt.data_filtering_off:
# for fast check or benchmark evaluation with no filtering
self.filtered_index_list = [index + 1 for index in range(self.nSamples)]
else:
""" Filtering part
If you want to evaluate IC15-2077 & CUTE datasets which have special character labels,
use --data_filtering_off and only evaluate on alphabets and digits.
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L190-L192
And if you want to evaluate them with the model trained with --sensitive option,
use --sensitive and --data_filtering_off,
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/dff844874dbe9e0ec8c5a52a7bd08c7f20afe704/test.py#L137-L144
"""
self.filtered_index_list = []
for index in range(self.nSamples):
index += 1 # lmdb starts with 1
label_key = 'label-%09d'.encode() % index
label = txn.get(label_key).decode('utf-8')
if self.opt.fixedString and len(label) != self.opt.batch_exact_length :
continue
elif len(label) > self.opt.batch_max_length or len(label)<self.opt.batch_min_length:
# print(f'The length of the label is longer than max_length: length
# {len(label)}, {label} in dataset {self.root}')
continue
# By default, images containing characters which are not in opt.character are filtered.
# You can add [UNK] token to `opt.character` in utils.py instead of this filtering.
out_of_char = f'[^{self.opt.character}]'
if re.search(out_of_char, label.lower()):
continue
self.filtered_index_list.append(index)
self.nSamples = len(self.filtered_index_list)
def __len__(self):
return self.nSamples
def __getitem__(self, index):
assert index <= len(self), 'index range error'
index = self.filtered_index_list[index]
with self.env.begin(write=False) as txn:
label_key = 'label-%09d'.encode() % index
label = txn.get(label_key).decode('utf-8')
img_key = 'image-%09d'.encode() % index
imgbuf = txn.get(img_key)
buf = six.BytesIO()
buf.write(imgbuf)
buf.seek(0)
try:
if self.opt.rgb:
img = Image.open(buf).convert('RGB') # for color image
else:
img = Image.open(buf).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img = Image.new('L', (self.opt.imgW, self.opt.imgH))
label = '[dummy_label]'
if not self.opt.sensitive:
label = label.lower()
# We only train and evaluate on alphanumerics (or pre-defined character set in train.py)
out_of_char = f'[^{self.opt.character}]'
label = re.sub(out_of_char, '', label)
return (img, label)
class LmdbStyleDataset(Dataset):
def __init__(self, root, opt):
self.root = root
self.opt = opt
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
if not self.env:
print('cannot create lmdb from %s' % (root))
sys.exit(0)
with self.env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'.encode()))
self.nSamples = nSamples
print('nSamples:::::::::::::',nSamples)
if self.opt.data_filtering_off:
# for fast check or benchmark evaluation with no filtering
self.filtered_index_list = [index + 1 for index in range(self.nSamples)]
else:
""" Filtering part
If you want to evaluate IC15-2077 & CUTE datasets which have special character labels,
use --data_filtering_off and only evaluate on alphabets and digits.
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L190-L192
And if you want to evaluate them with the model trained with --sensitive option,
use --sensitive and --data_filtering_off,
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/dff844874dbe9e0ec8c5a52a7bd08c7f20afe704/test.py#L137-L144
"""
self.filtered_index_list = []
for index in range(self.nSamples):
index += 1 # lmdb starts with 1
label1_key = 'label1-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label2-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
if self.opt.fixedString and (len(label1) != self.opt.batch_exact_length or len(label2) != self.opt.batch_exact_length) :
continue
elif len(label1) > self.opt.batch_max_length or len(label1)<self.opt.batch_min_length or len(label2) > self.opt.batch_max_length or len(label2)<self.opt.batch_min_length:
# print(f'The length of the label is longer than max_length: length
# {len(label)}, {label} in dataset {self.root}')
continue
# By default, images containing characters which are not in opt.character are filtered.
# You can add [UNK] token to `opt.character` in utils.py instead of this filtering.
out_of_char = f'[^{self.opt.character}]'
if re.search(out_of_char, label1.lower()) or re.search(out_of_char, label2.lower()):
continue
self.filtered_index_list.append(index)
self.nSamples = len(self.filtered_index_list)
def __len__(self):
return self.nSamples
def __getitem__(self, index):
assert index <= len(self), 'index range error'
index = self.filtered_index_list[index]
with self.env.begin(write=False) as txn:
label1_key = 'label1-%09d'.encode() % index
label2_key = 'label2-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2 = txn.get(label2_key).decode('utf-8')
img1_key = 'image1-%09d'.encode() % index
img2_key = 'image2-%09d'.encode() % index
img1buf = txn.get(img1_key)
img2buf = txn.get(img2_key)
buf1 = six.BytesIO()
buf1.write(img1buf)
buf1.seek(0)
buf2 = six.BytesIO()
buf2.write(img2buf)
buf2.seek(0)
try:
if self.opt.rgb:
img1 = Image.open(buf1).convert('RGB') # for color image
img2 = Image.open(buf2).convert('RGB') # for color image
else:
img1 = Image.open(buf1).convert('L')
img2 = Image.open(buf2).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img1 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img1 = Image.new('L', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('L', (self.opt.imgW, self.opt.imgH))
label1 = '[dummy_label]'
label2 = '[dummy_label]'
if not self.opt.sensitive:
label1 = label1.lower()
label2 = label2.lower()
# We only train and evaluate on alphanumerics (or pre-defined character set in train.py)
out_of_char = f'[^{self.opt.character}]'
label1 = re.sub(out_of_char, '', label1)
label2 = re.sub(out_of_char, '', label2)
return (img1, img2, label1, label2)
class LmdbStylePHOCDataset(Dataset):
def __init__(self, root, opt):
self.root = root
self.opt = opt
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
self.phocObj = phoc_gen(opt)
if not self.env:
print('cannot create lmdb from %s' % (root))
sys.exit(0)
with self.env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'.encode()))
self.nSamples = nSamples
print('nSamples:::::::::::::',nSamples)
if self.opt.data_filtering_off:
# for fast check or benchmark evaluation with no filtering
self.filtered_index_list = [index + 1 for index in range(self.nSamples)]
else:
""" Filtering part
If you want to evaluate IC15-2077 & CUTE datasets which have special character labels,
use --data_filtering_off and only evaluate on alphabets and digits.
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L190-L192
And if you want to evaluate them with the model trained with --sensitive option,
use --sensitive and --data_filtering_off,
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/dff844874dbe9e0ec8c5a52a7bd08c7f20afe704/test.py#L137-L144
"""
self.filtered_index_list = []
for index in range(self.nSamples):
index += 1 # lmdb starts with 1
label1_key = 'label1-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label2-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
if self.opt.fixedString and (len(label1) != self.opt.batch_exact_length or len(label2) != self.opt.batch_exact_length) :
continue
elif len(label1) > self.opt.batch_max_length or len(label1)<self.opt.batch_min_length or len(label2) > self.opt.batch_max_length or len(label2)<self.opt.batch_min_length:
# print(f'The length of the label is longer than max_length: length
# {len(label)}, {label} in dataset {self.root}')
continue
# By default, images containing characters which are not in opt.character are filtered.
# You can add [UNK] token to `opt.character` in utils.py instead of this filtering.
out_of_char = f'[^{self.opt.character}]'
if re.search(out_of_char, label1.lower()) or re.search(out_of_char, label2.lower()):
continue
self.filtered_index_list.append(index)
self.nSamples = len(self.filtered_index_list)
def __len__(self):
return self.nSamples
def __getitem__(self, index):
assert index <= len(self), 'index range error'
index = self.filtered_index_list[index]
with self.env.begin(write=False) as txn:
label1_key = 'label1-%09d'.encode() % index
label2_key = 'label2-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2 = txn.get(label2_key).decode('utf-8')
img1_key = 'image1-%09d'.encode() % index
img2_key = 'image2-%09d'.encode() % index
img1buf = txn.get(img1_key)
img2buf = txn.get(img2_key)
buf1 = six.BytesIO()
buf1.write(img1buf)
buf1.seek(0)
buf2 = six.BytesIO()
buf2.write(img2buf)
buf2.seek(0)
try:
if self.opt.rgb:
img1 = Image.open(buf1).convert('RGB') # for color image
img2 = Image.open(buf2).convert('RGB') # for color image
else:
img1 = Image.open(buf1).convert('L')
img2 = Image.open(buf2).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img1 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img1 = Image.new('L', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('L', (self.opt.imgW, self.opt.imgH))
label1 = '[dummy_label]'
label2 = '[dummy_label]'
if not self.opt.sensitive:
label1 = label1.lower()
label2 = label2.lower()
# We only train and evaluate on alphanumerics (or pre-defined character set in train.py)
out_of_char = f'[^{self.opt.character}]'
label1 = re.sub(out_of_char, '', label1)
label2 = re.sub(out_of_char, '', label2)
return (img1, img2, label1, label2, self.phocObj.getPhoc(label1), self.phocObj.getPhoc(label2))
class LmdbStyleContentDataset(Dataset):
def __init__(self, root, opt, dataMode=False):
self.root = root
self.opt = opt
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
self.synthGen = SynthGenerator('/private/home/pkrishnan/fonts/fonts-10-path.txt',imgSize=(64,256))
if not self.env:
print('cannot create lmdb from %s' % (root))
sys.exit(0)
with self.env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'.encode()))
self.nSamples = nSamples
print('nSamples:::::::::::::',nSamples)
if self.opt.data_filtering_off:
# for fast check or benchmark evaluation with no filtering
self.filtered_index_list = [index + 1 for index in range(self.nSamples)]
else:
""" Filtering part
If you want to evaluate IC15-2077 & CUTE datasets which have special character labels,
use --data_filtering_off and only evaluate on alphabets and digits.
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L190-L192
And if you want to evaluate them with the model trained with --sensitive option,
use --sensitive and --data_filtering_off,
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/dff844874dbe9e0ec8c5a52a7bd08c7f20afe704/test.py#L137-L144
"""
self.filtered_index_list = []
for index in range(self.nSamples):
index += 1 # lmdb starts with 1
if dataMode:
#Todo: remove duplication; simplify
label1_key = 'label-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
else:
label1_key = 'label1-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label2-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
if self.opt.fixedString and (len(label1) != self.opt.batch_exact_length or len(label2) != self.opt.batch_exact_length) :
continue
elif len(label1) > self.opt.batch_max_length or len(label1)<self.opt.batch_min_length or len(label2) > self.opt.batch_max_length or len(label2)<self.opt.batch_min_length:
# print(f'The length of the label is longer than max_length: length
# {len(label)}, {label} in dataset {self.root}')
continue
# By default, images containing characters which are not in opt.character are filtered.
# You can add [UNK] token to `opt.character` in utils.py instead of this filtering.
out_of_char = f'[^{self.opt.character}]'
if re.search(out_of_char, label1.lower()) or re.search(out_of_char, label2.lower()):
continue
self.filtered_index_list.append(index)
self.nSamples = len(self.filtered_index_list)
self.realData = dataMode
def __len__(self):
return self.nSamples
def __getitem__(self, index):
assert index <= len(self), 'index range error'
index = self.filtered_index_list[index]
with self.env.begin(write=False) as txn:
if self.realData:
#todo: remove duplication; simplify
label1_key = 'label-%09d'.encode() % index
label2_key = 'label-%09d'.encode() % index
else:
label1_key = 'label1-%09d'.encode() % index
label2_key = 'label2-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2 = txn.get(label2_key).decode('utf-8')
if self.realData:
#todo: remove duplication; simplify
img1_key = 'image-%09d'.encode() % index
img2_key = 'image-%09d'.encode() % index
else:
img1_key = 'image1-%09d'.encode() % index
img2_key = 'image2-%09d'.encode() % index
img1buf = txn.get(img1_key)
img2buf = txn.get(img2_key)
buf1 = six.BytesIO()
buf1.write(img1buf)
buf1.seek(0)
buf2 = six.BytesIO()
buf2.write(img2buf)
buf2.seek(0)
try:
if self.opt.rgb:
img1 = Image.open(buf1).convert('RGB') # for color image
img2 = Image.open(buf2).convert('RGB') # for color image
else:
img1 = Image.open(buf1).convert('L')
img2 = Image.open(buf2).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img1 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img1 = Image.new('L', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('L', (self.opt.imgW, self.opt.imgH))
label1 = '[dummy_label]'
label2 = '[dummy_label]'
if not self.opt.sensitive:
label1 = label1.lower()
label2 = label2.lower()
# We only train and evaluate on alphanumerics (or pre-defined character set in train.py)
out_of_char = f'[^{self.opt.character}]'
label1 = re.sub(out_of_char, '', label1)
label2 = re.sub(out_of_char, '', label2)
label1SynthImg = self.synthGen.synthesizeWordImage(label1, 0)
label2SynthImg = self.synthGen.synthesizeWordImage(label2, 0)
return (img1, img2, label1, label2, label1SynthImg, label2SynthImg)
class LmdbTestStyleContentDataset(Dataset):
def __init__(self, root, opt, dataMode=False):
self.root = root
self.opt = opt
self.env = lmdb.open(root, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
self.synthGen = SynthGenerator('/private/home/pkrishnan/fonts/fonts-10-path.txt',imgSize=(64,256))
if not self.env:
print('cannot create lmdb from %s' % (root))
sys.exit(0)
self.pairId = []
self.pairText = []
if opt.outPairFile!="":
with open(opt.outPairFile,'r') as pID:
lines = pID.readlines()
for currline in lines:
tokens = currline[:-1].split(" ")
labelTok = tokens[0].split('-')
self.pairId.append(labelTok[1])
self.pairText.append(tokens[2])
with self.env.begin(write=False) as txn:
nSamples = int(txn.get('num-samples'.encode()))
self.nSamples = nSamples
print('nSamples:::::::::::::',nSamples)
if self.opt.data_filtering_off:
# for fast check or benchmark evaluation with no filtering
self.filtered_index_list = [index + 1 for index in range(self.nSamples)]
else:
""" Filtering part
If you want to evaluate IC15-2077 & CUTE datasets which have special character labels,
use --data_filtering_off and only evaluate on alphabets and digits.
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L190-L192
And if you want to evaluate them with the model trained with --sensitive option,
use --sensitive and --data_filtering_off,
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/dff844874dbe9e0ec8c5a52a7bd08c7f20afe704/test.py#L137-L144
"""
self.filtered_index_list = []
for index in range(self.nSamples):
index += 1 # lmdb starts with 1
if dataMode:
#Todo: remove duplication; simplify
label1_key = 'label-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
else:
label1_key = 'label1-%09d'.encode() % index
label1 = txn.get(label1_key).decode('utf-8')
label2_key = 'label2-%09d'.encode() % index
label2 = txn.get(label2_key).decode('utf-8')
#read image and filter
if dataMode:
img1_key = 'image-%09d'.encode() % index
img1buf = txn.get(img1_key)
buf1 = six.BytesIO()
buf1.write(img1buf)
buf1.seek(0)
try:
if self.opt.rgb:
img1 = Image.open(buf1).convert('RGB') # for color image
else:
img1 = Image.open(buf1).convert('L')
if opt.sizeFilt and (img1.size[1]<opt.imgH_filt or (img1.size[0] < 1.25*img1.size[1])):
continue
except IOError:
print(f'Corrupted image for {index}')
continue
if self.opt.fixedString and (len(label1) != self.opt.batch_exact_length or len(label2) != self.opt.batch_exact_length) :
continue
elif len(label1) > self.opt.batch_max_length or len(label1)<self.opt.batch_min_length or len(label2) > self.opt.batch_max_length or len(label2)<self.opt.batch_min_length:
# print(f'The length of the label is longer than max_length: length
# {len(label)}, {label} in dataset {self.root}')
continue
# By default, images containing characters which are not in opt.character are filtered.
# You can add [UNK] token to `opt.character` in utils.py instead of this filtering.
out_of_char = f'[^{self.opt.character}]'
if re.search(out_of_char, label1.lower()) or re.search(out_of_char, label2.lower()):
continue
self.filtered_index_list.append(index)
self.nSamples = len(self.filtered_index_list)
if len(self.pairId)>0:
print('Filtered nSamples:::::::::::::',len(self.pairId))
else:
print('Filtered nSamples:::::::::::::',self.nSamples)
self.realData = dataMode
def __len__(self):
if len(self.pairId)>0:
return len(self.pairId)
else:
return self.nSamples
def __getitem__(self, index):
assert index <= len(self), 'index range error'
if len(self.pairId)==0:
index = self.filtered_index_list[index]
with self.env.begin(write=False) as txn:
if len(self.pairId)>0:
if self.realData:
label1_key = ('label-'+self.pairId[index]).encode()
label2_key = ('label-'+self.pairId[index]).encode()
else:
label1_key = ('label1-'+self.pairId[index]).encode()
label2_key = ('label2-'+self.pairId[index]).encode()
else:
if self.realData:
#todo: remove duplication; simplify
label1_key = 'label-%09d'.encode() % index
label2_key = 'label-%09d'.encode() % index
else:
label1_key = 'label1-%09d'.encode() % index
label2_key = 'label2-%09d'.encode() % index
if len(self.pairId)>0:
label1 = txn.get(label1_key).decode('utf-8')
label2 = self.pairText[index]
else:
label1 = txn.get(label1_key).decode('utf-8')
label2 = txn.get(label2_key).decode('utf-8')
if len(self.pairId)>0:
if self.realData:
#todo: remove duplication; simplify
img1_key = ('image-'+self.pairId[index]).encode()
img2_key = ('image-'+self.pairId[index]).encode()
else:
img1_key = ('image1-'+self.pairId[index]).encode()
img2_key = ('image2-'+self.pairId[index]).encode()
else:
if self.realData:
#todo: remove duplication; simplify
img1_key = 'image-%09d'.encode() % index
img2_key = 'image-%09d'.encode() % index
else:
img1_key = 'image1-%09d'.encode() % index
img2_key = 'image2-%09d'.encode() % index
img1buf = txn.get(img1_key)
img2buf = txn.get(img2_key)
buf1 = six.BytesIO()
buf1.write(img1buf)
buf1.seek(0)
buf2 = six.BytesIO()
buf2.write(img2buf)
buf2.seek(0)
try:
if self.opt.rgb:
img1 = Image.open(buf1).convert('RGB') # for color image
img2 = Image.open(buf2).convert('RGB') # for color image
else:
img1 = Image.open(buf1).convert('L')
img2 = Image.open(buf2).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img1 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img1 = Image.new('L', (self.opt.imgW, self.opt.imgH))
img2 = Image.new('L', (self.opt.imgW, self.opt.imgH))
label1 = '[dummy_label]'
label2 = '[dummy_label]'
if not self.opt.sensitive:
label1 = label1.lower()
label2 = label2.lower()
# We only train and evaluate on alphanumerics (or pre-defined character set in train.py)
out_of_char = f'[^{self.opt.character}]'
label1 = re.sub(out_of_char, '', label1)
label2 = re.sub(out_of_char, '', label2)
label1SynthImg = self.synthGen.synthesizeWordImage(label1, 0)
label2SynthImg = self.synthGen.synthesizeWordImage(label2, 0)
return (img1, img2, label1, label2, label1SynthImg, label2SynthImg)
class RawDataset(Dataset):
def __init__(self, root, opt):
self.opt = opt
self.image_path_list = []
for dirpath, dirnames, filenames in os.walk(root):
for name in filenames:
_, ext = os.path.splitext(name)
ext = ext.lower()
if ext == '.jpg' or ext == '.jpeg' or ext == '.png':
self.image_path_list.append(os.path.join(dirpath, name))
self.image_path_list = natsorted(self.image_path_list)
self.nSamples = len(self.image_path_list)
def __len__(self):
return self.nSamples
def __getitem__(self, index):
try:
if self.opt.rgb:
img = Image.open(self.image_path_list[index]).convert('RGB') # for color image
else:
img = Image.open(self.image_path_list[index]).convert('L')
except IOError:
print(f'Corrupted image for {index}')
# make dummy image and dummy label for corrupted image.
if self.opt.rgb:
img = Image.new('RGB', (self.opt.imgW, self.opt.imgH))
else:
img = Image.new('L', (self.opt.imgW, self.opt.imgH))
return (img, self.image_path_list[index])
class ResizeNormalize(object):
def __init__(self, size, interpolation=Image.BICUBIC):
self.size = size
self.interpolation = interpolation
self.toTensor = transforms.ToTensor()
def __call__(self, img):
img = img.resize(self.size, self.interpolation)
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
return img
class ResizeNormalize_translate(object):
def __init__(self, size, interpolation=Image.BICUBIC):
self.size = size
self.interpolation = interpolation
self.toTensor = transforms.ToTensor()
self.randomcrop=transforms.RandomResizedCrop((size[1],size[0]), scale=(0.99, 1.0), ratio=(1.0, 1.0), interpolation=interpolation)
self.affine = transforms.RandomAffine(0, translate=(0.1,0.2), scale=(0.8,1.0))
def __call__(self, img):
# img = img.resize(self.size, self.interpolation)
# img = self.affine(img)
img = self.randomcrop(img)
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
return img
class ResizeNormalize_Mean(object):
def __init__(self, size, interpolation=Image.BICUBIC):
self.size = size
self.interpolation = interpolation
self.toTensor = transforms.ToTensor()
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
def __call__(self, img):
img = img.resize(self.size, self.interpolation)
img = self.toTensor(img)
img = self.normalize(img)
# img.sub_(0.5).div_(0.5)
return img
class NormalizePAD(object):
def __init__(self, max_size, PAD_type='right'):
self.toTensor = transforms.ToTensor()
self.max_size = max_size
self.max_width_half = math.floor(max_size[2] / 2)
self.PAD_type = PAD_type
def __call__(self, img):
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
c, h, w = img.size()
Pad_img = torch.FloatTensor(*self.max_size).fill_(0)
Pad_img[:, :, :w] = img # right pad
if self.max_size[2] != w: # add border Pad
# Pad_img[:, :, w:] = img[:, :, w - 1].unsqueeze(2).expand(c, h, self.max_size[2] - w)
zero_vec = torch.zeros((img.size()[0],img.size()[1]))
Pad_img[:, :, w:] = zero_vec.unsqueeze(2).expand(c, h, self.max_size[2] - w)
return Pad_img
class NormalizePAD_Mean(object):
def __init__(self, max_size, PAD_type='right'):
self.toTensor = transforms.ToTensor()
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
self.max_size = max_size
self.max_width_half = math.floor(max_size[2] / 2)
self.PAD_type = PAD_type
def __call__(self, img):
img = self.toTensor(img)
# img.sub_(0.5).div_(0.5)
img = self.normalize(img)
c, h, w = img.size()
Pad_img = torch.FloatTensor(*self.max_size).fill_(0)
Pad_img[:, :, :w] = img # right pad
if self.max_size[2] != w: # add border Pad
# Pad_img[:, :, w:] = img[:, :, w - 1].unsqueeze(2).expand(c, h, self.max_size[2] - w)
zero_vec = torch.zeros((img.size()[0],img.size()[1]))
Pad_img[:, :, w:] = zero_vec.unsqueeze(2).expand(c, h, self.max_size[2] - w)
return Pad_img
class NormalizePADVarSize(object):
def __init__(self, max_size, PAD_type='right'):
self.toTensor = transforms.ToTensor()
self.max_size = max_size
self.max_width_half = math.floor(max_size[2] / 2)
self.PAD_type = PAD_type
def __call__(self, img):
img = self.toTensor(img)
img.sub_(0.5).div_(0.5)
# c, h, w = img.size()
# Pad_img = torch.FloatTensor(*self.max_size).fill_(0)
# Pad_img[:, :, :w] = img # right pad
# if self.max_size[2] != w: # add border Pad
# # Pad_img[:, :, w:] = img[:, :, w - 1].unsqueeze(2).expand(c, h, self.max_size[2] - w)
# zero_vec = torch.zeros((img.size()[0],img.size()[1]))
# Pad_img[:, :, w:] = zero_vec.unsqueeze(2).expand(c, h, self.max_size[2] - w)
return img
class AlignCollate(object):
def __init__(self, imgH=32, imgW=100, keep_ratio_with_pad=False):
self.imgH = imgH
self.imgW = imgW
self.keep_ratio_with_pad = keep_ratio_with_pad
def __call__(self, batch):
batch = filter(lambda x: x is not None, batch)
images, labels = zip(*batch)
if self.keep_ratio_with_pad: # same concept with 'Rosetta' paper
resized_max_w = self.imgW
input_channel = 3 if images[0].mode == 'RGB' else 1
transform = NormalizePAD((input_channel, self.imgH, resized_max_w))