-
Notifications
You must be signed in to change notification settings - Fork 28
/
New_work.py
12876 lines (11117 loc) · 586 KB
/
New_work.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 re
import shutil
def callback(work_path, project_name):
return f"""import re
import os
import numpy as np
import tensorflow as tf
from loguru import logger
from tqdm.keras import TqdmCallback
from tensorflow.keras import backend as K
from {work_path}.{project_name}.settings import LR
from {work_path}.{project_name}.settings import MODE
from {work_path}.{project_name}.settings import EPOCHS
from {work_path}.{project_name}.settings import LOG_DIR
from {work_path}.{project_name}.settings import CSV_PATH
from {work_path}.{project_name}.settings import BATCH_SIZE
from {work_path}.{project_name}.settings import TRAIN_PATH
from {work_path}.{project_name}.settings import UPDATE_FREQ
from {work_path}.{project_name}.settings import LR_PATIENCE
from {work_path}.{project_name}.settings import EARLY_PATIENCE
from {work_path}.{project_name}.settings import CHECKPOINT_PATH
from {work_path}.{project_name}.settings import COSINE_SCHEDULER
from {work_path}.{project_name}.settings import CHECKPOINT_FILE_PATH
from {work_path}.{project_name}.utils import Image_Processing
# 开启可视化的命令
'''
tensorboard --logdir "logs"
'''
# 回调函数官方文档
# https://keras.io/zh/callbacks/
class CallBack(object):
@classmethod
def calculate_the_best_weight(self):
if os.listdir(CHECKPOINT_PATH):
value = Image_Processing.extraction_image(CHECKPOINT_PATH)
try:
extract_num = [os.path.splitext(os.path.split(i)[-1])[0] for i in value]
num = [re.split('-', i) for i in extract_num]
losses = [float('-' + str(abs(float(i[2])))) for i in num]
model_dict = dict((ind, val) for ind, val in zip(losses, value))
return model_dict.get(max(losses))
except IndexError as e:
return value[0]
else:
logger.debug('没有可用的检查点')
@classmethod
def cosine_scheduler(self):
train_number = len(Image_Processing.extraction_image(TRAIN_PATH))
warmup_epoch = int(EPOCHS * 0.2)
total_steps = int(EPOCHS * train_number / BATCH_SIZE)
warmup_steps = int(warmup_epoch * train_number / BATCH_SIZE)
cosine_scheduler_callback = WarmUpCosineDecayScheduler(learning_rate_base=LR, total_steps=total_steps,
warmup_learning_rate=LR * 0.1,
warmup_steps=warmup_steps,
hold_base_rate_steps=train_number,
min_learn_rate=LR * 0.2)
return cosine_scheduler_callback
@classmethod
def callback(self, model):
call = []
if os.path.exists(CHECKPOINT_PATH):
if os.listdir(CHECKPOINT_PATH):
logger.debug('load the model')
model.load_weights(os.path.join(CHECKPOINT_PATH, self.calculate_the_best_weight()))
logger.debug(f'读取的权重为{{os.path.join(CHECKPOINT_PATH, self.calculate_the_best_weight())}}')
if MODE == 'YOLO' or MODE == 'YOLO_TINY' or MODE == 'EFFICIENTDET' or MODE == 'SSD':
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=CHECKPOINT_FILE_PATH,
verbose=1,
monitor='loss',
save_weights_only=True,
save_best_only=False, period=1)
else:
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=CHECKPOINT_FILE_PATH,
verbose=1,
save_weights_only=True,
save_best_only=False, period=1)
call.append(cp_callback)
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=LOG_DIR, histogram_freq=1, write_images=False,
update_freq=UPDATE_FREQ, write_graph=False)
call.append(tensorboard_callback)
if COSINE_SCHEDULER:
lr_callback = self.cosine_scheduler()
else:
if MODE == 'YOLO' or MODE == 'YOLO_TINY' or MODE == 'EFFICIENTDET' or MODE == 'SSD':
lr_callback = tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.1, patience=LR_PATIENCE)
else:
lr_callback = tf.keras.callbacks.ReduceLROnPlateau(factor=0.1, patience=LR_PATIENCE)
call.append(lr_callback)
csv_callback = tf.keras.callbacks.CSVLogger(filename=CSV_PATH, append=True)
call.append(csv_callback)
if MODE == 'YOLO' or MODE == 'YOLO_TINY' or MODE == 'EFFICIENTDET' or MODE == 'SSD':
early_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, verbose=1,
patience=EARLY_PATIENCE)
else:
early_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, verbose=1,
patience=EARLY_PATIENCE)
call.append(early_callback)
call.append(TqdmCallback())
return (model, call)
class WarmUpCosineDecayScheduler(tf.keras.callbacks.Callback):
def __init__(self, learning_rate_base, total_steps, global_step_init=0, warmup_learning_rate=0.0, warmup_steps=0,
hold_base_rate_steps=0, min_learn_rate=0., verbose=1):
super(WarmUpCosineDecayScheduler, self).__init__()
# 基础的学习率
self.learning_rate_base = learning_rate_base
# 热调整参数
self.warmup_learning_rate = warmup_learning_rate
# 参数显示
self.verbose = verbose
# learning_rates用于记录每次更新后的学习率,方便图形化观察
self.min_learn_rate = min_learn_rate
self.learning_rates = []
self.interval_epoch = [0.05, 0.15, 0.30, 0.50]
# 贯穿全局的步长
self.global_step_for_interval = global_step_init
# 用于上升的总步长
self.warmup_steps_for_interval = warmup_steps
# 保持最高峰的总步长
self.hold_steps_for_interval = hold_base_rate_steps
# 整个训练的总步长
self.total_steps_for_interval = total_steps
self.interval_index = 0
# 计算出来两个最低点的间隔
self.interval_reset = [self.interval_epoch[0]]
for i in range(len(self.interval_epoch) - 1):
self.interval_reset.append(self.interval_epoch[i + 1] - self.interval_epoch[i])
self.interval_reset.append(1 - self.interval_epoch[-1])
def cosine_decay_with_warmup(self, global_step, learning_rate_base, total_steps, warmup_learning_rate=0.0,
warmup_steps=0,
hold_base_rate_steps=0, min_learn_rate=0, ):
if total_steps < warmup_steps:
raise ValueError('total_steps must be larger or equal to '
'warmup_steps.')
# 这里实现了余弦退火的原理,设置学习率的最小值为0,所以简化了表达式
learning_rate = 0.5 * learning_rate_base * (1 + np.cos(np.pi *
(
global_step - warmup_steps - hold_base_rate_steps) / float(
total_steps - warmup_steps - hold_base_rate_steps)))
# 如果hold_base_rate_steps大于0,表明在warm up结束后学习率在一定步数内保持不变
if hold_base_rate_steps > 0:
learning_rate = np.where(global_step > warmup_steps + hold_base_rate_steps,
learning_rate, learning_rate_base)
if warmup_steps > 0:
if learning_rate_base < warmup_learning_rate:
raise ValueError('learning_rate_base must be larger or equal to '
'warmup_learning_rate.')
# 线性增长的实现
slope = (learning_rate_base - warmup_learning_rate) / warmup_steps
warmup_rate = slope * global_step + warmup_learning_rate
# 只有当global_step 仍然处于warm up阶段才会使用线性增长的学习率warmup_rate,否则使用余弦退火的学习率learning_rate
learning_rate = np.where(global_step < warmup_steps, warmup_rate,
learning_rate)
learning_rate = max(learning_rate, min_learn_rate)
return learning_rate
# 更新global_step,并记录当前学习率
def on_batch_end(self, batch, logs=None):
self.global_step = self.global_step + 1
self.global_step_for_interval = self.global_step_for_interval + 1
lr = K.get_value(self.model.optimizer.lr)
self.learning_rates.append(lr)
# 更新学习率
def on_batch_begin(self, batch, logs=None):
# 每到一次最低点就重新更新参数
if self.global_step_for_interval in [0] + [int(i * self.total_steps_for_interval) for i in self.interval_epoch]:
self.total_steps = self.total_steps_for_interval * self.interval_reset[self.interval_index]
self.warmup_steps = self.warmup_steps_for_interval * self.interval_reset[self.interval_index]
self.hold_base_rate_steps = self.hold_steps_for_interval * self.interval_reset[self.interval_index]
self.global_step = 0
self.interval_index += 1
lr = self.cosine_decay_with_warmup(global_step=self.global_step,
learning_rate_base=self.learning_rate_base,
total_steps=self.total_steps,
warmup_learning_rate=self.warmup_learning_rate,
warmup_steps=self.warmup_steps,
hold_base_rate_steps=self.hold_base_rate_steps,
min_learn_rate=self.min_learn_rate)
K.set_value(self.model.optimizer.lr, lr)
if self.verbose > 0:
logger.info(f'Batch {{self.global_step}}: setting learning rate to {{lr}}.')
if __name__ == '__main__':
logger.debug(CallBack.calculate_the_best_weight())
"""
def app(work_path, project_name):
return f"""import os
import json
import numpy as np
import gradio as gr
import tensorflow as tf
from loguru import logger
from {work_path}.{project_name}.settings import USE_GPU
from {work_path}.{project_name}.settings import APP_MODEL_PATH
from {work_path}.{project_name}.utils import Predict_Image
if USE_GPU:
gpus = tf.config.experimental.list_physical_devices(device_type="GPU")
if gpus:
logger.info("use gpu device")
logger.info(f'可用GPU数量: {{len(gpus)}}')
try:
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
except RuntimeError as e:
logger.error(e)
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(device=gpu, enable=True)
tf.print(gpu)
except RuntimeError as e:
logger.error(e)
else:
tf.config.experimental.list_physical_devices(device_type="CPU")
os.environ["CUDA_VISIBLE_DEVICE"] = "-1"
logger.info("not found gpu device,convert to use cpu")
else:
logger.info("use cpu device")
# 禁用gpu
tf.config.experimental.list_physical_devices(device_type="CPU")
os.environ["CUDA_VISIBLE_DEVICE"] = "-1"
if APP_MODEL_PATH:
model_path = os.path.join(APP_MODEL_PATH, os.listdir(APP_MODEL_PATH)[0])
logger.debug(f'{{model_path}}模型读取成功')
else:
raise OSError(f'{{APP_MODEL_PATH}}没有存放模型文件')
Predict = Predict_Image(model_path=model_path, app=True)
def show_label(image):
return_dict = Predict.api(image=image)
return json.dumps(return_dict, ensure_ascii=False)
def show_image(image):
return Predict.predict_image(image)
if __name__ == '__main__':
gr.Interface(show_label, gr.inputs.Image(), "label").launch(share=False)
# gr.Interface(show_image, gr.inputs.Image(), "image").launch()
"""
def captcha_config():
return '''{
"train_dir": "train_dataset",
"validation_dir": "validation_dataset",
"test_dir": "test_dataset",
"image_suffix": "jpg",
"characters": "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"count": 20000,
"char_count": [4,5,6],
"width": 100,
"height": 60
}
'''
def check_file(work_path, project_name):
return f"""import os
import numpy as np
from PIL import Image
from loguru import logger
from {work_path}.{project_name}.settings import MODE
from {work_path}.{project_name}.settings import TRAIN_PATH
from {work_path}.{project_name}.settings import VALIDATION_PATH
from {work_path}.{project_name}.settings import TEST_PATH
from {work_path}.{project_name}.settings import LABEL_PATH
from {work_path}.{project_name}.utils import Image_Processing
from concurrent.futures import ThreadPoolExecutor
train_image = Image_Processing.extraction_image(TRAIN_PATH)
def cheak_image(image_path):
with open(image_path, 'rb') as image_file:
image = Image.open(image_file)
# if image.mode != 'RGB':
# logger.error(f'{{image}}模式为{{image.mode}}')
try:
image.verify()
width, height = image.size
width_list.append(width)
height_list.append(height)
except SyntaxError as e:
logger.error(e)
try:
logger.error(f'图片: {{image_path}} 已损坏')
image_file.close()
os.remove(image_path)
logger.debug(f'已删除{{image_path}}')
except Exception as e:
logger.error(e)
validation_image = Image_Processing.extraction_image(VALIDATION_PATH)
test_image = Image_Processing.extraction_image(TEST_PATH)
width_list = []
height_list = []
image_list = train_image + validation_image + test_image
if MODE == 'YOLO' or MODE == 'YOLO_TINY' or MODE == 'EFFICIENTDET':
logger.debug(f'标签总数{{len(Image_Processing.extraction_image(LABEL_PATH))}}')
with ThreadPoolExecutor(max_workers=20) as t:
for i in image_list:
task = t.submit(cheak_image, i)
logger.debug(f'图片总数{{len(image_list)}}')
logger.info(f'所有图片最大的高为{{np.max(height_list)}}')
logger.info(f'所有图片最大的宽为{{np.max(width_list)}}')
"""
def delete_file(work_path, project_name):
return f"""# 增强后文件太多,手动删非常困难,直接用代码删
import shutil
from loguru import logger
from {work_path}.{project_name}.settings import WEIGHT
from {work_path}.{project_name}.settings import TRAIN_PATH
from {work_path}.{project_name}.settings import TEST_PATH
from {work_path}.{project_name}.settings import LABEL_PATH
from {work_path}.{project_name}.settings import INPUT_PATH
from {work_path}.{project_name}.settings import OUTPUT_PATH
from {work_path}.{project_name}.settings import VALIDATION_PATH
from {work_path}.{project_name}.settings import TRAIN_PACK_PATH
from {work_path}.{project_name}.settings import VISUALIZATION_PATH
from {work_path}.{project_name}.settings import VALIDATION_PACK_PATH
from concurrent.futures import ThreadPoolExecutor
def del_file(path):
try:
shutil.rmtree(path)
logger.debug(f'成功删除{{path}}')
except WindowsError as e:
logger.error(e)
if __name__ == '__main__':
path = [INPUT_PATH, OUTPUT_PATH, TRAIN_PATH, TEST_PATH, VALIDATION_PATH, TRAIN_PACK_PATH, VALIDATION_PACK_PATH,
LABEL_PATH, WEIGHT, VISUALIZATION_PATH]
with ThreadPoolExecutor(max_workers=50) as t:
for i in path:
t.submit(del_file, i)
"""
def utils(work_path, project_name):
return f"""import io
import re
import os
import cv2
import time
import json
import glob
import base64
import shutil
import random
import hashlib
import colorsys
import operator
import requests
import numpy as np
from PIL import Image
import tensorflow as tf
from loguru import logger
from PIL import ImageDraw
from PIL import ImageFont
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
from matplotlib.image import imread
from matplotlib.patches import Rectangle
from timeit import default_timer as timer
from tensorflow.keras import backend as K
from tensorflow.compat.v1.keras import backend as KT
from {work_path}.{project_name}.models import Models
from {work_path}.{project_name}.models import Yolo_model
from {work_path}.{project_name}.models import YOLO_anchors
from {work_path}.{project_name}.models import Yolo_tiny_model
from {work_path}.{project_name}.models import Efficientdet_anchors
from {work_path}.{project_name}.settings import PHI
from {work_path}.{project_name}.settings import MODE
from {work_path}.{project_name}.settings import MODEL
from {work_path}.{project_name}.settings import DIVIDE
from {work_path}.{project_name}.settings import PRUNING
from {work_path}.{project_name}.settings import THRESHOLD
from {work_path}.{project_name}.settings import MAX_BOXES
from {work_path}.{project_name}.settings import TEST_PATH
from {work_path}.{project_name}.settings import LABEL_PATH
from {work_path}.{project_name}.settings import BASIC_PATH
from {work_path}.{project_name}.settings import CONFIDENCE
from {work_path}.{project_name}.settings import IMAGE_WIDTH
from {work_path}.{project_name}.settings import IMAGE_SIZES
from {work_path}.{project_name}.settings import DIVIDE_RATO
from {work_path}.{project_name}.settings import IMAGE_HEIGHT
from {work_path}.{project_name}.settings import NUMBER_CLASSES_FILE
from {work_path}.{project_name}.settings import CAPTCHA_LENGTH
from {work_path}.{project_name}.settings import IMAGE_CHANNALS
from {work_path}.{project_name}.settings import VALIDATION_PATH
from {work_path}.{project_name}.settings import DATA_ENHANCEMENT
from {work_path}.{project_name}.settings import TRAIN_PATH
from concurrent.futures import ThreadPoolExecutor
mean_time = []
right_value = 0
predicted_value = 0
start = time.time()
time_list = []
table = []
for i in range(256):
if i < THRESHOLD:
table.append(0)
else:
table.append(255)
try:
if MODE == 'CTC_TINY':
input_len = np.int64(Models.captcha_model_ctc_tiny().get_layer('reshape_len').output_shape[1])
except:
pass
class Image_Processing(object):
@classmethod
# 提取全部图片plus
def extraction_image(self, path: str, mode=MODE) -> list:
try:
data_path = []
datas = [os.path.join(path, i) for i in os.listdir(path)]
for data in datas:
data_path = data_path + [os.path.join(data, i) for i in os.listdir(data)]
return data_path
except:
return [os.path.join(path, i) for i in os.listdir(path)]
@classmethod
def extraction_label(self, path_list: list, suffix=True, divide='_', mode=MODE):
if mode == 'ORDINARY':
if suffix:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
paths = [re.split(divide, i)[0] for i in paths]
else:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
ocr_path = []
for i in paths:
for s in i:
ocr_path.append(s)
n_class = sorted(set(ocr_path))
save_dict = dict((index, name) for index, name in enumerate(n_class))
if not os.path.exists(os.path.join(BASIC_PATH, NUMBER_CLASSES_FILE)):
with open(NUMBER_CLASSES_FILE, 'w', encoding='utf-8') as f:
f.write(json.dumps(save_dict, ensure_ascii=False))
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
make_dict = json.loads(f.read())
make_dict = dict((name, index) for index, name in make_dict.items())
label_list = [self.text2vector(label, make_dict=make_dict) for label in paths]
return label_list
elif mode == 'NUM_CLASSES':
if suffix:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
paths = [re.split(divide, i)[0] for i in paths]
else:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
n_class = sorted(set(paths))
save_dict = dict((index, name) for index, name in enumerate(n_class))
if not os.path.exists(os.path.join(BASIC_PATH, NUMBER_CLASSES_FILE)):
with open(NUMBER_CLASSES_FILE, 'w', encoding='utf-8') as f:
f.write(json.dumps(save_dict, ensure_ascii=False))
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
make_dict = json.loads(f.read())
make_dict = dict((name, index) for index, name in make_dict.items())
label_list = [self.text2vector(label, make_dict=make_dict, mode=MODE) for label in paths]
return label_list
elif mode == 'CTC':
if suffix:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
paths = [re.split(divide, i)[0] for i in paths]
else:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
ocr_path = []
for i in paths:
for s in i:
ocr_path.append(s)
n_class = sorted(set(ocr_path))
save_dict = dict((index, name) for index, name in enumerate(n_class))
if not os.path.exists(os.path.join(BASIC_PATH, NUMBER_CLASSES_FILE)):
with open(NUMBER_CLASSES_FILE, 'w', encoding='utf-8') as f:
f.write(json.dumps(save_dict, ensure_ascii=False))
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
make_dict = json.loads(f.read())
make_dict = dict((name, index) for index, name in make_dict.items())
label_list = [self.text2vector(label, make_dict=make_dict) for label in paths]
return label_list
elif mode == 'YOLO' or mode == 'YOLO_TINY' or mode == 'EFFICIENTDET' or mode == 'SSD':
n_class = []
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
try:
label = [(i, glob.glob(f'{{LABEL_PATH}}/*/{{i}}.xml')[0]) for i in paths]
except:
label = [(i, glob.glob(f'{{LABEL_PATH}}/{{i}}.xml')[0]) for i in paths]
path = [(i, os.path.splitext(os.path.split(i)[-1])[0]) for i in path_list]
for index, label_xml in label:
file = open(label_xml, encoding='utf-8')
for i in ET.parse(file).getroot().iter('object'):
classes = i.find('name').text
n_class.append(classes)
file.close()
n_class = sorted(set(n_class))
save_dict = dict((index, name) for index, name in enumerate(n_class))
if not os.path.exists(os.path.join(BASIC_PATH, NUMBER_CLASSES_FILE)):
with open(NUMBER_CLASSES_FILE, 'w', encoding='utf-8') as f:
f.write(json.dumps(save_dict, ensure_ascii=False))
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
make_dict = json.loads(f.read())
make_dict = dict((name, index) for index, name in make_dict.items())
label_dict = {{}}
for index, label_xml in label:
file = open(label_xml, encoding='utf-8')
box_classes = []
for i in ET.parse(file).getroot().iter('object'):
classes = i.find('name').text
xmlbox = i.find('bndbox')
classes_id = make_dict.get(classes, '0')
box = (int(float(xmlbox.find('xmin').text)), int(float(xmlbox.find('ymin').text)),
int(float(xmlbox.find('xmax').text)),
int(float(xmlbox.find('ymax').text)))
box = ','.join([str(a) for a in box]) + ',' + str(classes_id)
box_classes.append(box)
box = np.array([np.array(list(map(int, box.split(',')))) for box in box_classes])
label_dict[index] = box
file.close()
label_list = ([label_dict.get(value) for index, value in path])
return label_list
elif mode == 'CTC_TINY':
if suffix:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
paths = [re.split(divide, i)[0] for i in paths]
else:
paths = [os.path.splitext(os.path.split(i)[-1])[0] for i in path_list]
ocr_path = []
for i in paths:
for s in i:
ocr_path.append(s)
n_class = sorted(set(ocr_path))
save_dict = dict((index, name) for index, name in enumerate(n_class))
if not os.path.exists(os.path.join(BASIC_PATH, NUMBER_CLASSES_FILE)):
with open(NUMBER_CLASSES_FILE, 'w', encoding='utf-8') as f:
f.write(json.dumps(save_dict, ensure_ascii=False))
with open(NUMBER_CLASSES_FILE, 'r', encoding='utf-8') as f:
make_dict = json.loads(f.read())
make_dict = dict((name, index) for index, name in make_dict.items())
label_list = [self.text2vector(label, make_dict=make_dict) for label in paths]
return label_list
else:
raise ValueError(f'没有mode={{mode}}提取标签的方法')
@classmethod
def text2vector(self, label, make_dict: dict, mode=MODE):
if mode == 'ORDINARY':
if len(label) > CAPTCHA_LENGTH:
raise ValueError(f'标签{{label}}长度大于预设值{{CAPTCHA_LENGTH}},建议设置CAPTCHA_LENGTH为{{len(label) + 2}}')
num_classes = len(make_dict)
label_ver = np.ones((CAPTCHA_LENGTH), dtype=np.int64) * num_classes
for index, c in enumerate(label):
if not make_dict.get(c):
raise ValueError(f'错误的值{{c}}')
label_ver[index] = make_dict.get(c)
label_ver = list(tf.keras.utils.to_categorical(label_ver, num_classes=num_classes + 1).ravel())
return label_ver
elif mode == 'NUM_CLASSES':
num_classes = len(make_dict)
label_ver = np.zeros((num_classes), dtype=np.int64) * num_classes
label_ver[int(make_dict.get(label))] = 1.
return label_ver
elif mode == 'CTC':
label_ver = []
for c in label:
if not make_dict.get(c):
raise ValueError(f'错误的值{{c}}')
label_ver.append(int(make_dict.get(c)))
label_ver = np.array(label_ver)
return label_ver
elif mode == 'CTC_TINY':
if len(label) > CAPTCHA_LENGTH:
raise ValueError(f'标签{{label}}长度大于预设值{{CAPTCHA_LENGTH}},建议设置CAPTCHA_LENGTH为{{len(label) + 2}}')
num_classes = len(make_dict)
label_ver = np.ones((CAPTCHA_LENGTH), dtype=np.int64) * num_classes
for index, c in enumerate(label):
if not make_dict.get(c):
raise ValueError(f'错误的值{{c}}')
label_ver[index] = make_dict.get(c)
# label_ver = list(tf.keras.utils.to_categorical(label_ver, num_classes=num_classes + 1).ravel())
return label_ver
else:
raise ValueError(f'没有mode={{mode}}提取标签的方法')
@classmethod
def _shutil_move(self, full_path, des_path, number):
shutil.move(full_path, des_path)
logger.debug(f'剩余数量{{number}}')
# 分割数据集
@classmethod
def split_dataset(self, path: list, proportion=DIVIDE_RATO) -> bool:
if DIVIDE:
number = 0
logger.debug(f'数据集有{{len(path)}},{{proportion * 100}}%作为验证集,{{proportion * 100}}%作为测试集')
division_number = int(len(path) * proportion)
logger.debug(f'验证集数量为{{division_number}},测试集数量为{{division_number}}')
validation_dataset = random.sample(path, division_number)
with ThreadPoolExecutor(max_workers=50) as t:
for i in validation_dataset:
number = number + 1
logger.debug(f'准备移动{{(number / len(validation_dataset)) * 100}}%')
t.submit(path.remove, i)
validation = [os.path.join(VALIDATION_PATH, os.path.split(i)[-1]) for i in validation_dataset]
validation_lenght = len(validation)
with ThreadPoolExecutor(max_workers=50) as t:
for full_path, des_path in zip(validation_dataset, validation):
validation_lenght -= 1
t.submit(Image_Processing._shutil_move, full_path, des_path, validation_lenght)
test_dataset = random.sample(path, division_number)
test = [os.path.join(TEST_PATH, os.path.split(i)[-1]) for i in test_dataset]
test_lenght = len(test)
with ThreadPoolExecutor(max_workers=50) as t:
for full_path, des_path in zip(test_dataset, test):
test_lenght -= 1
t.submit(Image_Processing._shutil_move, full_path, des_path, test_lenght)
logger.success(f'任务结束')
return True
else:
logger.debug(f'数据集有{{len(path)}},{{proportion * 100}}%作为测试集')
division_number = int(len(path) * proportion)
logger.debug(f'测试集数量为{{division_number}}')
test_dataset = random.sample(path, division_number)
test = [os.path.join(TEST_PATH, os.path.split(i)[-1]) for i in test_dataset]
test_lenght = len(test)
with ThreadPoolExecutor(max_workers=50) as t:
for full_path, des_path in zip(test_dataset, test):
test_lenght -= 1
t.submit(Image_Processing._shutil_move, full_path, des_path, test_lenght)
logger.success(f'任务结束')
return True
# # 增强图片
# @classmethod
# def preprosess_save_images(self, image, number):
# logger.info(f'开始处理{{image}}')
# with open(image, 'rb') as images:
# im = Image.open(images)
# blur_im = im.filter(ImageFilter.BLUR)
# contour_im = im.filter(ImageFilter.CONTOUR)
# detail_im = im.filter(ImageFilter.DETAIL)
# edge_enhance_im = im.filter(ImageFilter.EDGE_ENHANCE)
# edge_enhance_more_im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
# emboss_im = im.filter(ImageFilter.EMBOSS)
# flnd_edges_im = im.filter(ImageFilter.FIND_EDGES)
# smooth_im = im.filter(ImageFilter.SMOOTH)
# smooth_more_im = im.filter(ImageFilter.SMOOTH_MORE)
# sharpen_im = im.filter(ImageFilter.SHARPEN)
# maxfilter_im = im.filter(ImageFilter.MaxFilter)
# minfilter_im = im.filter(ImageFilter.MinFilter)
# modefilter_im = im.filter(ImageFilter.ModeFilter)
# medianfilter_im = im.filter(ImageFilter.MedianFilter)
# unsharpmask_im = im.filter(ImageFilter.UnsharpMask)
# left_right_im = im.transpose(Image.FLIP_LEFT_RIGHT)
# top_bottom_im = im.transpose(Image.FLIP_TOP_BOTTOM)
# rotate_list = [im.rotate(i) for i in list(range(1, 360, 60))]
# brightness_im = ImageEnhance.Brightness(im).enhance(0.5)
# brightness_up_im = ImageEnhance.Brightness(im).enhance(1.5)
# color_im = ImageEnhance.Color(im).enhance(0.5)
# color_up_im = ImageEnhance.Color(im).enhance(1.5)
# contrast_im = ImageEnhance.Contrast(im).enhance(0.5)
# contrast_up_im = ImageEnhance.Contrast(im).enhance(1.5)
# sharpness_im = ImageEnhance.Sharpness(im).enhance(0.5)
# sharpness_up_im = ImageEnhance.Sharpness(im).enhance(1.5)
# image_list = [im, blur_im, contour_im, detail_im, edge_enhance_im, edge_enhance_more_im, emboss_im,
# flnd_edges_im,
# smooth_im, smooth_more_im, sharpen_im, maxfilter_im, minfilter_im, modefilter_im,
# medianfilter_im,
# unsharpmask_im, left_right_im,
# top_bottom_im, brightness_im, brightness_up_im, color_im, color_up_im, contrast_im,
# contrast_up_im, sharpness_im, sharpness_up_im] + rotate_list
# for index, file in enumerate(image_list):
# paths, files = os.path.split(image)
# files, suffix = os.path.splitext(files)
# new_file = os.path.join(paths, train_enhance_path, files + str(index) + suffix)
# file.save(new_file)
# logger.success(f'处理完成{{image}},还剩{{number}}张图片待增强')
@classmethod
def preprosess_save_images(self, image, number):
logger.info(f'开始处理{{image}}')
name = os.path.splitext(image)[0]
datagen = tf.keras.preprocessing.image.ImageDataGenerator(featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
zca_epsilon=1e-6,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
brightness_range=(0.7, 1.3),
shear_range=30,
zoom_range=0.2,
channel_shift_range=0.,
fill_mode='nearest',
cval=0.,
horizontal_flip=False,
vertical_flip=False,
rescale=1 / 255,
preprocessing_function=None,
data_format=None,
validation_split=0.0,
dtype=None)
img = tf.keras.preprocessing.image.load_img(image)
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, 0)
i = 0
for _ in datagen.flow(x, batch_size=1, save_to_dir=TRAIN_PATH, save_prefix=name, save_format='jpg'):
i += 1
if i == DATA_ENHANCEMENT:
break
logger.success(f'处理完成{{image}},还剩{{number}}张图片待增强')
# @classmethod
# # 展示图片处理后的效果
# def show_image(self, image_path):
# '''
# 展示图片处理后的效果
# :param image_path:
# :return:
# '''
# image = Image.open(image_path)
# while True:
# width, height = image.size
# if IMAGE_HEIGHT < height:
# resize_width = int(IMAGE_HEIGHT / height * width)
# image = image.resize((resize_width, IMAGE_HEIGHT))
# if IMAGE_WIDTH < width:
# resize_height = int(IMAGE_WIDTH / width * height)
# image = image.resize((IMAGE_WIDTH, resize_height))
# if IMAGE_WIDTH >= width and IMAGE_HEIGHT >= height:
# break
# width, height = image.size
# image = np.array(image)
# image = np.pad(image, ((0, IMAGE_HEIGHT - height), (0, IMAGE_WIDTH - width), (0, 0)), 'constant',
# constant_values=0)
# image = Image.fromarray(image)
# image_bytearr = io.BytesIO()
# image.save(image_bytearr, format='JPEG')
# plt.imshow(image)
# plt.show()
@staticmethod
def show_image(image):
image = Image.open(image)
if image.mode != 'RGB':
image = image.convert('RGB')
iw, ih = image.size
w, h = IMAGE_WIDTH, IMAGE_HEIGHT
scale = min(w / iw, h / ih)
nw = int(iw * scale)
nh = int(ih * scale)
image = image.resize((nw, nh), Image.BICUBIC)
if IMAGE_CHANNALS == 3:
new_image = Image.new('RGB', (IMAGE_WIDTH, IMAGE_HEIGHT), (128, 128, 128))
new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))
else:
new_image = Image.new('P', (IMAGE_WIDTH, IMAGE_HEIGHT), (128, 128, 128))
new_image = new_image.convert('L')
new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))
table = []
for i in range(256):
if i < THRESHOLD:
table.append(0)
else:
table.append(255)
new_image = new_image.point(table, 'L')
new_image.show()
@staticmethod
# 图片画框
def tagging_image(image_path, box):
im = imread(image_path)
plt.figure()
plt.imshow(im)
ax = plt.gca()
x = box[0]
y = box[1]
w = box[2]
h = box[3]
rect = Rectangle((x, y), w, h, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()
@staticmethod
def tagging_image2(image_path, box):
img = cv2.imread(image_path)
xmin = int(box[0])
ymin = int(box[1])
xmax = int(box[2])
ymax = int(box[3])
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), thickness=2)
cv2.imshow('example.jpg', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
class SSD_Generator(object):
def __init__(self, bbox_util, batch_size,
image_list, label_list, image_size, num_classes,
):
self.bbox_util = bbox_util
self.batch_size = batch_size
self.image_list = image_list
self.image_label = label_list
self.image_size = image_size
self.num_classes = num_classes - 1
def rand(self, a=0, b=1):
return np.random.rand() * (b - a) + a
def get_random_data(self, line, label, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5):
image = Image.open(line)
iw, ih = image.size
h, w = input_shape
box = label
# resize image
new_ar = w / h * self.rand(1 - jitter, 1 + jitter) / self.rand(1 - jitter, 1 + jitter)
scale = self.rand(.25, 2)
if new_ar < 1:
nh = int(scale * h)
nw = int(nh * new_ar)
else:
nw = int(scale * w)
nh = int(nw / new_ar)
image = image.resize((nw, nh), Image.BICUBIC)
# place image
dx = int(self.rand(0, w - nw))
dy = int(self.rand(0, h - nh))
new_image = Image.new('RGB', (w, h), (128, 128, 128))
new_image.paste(image, (dx, dy))
image = new_image
# flip image or not
flip = self.rand() < .5
if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)
# distort image
hue = self.rand(-hue, hue)
sat = self.rand(1, sat) if self.rand() < .5 else 1 / self.rand(1, sat)
val = self.rand(1, val) if self.rand() < .5 else 1 / self.rand(1, val)
x = cv2.cvtColor(np.array(image, np.float32) / 255, cv2.COLOR_RGB2HSV)
x[..., 0] += hue * 360
x[..., 0][x[..., 0] > 1] -= 1
x[..., 0][x[..., 0] < 0] += 1
x[..., 1] *= sat
x[..., 2] *= val
x[x[:, :, 0] > 360, 0] = 360
x[:, :, 1:][x[:, :, 1:] > 1] = 1
x[x < 0] = 0
image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB) * 255 # numpy array, 0 to 1
# correct boxes
box_data = np.zeros((len(box), 5))
if len(box) > 0:
np.random.shuffle(box)
box[:, [0, 2]] = box[:, [0, 2]] * nw / iw + dx
box[:, [1, 3]] = box[:, [1, 3]] * nh / ih + dy
if flip: box[:, [0, 2]] = w - box[:, [2, 0]]
box[:, 0:2][box[:, 0:2] < 0] = 0
box[:, 2][box[:, 2] > w] = w
box[:, 3][box[:, 3] > h] = h
box_w = box[:, 2] - box[:, 0]
box_h = box[:, 3] - box[:, 1]
box = box[np.logical_and(box_w > 1, box_h > 1)] # discard invalid box
box_data = np.zeros((len(box), 5))
box_data[:len(box)] = box
if len(box) == 0:
return image_data, []
if (box_data[:, :4] > 0).any():
return image_data, box_data
else:
return image_data, []
def generate(self):
for i in range(len(self.image_list)):
lines = self.image_list
label = self.image_label
inputs = []
targets = []
# n = len(lines)
for i in range(len(lines)):
img, y = self.get_random_data(lines[i], label[i], self.image_size[0:2])
# i = (i + 1) % n
if len(y) != 0:
boxes = np.array(y[:, :4], dtype=np.float32)
boxes[:, 0] = boxes[:, 0] / self.image_size[1]
boxes[:, 1] = boxes[:, 1] / self.image_size[0]
boxes[:, 2] = boxes[:, 2] / self.image_size[1]
boxes[:, 3] = boxes[:, 3] / self.image_size[0]
one_hot_label = np.eye(self.num_classes)[np.array(y[:, 4], np.int32)]
if ((boxes[:, 3] - boxes[:, 1]) <= 0).any() and ((boxes[:, 2] - boxes[:, 0]) <= 0).any():
continue
y = np.concatenate([boxes, one_hot_label], axis=-1)
y = self.bbox_util.assign_boxes(y)
inputs.append(img)
targets.append(y)
if len(targets) == self.batch_size:
tmp_inp = np.array(inputs)
tmp_targets = np.array(targets)
inputs = []
targets = []
yield tf.keras.applications.imagenet_utils.preprocess_input(tmp_inp), tmp_targets
class YOLO_Generator(object):
def rand(self, a=0, b=1):
return np.random.rand() * (b - a) + a
def merge_bboxes(self, bboxes, cutx, cuty):
merge_bbox = []
for i in range(len(bboxes)):
for box in bboxes[i]:
tmp_box = []
x1, y1, x2, y2 = box[0], box[1], box[2], box[3]
if i == 0:
if y1 > cuty or x1 > cutx:
continue
if y2 >= cuty and y1 <= cuty:
y2 = cuty
if y2 - y1 < 5:
continue
if x2 >= cutx and x1 <= cutx:
x2 = cutx
if x2 - x1 < 5:
continue
if i == 1:
if y2 < cuty or x1 > cutx:
continue
if y2 >= cuty and y1 <= cuty:
y1 = cuty
if y2 - y1 < 5:
continue
if x2 >= cutx and x1 <= cutx:
x2 = cutx
if x2 - x1 < 5:
continue
if i == 2:
if y2 < cuty or x2 < cutx:
continue