-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilIO.py
executable file
·1219 lines (909 loc) · 49.2 KB
/
utilIO.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
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import cv2
import numpy as np
import util
import utilConst
import utilDataGenerator
import utilMetrics
from collections import Counter
import math
# -----------------------------------------------------------------------------
def load_array_of_files(basepath, folders, truncate=False):
X = []
for folder in folders:
full_path = os.path.join(basepath, folder)
array_of_files = util.list_files(full_path, ext='png')
for fname_x in array_of_files:
X.append(fname_x)
if truncate:
X = X[:10]
return np.asarray(X)
# ----------------------------------------------------------------------------
def load_folds_names(dbname):
assert dbname in utilConst.ARRAY_DBS
train_folds = []
test_folds = []
DIBCO = [ ['Dibco/2009/handwritten_GR', 'Dibco/2009/printed_GR'],
['Dibco/2010/handwritten_GR'],
['Dibco/2011/handwritten_GR', 'Dibco/2011/printed_GR'],
['Dibco/2012/handwritten_GR'],
['Dibco/2013/handwritten_GR', 'Dibco/2013/printed_GR'],
['Dibco/2014/handwritten_GR'],
['Dibco/2016/handwritten_GR'] ]
DIBCO_synthetic_inv_col = [
['synthetic/inv_col/Dibco/2009/handwritten_GR', 'synthetic/inv_col/Dibco/2009/printed_GR'],
['synthetic/inv_col/Dibco/2010/handwritten_GR'],
['synthetic/inv_col/Dibco/2011/handwritten_GR', 'synthetic/inv_col/Dibco/2011/printed_GR'],
['synthetic/inv_col/Dibco/2012/handwritten_GR'],
['synthetic/inv_col/Dibco/2013/handwritten_GR', 'synthetic/inv_col/Dibco/2013/printed_GR'],
['synthetic/inv_col/Dibco/2014/handwritten_GR'],
['synthetic/inv_col/Dibco/2016/handwritten_GR'] ]
PALM_train = [ ['Palm/Challenge-1-ForTrain/gt1_GR'], ['Palm/Challenge-1-ForTrain/gt2_GR'] ]
PALM_test = [ ['Palm/Challenge-1-ForTest/gt1_GR'], ['Palm/Challenge-1-ForTest/gt2_GR'] ]
PALM_train_synthetic_inv_col = [ ['synthetic/inv_col/Palm/Challenge-1-ForTrain/gt1_GR'], ['synthetic/inv_col/Palm/Challenge-1-ForTrain/gt2_GR'] ]
PALM_test_synthetic_inv_col = [ ['synthetic/inv_col/Palm/Challenge-1-ForTest/gt1_GR'], ['synthetic/inv_col/Palm/Challenge-1-ForTest/gt2_GR'] ]
PHI_train = ['PHI/train/phi_GR']
PHI_test = ['PHI/test/phi_GR']
PHI_train_synthetic_inv_col = ['synthetic/inv_col/PHI/train/phi_GR']
PHI_test_synthetic_inv_col = ['synthetic/inv_col/PHI/test/phi_GR']
EINSIELDELN_train = ['Einsieldeln/train/ein_GR']
EINSIELDELN_test = ['Einsieldeln/test/ein_GR']
EINSIELDELN_train_synthetic_inv_col = ['synthetic/inv_col/Einsieldeln/train/ein_GR']
EINSIELDELN_test_synthetic_inv_col = ['synthetic/inv_col/Einsieldeln/test/ein_GR']
SALZINNES_train = ['Salzinnes/train/sal_GR']
SALZINNES_test = ['Salzinnes/test/sal_GR']
SALZINNES_train_synthetic_overexposure10 = ['synthetic/overexposure_g10/Salzinnes/train/sal_GR']
SALZINNES_test_synthetic_overexposure10 = ['synthetic/overexposure_g10/Salzinnes/test/sal_GR']
SALZINNES_train_synthetic_overexposure0_4 = ['synthetic/overexposure_g0.4/Salzinnes/train/sal_GR']
SALZINNES_test_synthetic_overexposure0_4 = ['synthetic/overexposure_g0.4/Salzinnes/test/sal_GR']
SALZINNES_train_synthetic_blur30x30 = ['synthetic/blur_30x30/Salzinnes/train/sal_GR']
SALZINNES_test_synthetic_blur30x30 = ['synthetic/blur_30x30/Salzinnes/test/sal_GR']
SALZINNES_train_synthetic_inv_col = ['synthetic/inv_col/Salzinnes/train/sal_GR']
SALZINNES_test_synthetic_inv_col = ['synthetic/inv_col/Salzinnes/test/sal_GR']
VOYNICH_test = ['Voynich/voy_GR']
VOYNICH_test_synthetic_inv_col = ['synthetic/inv_col/Voynich/voy_GR']
BDI_train = ['BDI/train/bdi11_GR']
BDI_test = ['BDI/test/bdi11_GR']
BDI_train_synthetic_inv_col = ['synthetic/inv_col/BDI/train/bdi11_GR']
BDI_test_synthetic_inv_col = ['synthetic/inv_col/BDI/test/bdi11_GR']
LRDE_DBD_train = ['LRDE_DBD/train/GR']
LRDE_DBD_test = ['LRDE_DBD/test/GR']
if dbname == 'dibco2016':
test_folds = DIBCO[6]
DIBCO.pop(6)
train_folds = [val for sublist in DIBCO for val in sublist]
elif dbname == 'dibco2016-ic':
test_folds = DIBCO_synthetic_inv_col[6]
DIBCO_synthetic_inv_col.pop(6)
train_folds = [val for sublist in DIBCO_synthetic_inv_col for val in sublist]
elif dbname == 'dibco2014':
test_folds = DIBCO[5]
DIBCO.pop(5)
train_folds = [val for sublist in DIBCO for val in sublist]
elif dbname == 'dibco2014-ic':
test_folds = DIBCO_synthetic_inv_col[5]
DIBCO_synthetic_inv_col.pop(5)
train_folds = [val for sublist in DIBCO_synthetic_inv_col for val in sublist]
elif dbname == 'palm0':
train_folds = PALM_train[0]
test_folds = PALM_test[0]
elif dbname == 'palm0-ic':
train_folds = PALM_train_synthetic_inv_col[0]
test_folds = PALM_test_synthetic_inv_col[0]
elif dbname == 'palm1':
train_folds = PALM_train[1]
test_folds = PALM_test[1]
elif dbname == 'palm1-ic':
train_folds = PALM_train_synthetic_inv_col[1]
test_folds = PALM_test_synthetic_inv_col[1]
elif dbname == 'phi':
train_folds = PHI_train
test_folds = PHI_test
elif dbname == 'phi-ic':
train_folds = PHI_train_synthetic_inv_col
test_folds = PHI_test_synthetic_inv_col
elif dbname == 'ein':
train_folds = EINSIELDELN_train
test_folds = EINSIELDELN_test
elif dbname == 'ein-ic':
train_folds = EINSIELDELN_train_synthetic_inv_col
test_folds = EINSIELDELN_test_synthetic_inv_col
elif dbname == 'sal':
train_folds = SALZINNES_train
test_folds = SALZINNES_test
elif dbname == 'sal-ic':
train_folds = SALZINNES_train_synthetic_inv_col
test_folds = SALZINNES_test_synthetic_inv_col
elif dbname == 'sal-oe10':
train_folds = SALZINNES_train_synthetic_overexposure10
test_folds = SALZINNES_test_synthetic_overexposure10
elif dbname == 'sal-oe0.4':
train_folds = SALZINNES_train_synthetic_overexposure0_4
test_folds = SALZINNES_test_synthetic_overexposure0_4
elif dbname == 'sal-blur30x30':
train_folds = SALZINNES_train_synthetic_blur30x30
test_folds = SALZINNES_test_synthetic_blur30x30
elif dbname == 'lrde':
train_folds = LRDE_DBD_train
test_folds = LRDE_DBD_test
elif dbname == 'voy':
train_folds = [val for sublist in DIBCO for val in sublist]
test_folds = VOYNICH_test
elif dbname == 'voy-ic':
train_folds = [val for sublist in DIBCO_synthetic_inv_col for val in sublist]
test_folds = VOYNICH_test_synthetic_inv_col
elif dbname == 'bdi':
train_folds = BDI_train
test_folds = BDI_test
elif dbname == 'bdi-ic':
train_folds = BDI_train_synthetic_inv_col
test_folds = BDI_test_synthetic_inv_col
elif dbname == 'all':
test_folds = [DIBCO[5], DIBCO[6]]
test_folds.append(PALM_test[0])
test_folds.append(PALM_test[1])
test_folds.append(PHI_test)
test_folds.append(EINSIELDELN_test)
test_folds.append(SALZINNES_test)
test_folds.append(LRDE_DBD_test)
DIBCO.pop(6)
DIBCO.pop(5)
train_folds = [[val for sublist in DIBCO for val in sublist]]
train_folds.append(PALM_train[0])
train_folds.append(PALM_train[1])
train_folds.append(PHI_train)
train_folds.append(EINSIELDELN_train)
train_folds.append(SALZINNES_train)
train_folds.append(LRDE_DBD_train)
test_folds = [val for sublist in test_folds for val in sublist] # transform to flat lists
train_folds = [val for sublist in train_folds for val in sublist]
elif dbname == 'all-ic':
test_folds = [DIBCO_synthetic_inv_col[5], DIBCO_synthetic_inv_col[6]]
test_folds.append(PALM_test_synthetic_inv_col[0])
test_folds.append(PALM_test_synthetic_inv_col[1])
test_folds.append(PHI_test_synthetic_inv_col)
test_folds.append(EINSIELDELN_test_synthetic_inv_col)
test_folds.append(SALZINNES_test_synthetic_inv_col)
DIBCO_synthetic_inv_col.pop(6)
DIBCO_synthetic_inv_col.pop(5)
train_folds = [[val for sublist in DIBCO_synthetic_inv_col for val in sublist]]
train_folds.append(PALM_train_synthetic_inv_col[0])
train_folds.append(PALM_train_synthetic_inv_col[1])
train_folds.append(PHI_train_synthetic_inv_col)
train_folds.append(EINSIELDELN_train_synthetic_inv_col)
train_folds.append(SALZINNES_train_synthetic_inv_col)
test_folds = [val for sublist in test_folds for val in sublist] # transform to flat lists
train_folds = [val for sublist in train_folds for val in sublist]
else:
raise Exception('Unknown database name')
return train_folds, test_folds
#------------------------------------------------------------------------------
def __calculate_img_diff(img_pr, img_y):
assert img_pr is not None and img_y is not None
assert img_pr.shape == img_y.shape
img_diff = np.zeros((img_pr.shape[0], img_pr.shape[1], 3), np.uint8)
for f in xrange(img_pr.shape[0]):
for c in xrange(img_pr.shape[1]):
if img_pr[f,c] == img_y[f,c]:
img_diff[f,c] = (0,0,0) if img_y[f,c] == 0 else (255,255,255)
else:
img_diff[f,c] = (0,0,255) if img_y[f,c] == 0 else (255,0,0)
return img_diff
def getPrecision(num_decimal):
precision = 1.
for _ in range(num_decimal):
precision /= 10.
return precision
def getHistogram(image, num_decimal):
tuple_prediction = tuple(image.reshape(1,-1)[0])
if num_decimal is not None:
tuple_prediction_round = []
for num in tuple_prediction:
if num > 0.01:
tuple_prediction_round.append(round(num, num_decimal))
#tuple_prediction_round = [round(num, num_decimal) for num in tuple_prediction]
tuple_prediction = tuple_prediction_round
precision = getPrecision(num_decimal)
value = 0.
value = round(value, num_decimal)
while value <= 1:
tuple_prediction.append(value)
value += precision
value = round(value, num_decimal)
histogram_prediction = Counter(tuple_prediction)
return histogram_prediction
# ----------------------------------------------------------------------------
def getHistograms(model, array_files_to_save, config, threshold = 0.5, num_decimal=None):
print('Calculating histogram...')
list_histograms = []
array_files = load_array_of_files(config.path, array_files_to_save)
for fname in array_files:
print('Processing image', fname)
fname_gt = fname.replace(utilConst.X_SUFIX, utilConst.Y_SUFIX)
img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(fname_gt, cv2.IMREAD_GRAYSCALE)
rows = img.shape[0]
cols = img.shape[1]
if img.shape[0] < config.window or img.shape[1] < config.window:
new_rows = config.window if img.shape[0] < config.window else img.shape[0]
new_cols = config.window if img.shape[1] < config.window else img.shape[1]
img = cv2.resize(img, (new_cols, new_rows), interpolation = cv2.INTER_CUBIC)
#cv2.imshow("img", img)
#cv2.waitKey(0)
finalImg = np.zeros(img.shape, dtype=float)
for (x, y, window) in utilDataGenerator.sliding_window(img, stepSize=config.step-5, windowSize=(config.window, config.window)):
if window.shape[0] != config.window or window.shape[1] != config.window:
continue
roi = img[y:(y + config.window), x:(x + config.window)].copy()
#cv2.imshow("roi", roi)
#cv2.waitKey(0)
roi = roi.reshape(1, config.window, config.window, 1)
roi = roi.astype('float32')
norm_type = '255'
roi = utilDataGenerator.normalize_data( roi, norm_type )
prediction = model.predict(roi)
prediction = prediction[:,2:prediction.shape[1]-2,2:prediction.shape[2]-2,:]
finalImg[y+2:(y + config.window-2), x+2:(x + config.window-2)] = prediction[0].reshape(config.window-4, config.window-4)
#cv2.imshow("finalImg", (1 - finalImg.astype('uint8')) * 255 )
#cv2.waitKey(0)
finalImg_bin = (finalImg >= threshold)
finalImg_bin = (1 - finalImg_bin.astype('uint8'))
import ntpath
filename = ntpath.basename(fname)
filename_out = filename.replace(".", "_"+str(config.type) + ".")
pathdir_outimage = "OUTPUT/probs/" + str(config.db1) +"-"+ str(config.db2) + "/"
util.mkdirp( os.path.dirname(pathdir_outimage) )
cv2.imwrite(pathdir_outimage + str(filename_out), finalImg_bin*255)
cv2.imwrite(pathdir_outimage + str(filename), 255-img*255)
histogram_prediction = getHistogram(finalImg, num_decimal)
list_histograms.append(histogram_prediction)
out_histogram_filename = fname.replace(config.path, 'OUTPUT/histogram')
out_histogram_filename = out_histogram_filename.replace(utilConst.X_SUFIX+'/', '/'+config.modelpath + '/')
out_histogram_filename = out_histogram_filename.replace(utilConst.WEIGHTS_DANN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace(utilConst.WEIGHTS_CNN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace(utilConst.LOGS_DANN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace(utilConst.LOGS_CNN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace('.h5', '/OUT_PR').replace('.npy', '/OUT_PR')
out_histogram_filename = str(out_histogram_filename.replace(".png", ".txt"))
print(' - Saving predicted image to:', out_histogram_filename)
util.mkdirp( os.path.dirname(out_histogram_filename) )
items_histogram = sorted(histogram_prediction.items())
str_prob = ""
str_value = ""
for prob, value in items_histogram:
str_prob += str(prob) + "\t"
str_value += str(value-1) + "\t"
str_histogram = str_prob + "\n" + str_value
#tuple_prediction_round = [str_prob for prob, value in items_histogram]
saveString(str_histogram, out_histogram_filename, True)
return list_histograms
def getNormalizedHistogram(histogram):
print ("---------------------")
print (histogram)
values = getHistogramValuesSorted(histogram)
print(values)
total = np.sum(values)
values = [v/float(total) for v in values]
print (values)
print ("---------------------")
return values
def getHistogramValuesSorted(histogram):
values = []
items_histogram = sorted(histogram.items())
for prob, value in items_histogram:
values.append(value)
return values
def getHistogramBins(sample_image, num_decimal):
tuple_sample = tuple(sample_image.reshape(1,-1)[0])
if num_decimal is not None:
tuple_sample_round = []
for num in tuple_sample:
if num > 0.01:
tuple_sample_round.append(round(num, num_decimal))
tuple_sample = tuple_sample_round
precision = 1.
for i in range(num_decimal):
precision /= 10.
value = 0.
value = round(value, num_decimal)
while value <= 1:
tuple_sample.append(value)
value += precision
value = round(value, num_decimal)
histogram_prediction = Counter(tuple_sample)
return histogram_prediction
def getHistogramDomain(array_files, model, config, num_decimal=None):
histogram_domain = None
array_files = load_array_of_files(config.path, array_files)
for fname in array_files:
print('Processing image', fname)
#fname_gt = fname.replace(utilConst.X_SUFIX, utilConst.Y_SUFIX)
img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
if img.shape[0] < config.window or img.shape[1] < config.window:
new_rows = config.window if img.shape[0] < config.window else img.shape[0]
new_cols = config.window if img.shape[1] < config.window else img.shape[1]
img = cv2.resize(img, (new_cols, new_rows), interpolation = cv2.INTER_CUBIC)
finalImg = np.zeros(img.shape, dtype=float)
for (x, y, window) in utilDataGenerator.sliding_window(img, stepSize=config.step-5, windowSize=(config.window, config.window)):
if window.shape[0] != config.window or window.shape[1] != config.window:
continue
roi = img[y:(y + config.window), x:(x + config.window)].copy()
roi = roi.reshape(1, config.window, config.window, 1)
roi = roi.astype('float32')
norm_type = '255'
roi = utilDataGenerator.normalize_data( roi, norm_type )
prediction = model.predict(roi)
prediction = prediction[:,2:prediction.shape[1]-2,2:prediction.shape[2]-2,:]
sample_prediction = prediction[0].reshape(config.window-4, config.window-4)
finalImg[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction
histogram_domain_fname = getHistogram(finalImg, num_decimal)
print(str(histogram_domain_fname))
if histogram_domain is None:
histogram_domain = histogram_domain_fname.copy()
else:
histogram_domain = histogram_domain + histogram_domain_fname
print(str(histogram_domain))
return histogram_domain
def predictSAE(
model_cnn,
config,
target_test_folds,
source_best_th_cnn,
threshold_correl_pearson,
num_decimal=None):
print('Calculating SAE...')
array_files = load_array_of_files(config.path, array_files_to_save)
list_target_best_fm_cnn = []
list_target_best_fm_cnn_inv = []
for fname in array_files:
print('Processing image', fname)
fname_gt = fname.replace(utilConst.X_SUFIX, utilConst.Y_SUFIX)
img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(fname_gt, cv2.IMREAD_GRAYSCALE)
if img.shape[0] < config.window or img.shape[1] < config.window:
new_rows = config.window if img.shape[0] < config.window else img.shape[0]
new_cols = config.window if img.shape[1] < config.window else img.shape[1]
img = cv2.resize(img, (new_cols, new_rows), interpolation = cv2.INTER_CUBIC)
finalImg = np.zeros(img.shape, dtype=float)
finalImg_bin = np.zeros(img.shape, dtype=float)
finalImg_cnn = np.zeros(img.shape, dtype=float)
finalImg_bin_cnn = np.zeros(img.shape, dtype=float)
for (x, y, window) in utilDataGenerator.sliding_window(img, stepSize=config.window-5, windowSize=(config.window, config.window)):
if window.shape[0] != config.window or window.shape[1] != config.window:
continue
roi = img[y:(y + config.window), x:(x + config.window)].copy()
roi = roi.reshape(1, config.window, config.window, 1)
roi = roi.astype('float32')
norm_type = '255'
roi = utilDataGenerator.normalize_data( roi, norm_type )
prediction_cnn = model_cnn.predict(roi)
prediction_cnn = prediction_cnn[:,2:prediction_cnn.shape[1]-2,2:prediction_cnn.shape[2]-2,:]
sample_prediction_cnn = prediction_cnn[0].reshape(config.window-4, config.window-4)
sample_prediction = sample_prediction_cnn
finalImg[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction
finalImg_bin[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction < threshold)
finalImg_cnn[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction_cnn
finalImg_bin_cnn[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction_cnn < threshold_cnn)
import ntpath
filename = ntpath.basename(fname)
filename_out = filename.replace(".", "_"+str(config.type) + ".")
filename_out_cnn = filename.replace(".", "_"+str(config.type) + "_cnn.")
pathdir_outimage = "OUTPUT/sae/probs/" + str(config.db1) +"-"+ str(config.db2) + "/"
util.mkdirp( os.path.dirname(pathdir_outimage) )
cv2.imwrite(pathdir_outimage + str(filename_out), finalImg_bin*255)
cv2.imwrite(pathdir_outimage + str(filename), 255-img*255)
cv2.imwrite(pathdir_outimage + str(filename_out_cnn), finalImg_bin_cnn*255)
finalImg_bin = (finalImg_bin>source_best_th_cnn)
finalImg_bin_cnn = (finalImg_bin_cnn>source_best_th_cnn)
gt = (gt > 0.5)
finalImg_bin_inv = (finalImg_bin<=source_best_th_cnn)
finalImg_bin_cnn_inv = (finalImg_bin_cnn<=source_best_th_cnn)
gt_inv = (gt <= 0.5)
print ("SAE:")
target_best_fm_cnn, _, _, _ = utilMetrics.calculate_best_fm(finalImg_bin_cnn, gt, None)
list_target_best_fm_cnn.append(target_best_fm_cnn)
print ("F1 at page-level")
str_f1 = "SAE:\t"
str_f1 += str(list_target_best_fm_cnn)
avg_cnn = np.average(list_target_best_fm_cnn)
str_f1 += ("\nAVERAGE SAE\n")
str_f1 += (str(avg_cnn))
print(str_f1)
pathdir_F1 = "OUTPUT/sae/probs/" + str(config.db1) +"-"+ str(config.db2) + "/" + "f1.txt"
saveString(str_f1, pathdir_F1, True)
return avg_cnn
def predictModelAtFullPage(
model,
config,
model_type,
array_files,
source_best_th,
num_decimal=None):
print('Calculating ' + str(model_type) + '...')
array_files = load_array_of_files(config.path, array_files)
list_target_best_fm = []
list_target_results = []
for fname in array_files:
print('Processing image', fname)
fname_gt = fname.replace(utilConst.X_SUFIX, utilConst.Y_SUFIX)
img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(fname_gt, cv2.IMREAD_GRAYSCALE)
if img.shape[0] < config.window or img.shape[1] < config.window:
new_rows = config.window if img.shape[0] < config.window else img.shape[0]
new_cols = config.window if img.shape[1] < config.window else img.shape[1]
img = cv2.resize(img, (new_cols, new_rows), interpolation = cv2.INTER_CUBIC)
finalImg_prob = np.zeros(img.shape, dtype=float)
finalImg_bin = np.zeros(img.shape, dtype=float)
for (x, y, window) in utilDataGenerator.sliding_window(img, stepSize=config.window-5, windowSize=(config.window, config.window)):
if window.shape[0] != config.window or window.shape[1] != config.window:
continue
roi = img[y:(y + config.window), x:(x + config.window)].copy()
roi = roi.reshape(1, config.window, config.window, 1)
roi = roi.astype('float32')
norm_type = '255'
roi = utilDataGenerator.normalize_data( roi, norm_type )
prediction_cnn = model.predict(roi)
prediction_cnn = prediction_cnn[:,2:prediction_cnn.shape[1]-2,2:prediction_cnn.shape[2]-2,:]
sample_prediction_cnn = prediction_cnn[0].reshape(config.window-4, config.window-4)
finalImg_prob[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction_cnn
finalImg_bin[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction_cnn < source_best_th)
import ntpath
filename = ntpath.basename(fname)
filename_out_prob = filename.replace(".", "_"+str(config.type) + ".")
filename_out_cnn = filename.replace(".", "_"+str(config.type) + "_"+ str(model_type) + ".")
pathdir_outimage = "OUTPUT/" + str(model_type) + "/probs/" + str(config.db1) +"-"+ str(config.db2) + "/"
util.mkdirp( os.path.dirname(pathdir_outimage) )
cv2.imwrite(pathdir_outimage + str(filename_out_prob), finalImg_prob*255)
cv2.imwrite(pathdir_outimage + str(filename), 255-img*255)
cv2.imwrite(pathdir_outimage + str(filename_out_cnn), finalImg_bin*255)
finalImg_bin = (finalImg_bin>source_best_th)
finalImg_bin = (finalImg_bin>source_best_th)
gt = (gt > 0.5)
print ("F1 at sample-level:")
target_best_fm_cnn, _, target_precision_cnn, target_recall_cnn = utilMetrics.calculate_best_fm(finalImg_bin, gt, None)
list_target_best_fm.append(target_best_fm_cnn)
list_target_results.append( (target_best_fm_cnn, target_precision_cnn, target_recall_cnn ))
str_f1 = "F1 at page-level:\t"
str_f1 += str(list_target_results)
avg_cnn = np.average(list_target_best_fm)
str_f1 += ("\nAVERAGE " + str(model_type) + "\n")
str_f1 += (str(avg_cnn))
print(str_f1)
pathdir_F1 = "OUTPUT/" + str(model_type) + "/probs/" + str(config.db1) +"-"+ str(config.db2) + "/" + "f1.txt"
saveString(str_f1, pathdir_F1, True)
return avg_cnn
def histogram_intersection(h1, h2):
assert(len(h1) == len(h2))
sm = 0
for i in range(len(h1)):
sm += min(h1[i], h2[i])
return sm
def log2(x):
return math.log(x)/math.log(2)
# calculate the kl divergence (measured in bits)
def kl_divergence_bits(p, q):
cte = 0.01
p2 = [p[i] + cte for i in range(len(p))]
q2 = [q[i] + cte for i in range(len(q))]
return sum([p2[i] * log2(p2[i]/q2[i]) for i in range(len(p2))])
# calculate the kl divergence (measured in nats)
def kl_divergence_nats(p, q):
cte = 0.01
p2 = [p[i] + cte for i in range(len(p))]
q2 = [q[i] + cte for i in range(len(q))]
return sum([p2[i] * math.log(p2[i]/q2[i]) for i in range(len(p2))])
# calculate the js divergence (measure in bits)
def js_divergence_bits(p, q):
m = [0.5 * (p[i] + q[i]) for i in range(len(q))]
return 0.5 * kl_divergence_bits(p, m) + 0.5 * kl_divergence_bits(q, m)
# calculate the js divergence (measured in nats)
def js_divergence_nats(p, q):
m = [0.5 * (p[i] + q[i]) for i in range(len(q))]
return 0.5 * kl_divergence_nats(p, m) + 0.5 * kl_divergence_nats(q, m)
def pearson_correlation(p, q):
return np.corrcoef(p, q)[0, 1]
def get_correlation_metric(correlation_type, p, q):
if correlation_type == "pearson":
return pearson_correlation(p, q)
elif correlation_type == "kl-nats":
return kl_divergence_nats(p, q)
elif correlation_type == "js-nats":
return js_divergence_nats(p, q)
elif correlation_type == "kl-bits":
return kl_divergence_bits(p, q)
elif correlation_type == "js-bits":
return js_divergence_bits(p, q)
elif correlation_type == "hist-intersection":
return histogram_intersection(p, q)
def get_all_correlation_metrics(p, q):
pearson = get_correlation_metric("pearson", p, q)
kl_nats = get_correlation_metric("kl-nats", p, q)
kl_bits = get_correlation_metric("kl-bits", p, q)
js_nats = get_correlation_metric("js-nats", p, q)
js_bits = get_correlation_metric("js-bits", p, q)
hist_inter = get_correlation_metric("hist-intersection", p, q)
print ("Pearson;KL (nats);KL (bits);JS (nats);JS (bits);Histogram intersection")
print (str(str(pearson) + ";"\
+ str(kl_nats) + ";"\
+ str(kl_bits) + ";"\
+ str(js_nats) + ";"\
+ str(js_bits) + ";"\
+ str(hist_inter)).replace(".", ","))
def predictAutoDANN_AtSampleLevel(
model_dann,
model_cnn,
config,
x_test_samples,
y_test_samples,
source_best_th_cnn,
source_best_th_dann,
correlation_type, threshold_correl,
histogram_source_cnn,
num_decimal):
predicts_auto = []
predicts_auto_ideal = []
#Histogram for source
list_histogram_source_cnn = histogram_source_cnn.values()
number_pixels_source = sum(list_histogram_source_cnn)
normalized_list_histogram_source_cnn = [number / float(number_pixels_source) for number in list_histogram_source_cnn]
count_cnn = 0
count_dann = 0
count_cnn_ideal = 0
count_dann_ideal = 0
idx_sample = 0
for idx_sample in range(len(x_test_samples)):
x_test_sample = x_test_samples[idx_sample]
y_test_sample = y_test_samples[idx_sample]
list_x_test_sample = list()
list_x_test_sample.append(x_test_sample)
list_x_test_sample_array = np.asarray(list_x_test_sample)
prediction_cnn = model_cnn.predict(list_x_test_sample_array)
sample_prediction_cnn = prediction_cnn[0].reshape(config.window, config.window)
#Histogram for target
histogram_prediction_cnn = getHistogramBins(prediction_cnn, num_decimal)
list_histogram_prediction_cnn = histogram_prediction_cnn.values()
number_pixels_target = sum(list_histogram_prediction_cnn)
normalized_list_histogram_prediction_cnn = [number / float(number_pixels_target) for number in list_histogram_prediction_cnn]
correlation = get_correlation_metric(correlation_type, normalized_list_histogram_prediction_cnn, normalized_list_histogram_source_cnn)
#get_all_correlation_metrics(normalized_list_histogram_prediction_cnn, normalized_list_histogram_source_cnn)
prediction_dann = model_dann.predict(list_x_test_sample_array)
sample_prediction_dann = prediction_dann[0].reshape(config.window, config.window)
if correlation > threshold_correl:
#SAE
threshold = source_best_th_cnn
sample_prediction = sample_prediction_cnn
count_cnn += 1
else:
#DANN
threshold = source_best_th_dann
sample_prediction = sample_prediction_dann
count_dann += 1
predicts_auto.append(sample_prediction > threshold)
sample_prediction_cnn_th = sample_prediction_cnn > source_best_th_cnn
sample_prediction_dann_th = sample_prediction_dann > source_best_th_dann
y_test_sample = y_test_sample[:,:,0].reshape(config.window, config.window)
#cv2.imwrite("prueba/cnn.png", sample_prediction_cnn_th*255)
#cv2.imwrite("prueba/dann.png", sample_prediction_dann_th*255)
#cv2.imwrite("prueba/gt.png", (y_test_sample>0.5)*255)
#print (sample_prediction_cnn_th.shape)
#print(sample_prediction_dann_th.shape)
#print(y_test_sample.shape)
target_best_fm_cnn, _, target_precision_cnn, target_recall_cnn = utilMetrics.calculate_best_fm(sample_prediction_cnn_th, y_test_sample > 0.5, None, False)
target_best_fm_dann, _, target_precision_dann, target_recall_dann = utilMetrics.calculate_best_fm(sample_prediction_dann_th, y_test_sample > 0.5, None, False)
if target_best_fm_cnn > target_best_fm_dann:
best_sample_prediction_th = sample_prediction_cnn_th
count_cnn_ideal += 1
else:
best_sample_prediction_th = sample_prediction_dann_th
count_dann_ideal += 1
#print("SAE: " + str(target_best_fm_cnn))
#print("DANN: " + str(target_best_fm_dann))
predicts_auto_ideal.append(best_sample_prediction_th)
print (config.db1 + "->" + config.db2 )
print ("Filters in target:")
print("SAE: " + str(count_cnn))
print("DANN: " + str(count_dann))
print("Total samples: " + str(count_cnn + count_dann))
print ("Ideal filters:")
print("SAE: " + str(count_cnn_ideal))
print("DANN: " + str(count_dann_ideal))
print("Total samples: " + str(count_cnn_ideal + count_dann_ideal))
predicts_auto = np.asarray(predicts_auto)
predicts_auto_ideal = np.asarray(predicts_auto_ideal)
assert(len(predicts_auto)==len(predicts_auto_ideal))
return predicts_auto, predicts_auto_ideal
def predictAUTODann(
model_dann,
model_cnn,
config,
array_files_to_save,
threshold_cnn,
threshold_dann,
correlation_type, threshold_correl,
histogram_source_cnn,
histogram_target_cnn,
num_decimal=None):
print('Calculating AUTODANN...')
#Histogram for source
list_histogram_source_cnn = [histogram_source_cnn[round(float(number)/len(histogram_source_cnn), 1)] for number in range(len(histogram_source_cnn))]
number_pixels_source = sum(list_histogram_source_cnn)
normalized_list_histogram_source_cnn = [number / float(number_pixels_source) for number in list_histogram_source_cnn]
list_histogram_target_cnn = [histogram_target_cnn[round(float(number)/len(histogram_target_cnn), 1)] for number in range(len(histogram_target_cnn))]
number_pixels_target = sum(list_histogram_target_cnn)
normalized_list_histogram_target_cnn = [number / float(number_pixels_target) for number in list_histogram_target_cnn]
print ("------------------------Normalized global histograms---------------------------")
print (config.db1)
print(normalized_list_histogram_source_cnn)
print (config.db2)
print(normalized_list_histogram_target_cnn)
array_files = load_array_of_files(config.path, array_files_to_save)
list_target_best_fm_autodann = []
list_target_results_autodann = []
list_target_best_fm_cnn = []
list_target_best_fm_dann = []
list_target_best_fm_ideal = []
count_cnn = 0
count_dann = 0
count_cnn_ideal = 0
count_dann_ideal = 0
for fname in array_files:
print('Processing image', fname)
fname_gt = fname.replace(utilConst.X_SUFIX, utilConst.Y_SUFIX)
img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(fname_gt, cv2.IMREAD_GRAYSCALE)
if img.shape[0] < config.window or img.shape[1] < config.window:
new_rows = config.window if img.shape[0] < config.window else img.shape[0]
new_cols = config.window if img.shape[1] < config.window else img.shape[1]
img = cv2.resize(img, (new_cols, new_rows), interpolation = cv2.INTER_CUBIC)
#cv2.imshow("img", img)
#cv2.waitKey(0)
finalImg = np.zeros(img.shape, dtype=float)
finalImg_bin = np.zeros(img.shape, dtype=float)
finalImg_sel = np.zeros(img.shape, dtype=float)
finalImg_ideal = np.zeros(img.shape, dtype=float)
finalImg_cnn = np.zeros(img.shape, dtype=float)
finalImg_dann = np.zeros(img.shape, dtype=float)
finalImg_bin_cnn = np.zeros(img.shape, dtype=float)
finalImg_bin_dann = np.zeros(img.shape, dtype=float)
finalImg_bin_ideal = np.zeros(img.shape, dtype=float)
for (x, y, window) in utilDataGenerator.sliding_window(img, stepSize=config.window-5, windowSize=(config.window, config.window)):
if window.shape[0] != config.window or window.shape[1] != config.window:
continue
roi = img[y:(y + config.window), x:(x + config.window)].copy()
#cv2.imshow("roi", roi)
#cv2.waitKey(0)
roi = roi.reshape(1, config.window, config.window, 1)
roi = roi.astype('float32')
norm_type = '255'
roi = utilDataGenerator.normalize_data( roi, norm_type )
prediction_cnn = model_cnn.predict(roi)
prediction_cnn = prediction_cnn[:,2:prediction_cnn.shape[1]-2,2:prediction_cnn.shape[2]-2,:]
sample_prediction_cnn = prediction_cnn[0].reshape(config.window-4, config.window-4)
#Histogram for target
histogram_prediction_cnn = getHistogramBins(prediction_cnn, num_decimal)
list_histogram_prediction_cnn = histogram_prediction_cnn.values()
number_pixels_target = sum(list_histogram_prediction_cnn)
normalized_list_histogram_prediction_cnn = [number / float(number_pixels_target) for number in list_histogram_prediction_cnn]
correlation = get_correlation_metric(correlation_type, normalized_list_histogram_prediction_cnn, normalized_list_histogram_source_cnn)
#get_all_correlation_metrics(normalized_list_histogram_prediction_cnn, normalized_list_histogram_source_cnn)
prediction_dann = model_dann.predict(roi)
prediction_dann = prediction_dann[:,2:prediction_dann.shape[1]-2,2:prediction_dann.shape[2]-2,:]
sample_prediction_dann = prediction_dann[0].reshape(config.window-4, config.window-4)
if correlation > threshold_correl:
#SAE
threshold = threshold_cnn
sample_prediction = sample_prediction_cnn
count_cnn += 1
else:
#DANN
threshold = threshold_dann
sample_prediction = sample_prediction_dann
finalImg_sel[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction >= 0.0)
count_dann += 1
finalImg[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction
finalImg_bin[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction < threshold)
finalImg_cnn[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction_cnn
finalImg_bin_cnn[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction_cnn < threshold_cnn)
finalImg_dann[y+2:(y + config.window-2), x+2:(x + config.window-2)] = sample_prediction_dann
finalImg_bin_dann[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (sample_prediction_dann < threshold_dann)
gt_sample = gt[y+2:(y + config.window-2), x+2:(x + config.window-2)]
sample_prediction_cnn_th = sample_prediction_cnn < threshold_cnn
sample_prediction_dann_th = sample_prediction_dann < threshold_dann
target_best_fm_cnn, _, target_precision_cnn, target_recall_cnn = utilMetrics.calculate_best_fm(sample_prediction_cnn_th, gt_sample > 0.5, None, False)
target_best_fm_dann, _, target_precision_dann, target_recall_dann = utilMetrics.calculate_best_fm(sample_prediction_dann_th, gt_sample > 0.5, None, False)
if target_best_fm_cnn > target_best_fm_dann:
best_sample_prediction_th = sample_prediction_cnn_th
best_sample_prediction = sample_prediction_cnn
count_cnn_ideal += 1
best_threshold_auto_ideal = threshold_cnn
else:
best_sample_prediction_th = sample_prediction_dann_th
best_sample_prediction = sample_prediction_dann
count_dann_ideal += 1
best_threshold_auto_ideal = threshold_dann
finalImg_bin_ideal[y+2:(y + config.window-2), x+2:(x + config.window-2)] = (best_sample_prediction_th)
#cv2.imshow("finalImg", (1 - finalImg.astype('uint8')) * 255 )
#cv2.waitKey(0)
import ntpath
filename = ntpath.basename(fname)
filename_out = filename.replace(".", "_"+str(config.type) + ".")
filename_out_sel = filename.replace(".", "_"+str(config.type) + "_sel.")
filename_out_cnn = filename.replace(".", "_"+str(config.type) + "_cnn.")
filename_out_dann = filename.replace(".", "_"+str(config.type) + "_dann.")
pathdir_outimage = "OUTPUT/auto_dann/probs/" + str(config.db1) +"-"+ str(config.db2) + "/"
util.mkdirp( os.path.dirname(pathdir_outimage) )
cv2.imwrite(pathdir_outimage + str(filename_out), finalImg_bin*255)
cv2.imwrite(pathdir_outimage + str(filename), 255-img*255)
cv2.imwrite(pathdir_outimage + str(filename_out_sel), finalImg_sel*255)
cv2.imwrite(pathdir_outimage + str(filename_out_cnn), finalImg_bin_cnn*255)
cv2.imwrite(pathdir_outimage + str(filename_out_dann), finalImg_bin_dann*255)
histogram_prediction = getHistogramBins(finalImg, num_decimal)
out_histogram_filename = fname.replace(config.path, 'OUTPUT/auto_dann/histogram')
out_histogram_filename = str(out_histogram_filename)
out_histogram_filename = out_histogram_filename.replace(utilConst.X_SUFIX+'/', '/'+config.modelpath + '/')
out_histogram_filename = out_histogram_filename.replace(utilConst.WEIGHTS_DANN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace(utilConst.WEIGHTS_CNN_FOLDERNAME+'/', '')
out_histogram_filename = out_histogram_filename.replace(utilConst.LOGS_DANN_FOLDERNAME+'/', '')