forked from nachifur/MulimgViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_img.py
1635 lines (1448 loc) · 64.8 KB
/
utils_img.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 wx
import numpy as np
import os
from PIL import Image, ImageDraw, ImageFont
from shutil import copyfile, move
from pathlib import Path
import csv
import copy
from utils import solve_factor, rgb2hex, change_order
class ImgUtils():
"""The set of functional programming modules"""
def __init__(self):
pass
def PIL2wx(self, image):
width, height = image.size
return wx.Bitmap.FromBufferRGBA(width, height, image.tobytes())
def add_alpha(self, img, alpha):
img_array = np.array(img)
temp = img_array[:, :, 0]
if img_array.shape[2] == 3:
img = np.concatenate((img_array, np.ones_like(
temp[:, :, np.newaxis])*alpha), axis=2)
elif img_array.shape[2] == 4:
img_array[:, :, 3] = np.ones_like(temp)*alpha
img = img_array
else:
pass
img = Image.fromarray(img.astype('uint8')).convert('RGBA')
return img
def sort_box_point(self, box_point, show_scale, img_resolution_origin, first_point=False):
# box_point = [x_0,y_0,x_1,y_1]
if box_point[2] < box_point[0]:
temp = box_point[0]
box_point[0] = box_point[2]
box_point[2] = temp
if box_point[3] < box_point[1]:
temp = box_point[1]
box_point[1] = box_point[3]
box_point[3] = temp
img_resolution = (np.array(img_resolution_origin)
* np.array(show_scale)).astype(np.int)
width = abs(box_point[0]-box_point[2])
height = abs(box_point[1]-box_point[3])
# limit box boundary
if first_point:
if box_point[2] > img_resolution[0]:
box_point[2] = img_resolution[0]
if box_point[0] < 0:
box_point[0] = 0
if box_point[3] > img_resolution[1]:
box_point[3] = img_resolution[1]
if box_point[1] < 0:
box_point[1] = 0
else:
if box_point[2] > img_resolution[0]:
box_point[2] = img_resolution[0]
box_point[0] = img_resolution[0]-width
elif box_point[0] < 0:
box_point[0] = 0
box_point[2] = width
if box_point[3] > img_resolution[1]:
box_point[3] = img_resolution[1]
box_point[1] = img_resolution[1]-height
elif box_point[1] < 0:
box_point[1] = 0
box_point[3] = height
return box_point
def draw_rectangle(self, img, xy_grids, bounding_boxs, color_list, line_width=2, single_box=False):
"""img
xy_grids: the position of bounding_boxs (list)
boxs_points: the four points that make up a bounding boxs
color_list: the color of bounding_boxs
"""
if single_box:
xy_grids = [xy_grids[0]]
else:
xy_grids = xy_grids
img_array = np.array(img)
i = 0
k = 0
for bounding_box in bounding_boxs:
x_0, y_0, x, y = bounding_box[0:4]
height = y-y_0
width = x - x_0
color = color_list[k]
draw_colour = np.array(
[color.red, color.green, color.blue, color.alpha])
for xy in xy_grids:
x_left_up = [x_0+xy[0], y_0+xy[1]]
x_left_down = [x_0+xy[0], y_0+xy[1]+height]
x_right_up = [x_0+xy[0]+width, y_0+xy[1]]
x_right_down = [x_0+xy[0]+width, y_0+xy[1]+height]
img_array[x_left_up[1]:x_left_down[1], x_left_up[0]:x_left_up[0]+line_width, :] = np.ones_like(
img_array[x_left_up[1]:x_left_down[1], x_left_up[0]:x_left_up[0]+line_width, :])*draw_colour
img_array[x_left_up[1]:x_left_up[1]+line_width, x_left_up[0]:x_right_up[0], :] = np.ones_like(
img_array[x_left_up[1]:x_left_up[1]+line_width, x_left_up[0]:x_right_up[0], :])*draw_colour
img_array[x_right_up[1]:x_right_down[1], x_right_up[0]-line_width:x_right_up[0], :] = np.ones_like(
img_array[x_right_up[1]:x_right_down[1], x_right_up[0]-line_width:x_right_up[0], :])*draw_colour
img_array[x_left_down[1]-line_width:x_left_down[1], x_left_up[0]:x_right_up[0], :] = np.ones_like(
img_array[x_left_down[1]-line_width:x_left_down[1], x_left_up[0]:x_right_up[0], :])*draw_colour
i += 1
k += 1
if k == len(color_list):
k = 0
img = Image.fromarray(img_array.astype('uint8')).convert('RGBA')
return img
def cal_magnifier_size(self, magnifier_scale, crop_size, img_mode, gap, img_size, num_box, show_original, gap_box_img, box_position=0, vertical=False):
delta_x = 0
delta_y = 0
width, height = crop_size
img_width, img_height = img_size
if img_mode:
gap = 0
num_box = 1
if vertical:
if magnifier_scale[0] != -1 or magnifier_scale[1] != -1:
if magnifier_scale[0] == -1:
magnifier_scale[0] = magnifier_scale[1]
if magnifier_scale[1] == -1:
magnifier_scale[1] = magnifier_scale[0]
# custom magnifier scale
to_height = int(height*magnifier_scale[1])
to_width = int(width*magnifier_scale[0])
height_all = to_height*num_box + (num_box-1)*gap
width_all = to_width
if img_height/height_all > img_width/width_all:
if to_width > img_width:
to_height = int(
img_width/to_width*to_height)
to_width = img_width
else:
if height_all >= img_height:
to_width = int(
img_height/height_all*to_width)
to_height = int(
(img_height-gap*(num_box-1))/num_box)
else:
# auto magnifier scale
to_height = int((img_height-gap*(num_box-1))/num_box)
to_width = int(to_height/height*width)
if to_width > img_width:
to_width = img_width
to_height = int(img_width/width*height)
height_all = (to_height*num_box +
(num_box-1)*gap)
delta_y = int((img_height-height_all)/2)
magnifier_img_all_size = [to_width, height_all]
# adjust box position
if box_position == 0: # middle bottom
delta_y = int((img_height-height_all)/2)
delta_x = gap_box_img
elif box_position == 2: # right bottom
delta_y = 0
delta_x = -to_width
elif box_position == 1: # left bottom
delta_y = img_height-height_all
delta_x = -to_width
elif box_position == 4: # right top
delta_y = 0
delta_x = -img_width
elif box_position == 3: # left top
delta_y = img_height-height_all
delta_x = -img_width
if not show_original:
magnifier_img_all_size = [to_width, height_all]
delta_y = 0
else:
if magnifier_scale[0] != -1 or magnifier_scale[1] != -1:
if magnifier_scale[0] == -1:
magnifier_scale[0] = magnifier_scale[1]
if magnifier_scale[1] == -1:
magnifier_scale[1] = magnifier_scale[0]
# custom magnifier scale
to_height = int(height*magnifier_scale[1])
to_width = int(width*magnifier_scale[0])
width_all = to_width*num_box + (num_box-1)*gap
height_all = to_height
if img_width/width_all > img_height/height_all:
if to_height > img_height:
to_width = int(
img_height/to_height*to_width)
to_height = img_height
else:
if width_all >= img_width:
to_height = int(
img_width/width_all*to_height)
to_width = int(
(img_width-gap*(num_box-1))/num_box)
else:
# auto magnifier scale
to_width = int((img_width-gap*(num_box-1))/num_box)
to_height = int(to_width/width*height)
if to_height > img_height:
to_height = img_height
to_width = int(img_height/height*width)
width_all = (to_width*num_box +
(num_box-1)*gap)
magnifier_img_all_size = [width_all, to_height]
# adjust box position
if box_position == 0: # middle bottom
delta_x = int((img_width-width_all)/2)
delta_y = gap_box_img
elif box_position == 1: # left bottom
delta_x = 0
delta_y = -to_height
elif box_position == 2: # right bottom
delta_x = img_width-width_all
delta_y = -to_height
elif box_position == 3: # left top
delta_x = 0
delta_y = -img_height
elif box_position == 4: # right top
delta_x = img_width-width_all
delta_y = -img_height
if not show_original:
delta_x = 0
to_resize = [to_width, to_height]
delta = [delta_x, delta_y]
return to_resize, delta, magnifier_img_all_size
def adjust_gap(self, target_length, number, length, gap, delta):
"""Adjust image gap. target_length>=sum(length)+sum(gap[0:-1])"""
number = len(length)
length_all = 0
for i in range(number):
length_all = length_all + length[i]
if i == number-1:
length_all = length_all + gap[i]
res_ = (target_length - sum(length) - sum(gap[0:-1]) - 2*delta)
if number == 1:
res_a = 0
else:
res_a = res_ / (number-1)
# Quantitative change causes qualitative change
add_ = 0
add_gap = 0
for i in range(number):
gap[i] = gap[i]+add_gap
add_ = add_+res_a
if add_ >= 1:
add_ -= 1
add_gap = 1
else:
add_gap = 0
return gap
def get_xy_grid(self, width, height, row, col, gap_x, gap_y, grid="rowcol"):
xy_grid = np.zeros((2, row, col)).astype(int)
if grid == "rowcol":
y = 0
for iy in range(row):
y = y + gap_y[iy]
x = 0
for ix in range(col):
if grid:
x = x + gap_x[ix]
else:
x = x + gap_x[iy]
xy_grid[:, iy, ix] = [x, y]
x = x + width[ix]
y = y + height[iy]
elif grid == "row":
y = 0
for iy in range(row):
y = y + gap_y[iy]
x = 0
for ix in range(col):
x = x + gap_x[iy]
xy_grid[:, iy, ix] = [x, y]
x = x + width[ix]
y = y + height[iy]
elif grid == "col":
x = 0
for ix in range(col):
x = x + gap_x[ix]
y = 0
for iy in range(row):
y = y + gap_y[ix]
xy_grid[:, iy, ix] = [x, y]
x = x + width[ix]
y = y + height[iy]
return xy_grid
def reshape_higher_dim(self, row_cols, img_list, vertical):
"""It is currently in 4 dimensions, and can be expanded to higher dimensions by simply modifying the code."""
id = 0
size = []
for i in range(len(row_cols)):
row_col = row_cols[i]
size = size+row_col
output = np.zeros(tuple(size)).astype(object)
for i in range(len(row_cols)):
row_col = row_cols[i]
if vertical:
row_col.reverse()
# level 0
for iy_0 in range(row_cols[0][0]):
for ix_0 in range(row_cols[0][1]):
id_0 = [iy_0, ix_0]
if vertical:
id_0.reverse()
# level 1
for iy_1 in range(row_cols[1][0]):
for ix_1 in range(row_cols[1][1]):
id_1 = [iy_1, ix_1]
if vertical:
id_1.reverse()
output[id_0[0], id_0[1], id_1[0],
id_1[1]] = img_list[id]
id += 1
return output
def layout_2d(self, layout_list, gap_color, img_list, img_preprocessing, img_preprocessing_sub, vertical):
# Two-dimensional arrangement
# layout_list = [
# [[row_2,col_2],[gap_x_2,gap_y_2],[width_2,height_2],[target_width_2, target_height_2],discard_table_2],
# [[row_1,col_1],[gap_x_1,gap_y_1],[width_1,height_1],[target_width_1, target_height_1],discard_table_1],
# [[row_0,col_0],[gap_x_0,gap_y_0],[width_0,height_0],[target_width_0, target_height_0],discard_table_0],
# ]
# Construct a two-dimensional grid
# when i >=1, width layout[2] and layout[6] can be empty
i = 0
xy_grids = []
if vertical:
grid = ["col", "row", "rowcol"]
else:
grid = ["row", "col", "rowcol"]
for layout in layout_list:
row, col = layout[0]
gap_x, gap_y = layout[1]
if grid[i] == "rowcol":
if isinstance(gap_x, list):
pass
else:
gap_x = [0]+[gap_x for i in range(col-1)]
if isinstance(gap_y, list):
pass
else:
gap_y = [0]+[gap_y for i in range(row-1)]
elif grid[i] == "col":
if isinstance(gap_x, list):
pass
else:
gap_x = [0]+[gap_x for i in range(col-1)]
if isinstance(gap_y, list):
pass
else:
gap_y = [0]+[gap_y for i in range(col-1)]
elif grid[i] == "row":
if isinstance(gap_x, list):
pass
else:
gap_x = [0]+[gap_x for i in range(row-1)]
if isinstance(gap_y, list):
pass
else:
gap_y = [0]+[gap_y for i in range(row-1)]
if i >= 1:
width = [target_width for i in range(col)]
height = [target_height for i in range(row)]
layout[2] = [width, height]
target_width = target_width*col+sum(gap_x[:])
target_height = target_height*row+sum(gap_y[:])
layout[3] = [target_width, target_height]
else:
width, height = layout[2]
target_width, target_height = layout[3]
xy_grids.append(self.get_xy_grid(
width, height, row, col, gap_x, gap_y, grid=grid[i]))
i += 1
# Construct a blank image
img = Image.new('RGBA', (target_width, target_height), gap_color)
# Fill the image
layout_list.reverse()
xy_grids.reverse()
Row = dict()
Col = dict()
Discard_table = dict()
for level in range(len(layout_list)):
Row['level_{}'.format(level)] = layout_list[level][0][0]
Col['level_{}'.format(level)] = layout_list[level][0][1]
Discard_table['level_{}'.format(level)] = layout_list[level][4]
# The number of img that a blank img can hold
image_num_capacity = Row['level_0'] * \
Col['level_0']*Row['level_1']*Col['level_1']
for i in range(len(img_list)):
img_list[i] = [img_list[i], i]
if len(img_list) < image_num_capacity:
empty_ = [[] for i in range(image_num_capacity-len(img_list))]
img_list = img_list+empty_
# Change the order of the image list
img_list = self.reshape_higher_dim([[Row['level_0'], Col['level_0']], [
Row['level_1'], Col['level_1']]], img_list, vertical)
xy_grids_output = []
xy_grids_id_list = []
# level_0
for iy_0 in range(Row['level_0']):
for ix_0 in range(Col['level_0']):
level = 0
x_offset_0 = xy_grids[level][0, iy_0, ix_0]
y_offset_0 = xy_grids[level][1, iy_0, ix_0]
# level_1
for iy_1 in range(Row['level_1']):
for ix_1 in range(Col['level_1']):
level = 1
x_offset_1 = xy_grids[level][0, iy_1, ix_1]
y_offset_1 = xy_grids[level][1, iy_1, ix_1]
if Discard_table['level_0'][iy_0, ix_0] and Discard_table['level_1'][iy_1, ix_1]:
im = None
else:
# img preprocessing
if img_list[iy_0, ix_0, iy_1, ix_1] != []:
im = img_list[iy_0, ix_0, iy_1, ix_1][0]
im = img_preprocessing(
im, id=iy_1*Col['level_1']+ix_1)
xy_grids_output.append(
[x_offset_0+x_offset_1, y_offset_0+y_offset_1])
xy_grids_id_list.append(
img_list[iy_0, ix_0, iy_1, ix_1][1])
else:
im = None
if im:
# level_2
i = 0
for iy_2 in range(Row['level_2']):
for ix_2 in range(Col['level_2']):
level = 2
x_offset_2 = xy_grids[level][0, iy_2, ix_2]
y_offset_2 = xy_grids[level][1, iy_2, ix_2]
x = x_offset_0+x_offset_1+x_offset_2
y = y_offset_0+y_offset_1+y_offset_2
# img preprocessing
if Discard_table['level_2'][iy_2, ix_2]:
pass
else:
if img_preprocessing_sub[iy_2, ix_2] != []:
im_ = img_preprocessing_sub[iy_2, ix_2](
im, id=img_list[iy_0, ix_0, iy_1, ix_1][1])
if im_:
img.paste(im_, (x, y))
i += 1
return img, xy_grids_output, xy_grids_id_list
def identity_transformation(self, img, id=0):
return img
def cal_txt_size(self, title_list, standard_size, font, font_size, vertical):
im = Image.new('RGBA', (256, 256), 0)
draw = ImageDraw.Draw(im)
title_size = []
for title in title_list:
title_size.append(draw.multiline_textsize(title, font))
title_size = np.array(title_size)
title_size = title_size.reshape(-1, 2)
# adjust title names
for i in range(len(title_list)):
split_num = 2
title = title_list[i]
str_ = title_list[i]
while title_size[i, 0] > standard_size:
ids = [0] + [(i+1)*int(len(title)/split_num)
for i in range(split_num-1)]
str_ = ""
k = 0
for id in ids:
if k == 0:
str_ = str_ + title[id:ids[k+1]]
elif k+1 < len(ids):
str_ = str_ + "\n" + title[id:ids[k+1]]
else:
str_ = str_ + "\n"+title[id:]
k += 1
size_edit = draw.multiline_textsize(str_, font)
title_size[i, :] = size_edit
split_num = split_num+1
if split_num > len(title):
break
title_list[i] = str_
# re-calculate title size
title_size = []
for title in title_list:
title_size.append(draw.multiline_textsize(title, font))
title_size = np.array(title_size)
title_size = title_size.reshape(-1, 2)
# final title list
title_list = title_list
title_max_size = [standard_size,
(title_size[:, 1]).max()+int(font_size/4)]
if vertical:
title_max_size.reverse()
return title_size, title_list, title_max_size
class ImgDatabase():
"""Multi-image database.
Multi-image browsing, path management, loading multi-image data, automatic layout layout, etc. """
def init(self, input_path, type, parallel_to_sequential=False, action_count=None, img_count=None):
self.input_path = input_path
self.type = type
self.parallel_to_sequential = parallel_to_sequential
self.init_flist()
if self.parallel_to_sequential:
list_ = []
for name_list in self.name_list:
list_ = list_+name_list.tolist()
self.img_num = len(list_)
else:
self.img_num = len(self.name_list)
# self.set_count_per_action(1)
if img_count:
self.img_count = img_count
else:
self.img_count = 0
if action_count:
self.action_count = action_count
else:
self.action_count = 0
def init_flist(self):
self.csv_flag = 0
if self.type == 0:
# one_dir_mul_dir_auto
cwd = Path(self.input_path)
self.path_list = [str(path)
for path in cwd.iterdir() if cwd.is_dir() and path.is_dir()]
if len(self.path_list) == 0:
self.path_list = [self.input_path]
self.path_list = np.sort(self.path_list)
self.name_list = self.get_name_list()
elif self.type == 1:
# one_dir_mul_dir_manual
self.path_list = [path
for path in self.input_path if Path(path).is_dir()]
if len(self.path_list) != 0:
self.name_list = self.get_name_list()
else:
self.name_list = []
elif self.type == 2:
# one_dir_mul_img
self.path_list = [self.input_path]
self.path_list = np.sort(self.path_list)
self.name_list = self.get_name_list()
elif self.type == 3:
# read file list from a list file
self.path_list = self.get_path_list_from_lf()
self.name_list = self.get_name_list_from_lf()
else:
self.path_list = []
self.name_list = []
def get_path_list_from_lf(self):
format_group = [".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"]
if Path(self.input_path).suffix.lower() == '.txt':
with open(self.input_path, "r") as f:
dataset = f.read().split('\n')
elif Path(self.input_path).suffix.lower() == '.csv':
with open(self.input_path, 'r', newline='') as csvfile:
dataset = list(csv.reader(csvfile))
dataset_ = []
row = len(dataset)
col = len(dataset[0])
for items in dataset:
for item in items:
dataset_.append(item)
dataset = dataset_
self.csv_flag = 1
self.csv_row_col = [row, col]
else:
dataset = []
if len(dataset) == 0:
validdataset = []
self.dataset_mode = False
elif len(dataset) < 100:
validdataset = [item for item in dataset if Path(
item).is_file() and Path(item).suffix.lower() in format_group]
self.dataset_mode = False
else:
validdataset = dataset
self.dataset_mode = True
return validdataset
def get_name_list_from_lf(self):
if self.path_list == []:
return []
dataset = np.array(self.path_list).ravel().tolist()
namelist = [Path(item).name for item in dataset]
return namelist
def get_name_list(self):
i = 0
output = []
for path_ in self.path_list:
no_check_list = [str(f.name)
for f in Path(path_).iterdir()]
if len(no_check_list) > 100:
self.dataset_mode = True
no_check_list = np.sort(no_check_list)
output.append(no_check_list)
else:
self.dataset_mode = False
check_list = [str(f.name) for f in Path(path_).iterdir(
) if f.is_file() and f.suffix.lower() in self.format_group]
check_list = np.sort(check_list)
output.append(check_list)
if not self.parallel_to_sequential:
if i == 0:
break
i += 1
if self.parallel_to_sequential:
return output
else:
return output[0]
def add(self):
if self.action_count < self.max_action_num-1:
self.action_count += 1
self.img_count += self.count_per_action
def subtract(self):
if self.action_count > 0:
self.action_count -= 1
self.img_count -= self.count_per_action
def set_count_per_action(self, count_per_action):
self.count_per_action = count_per_action
if self.img_num % self.count_per_action:
self.max_action_num = int(self.img_num/self.count_per_action)+1
else:
self.max_action_num = int(self.img_num/self.count_per_action)
def set_action_count(self, action_count):
if action_count < self.max_action_num:
self.action_count = action_count
self.img_count = self.count_per_action*self.action_count
def layout_advice(self):
if self.csv_flag:
return self.csv_row_col
else:
if self.type == 0 or self.type == 1:
if self.parallel_to_sequential:
num_all = len(self.name_list[0])
else:
num_all = len(self.path_list)
else:
num_all = self.img_num
list_factor = solve_factor(num_all)
if len(list_factor) == 0:
row_col = [1, num_all]
else:
if len(list_factor) <= 1:
num_all = num_all+1
list_factor = solve_factor(num_all)
row = list_factor[int(len(list_factor)/2)-1]
row = int(row)
col = int(num_all/row)
if row < col:
row_col = [row, col]
else:
row_col = [col, row]
if row_col[0] >= 50:
row_col[0] = 50
if row_col[1] >= 50:
row_col[1] = 50
return row_col
def get_flist(self):
if self.type == 0 or self.type == 1:
# one_dir_mul_dir_auto, one_dir_mul_dir_manual
if self.parallel_to_sequential:
flist_all = []
for i in range(len(self.path_list)):
flist_all = flist_all + \
[str(Path(self.path_list[i])/self.name_list[i][k])
for k in range(len(self.name_list[i]))]
try:
flist = [flist_all[k] for k in range(
self.img_count, self.img_count+self.count_per_action)]
except:
flist = [flist_all[k]
for k in range(self.img_count, self.img_num)]
else:
flist = []
for i in range(len(self.path_list)):
for k in range(self.img_count, self.img_count+self.count_per_action):
try:
flist += [str(Path(self.path_list[i]) /
self.name_list[k])]
except:
flist += [str(Path(self.path_list[i]) /
self.name_list[-1])]
elif self.type == 2:
# one_dir_mul_img
try:
flist = [str(Path(self.path_list[0])/self.name_list[i])
for i in range(self.img_count, self.img_count+self.count_per_action)]
except:
flist = [str(Path(self.path_list[0])/self.name_list[i])
for i in range(self.img_count, self.img_num)]
elif self.type == 3:
# one file list
# flist = self.path_list
try:
flist = [str(Path(self.path_list[i]))
for i in range(self.img_count, self.img_count+self.count_per_action)]
except:
flist = [str(Path(self.path_list[i]))
for i in range(self.img_count, self.img_num)]
else:
flist = []
self.flist = flist
return flist
def get_dir_num(self):
num = len(self.path_list)
return num
class ImgManager(ImgDatabase):
"""Multi-image manager.
Multi-image parallel magnification, stitching, saving, rotation"""
def __init__(self):
self.layout_params = []
self.gap_color = (0, 0, 0, 0)
self.img = ""
self.gap_alpha = 255
self.img_alpha = 255
self.img_stitch_mode = 0 # 0:"fill" 1:"crop" 2:"resize"
self.img_resolution = [-1, -1]
self.custom_resolution = False
self.img_num = 0
self.format_group = [".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif"]
self.crop_points = []
self.draw_points = []
self.ImgF = ImgUtils()
def get_img_list(self):
img_list = []
for path in self.flist:
path = Path(path)
if path.is_file() and path.suffix.lower() in self.format_group:
img_list.append(Image.open(path).convert('RGB'))
else:
pass
# resolution
width_ = []
height_ = []
for img in img_list:
width, height = img.size
width_.append(width)
height_.append(height)
width_ = np.sort(width_)
height_ = np.sort(height_)
if self.img_stitch_mode == 2:
width = max(width_)
height = max(height_)
elif self.img_stitch_mode == 1:
width = np.min(width_)
height = np.min(height_)
elif self.img_stitch_mode == 0:
if len(width_) > 3:
width = np.mean(width_[1:-1])
height = np.mean(height_[1:-1])
else:
width = np.mean(width_)
height = np.mean(height_)
if self.layout_params[6][0] == -1 or self.layout_params[6][1] == -1:
if self.layout_params[6][0] == -1 and self.layout_params[6][1] == -1:
self.img_resolution_origin = [int(width), int(height)]
elif self.layout_params[6][0] == -1 and self.layout_params[6][1] != -1:
self.img_resolution_origin = [
int(width*self.layout_params[6][1]/height), int(self.layout_params[6][1])]
elif self.layout_params[6][0] != -1 and self.layout_params[6][1] == -1:
self.img_resolution_origin = [int(self.layout_params[6][0]), int(
height*self.layout_params[6][0]/width)]
self.custom_resolution = False
else:
self.img_resolution_origin = [int(i)
for i in self.layout_params[6]]
self.custom_resolution = True
self.img_list = img_list
def set_scale_mode(self, img_mode=0):
"""img_mode, 0: show, 1: save"""
if img_mode == 0:
self.scale = self.layout_params[4]
elif img_mode == 1:
self.scale = self.layout_params[5]
self.img_resolution = (
np.array(self.img_resolution_origin) * np.array(self.scale)).astype(np.int)
if img_mode == 0:
self.img_resolution_show = self.img_resolution
elif img_mode == 1:
self.img_resolution_save = self.img_resolution
self.img_resolution = self.img_resolution.tolist()
return self.img_resolution
def stitch_img_init(self, img_mode, draw_points):
"""img_mode, 0: show, 1: save"""
# init
self.get_img_list() # Generate image list
self.set_scale_mode(img_mode=img_mode)
if img_mode == 0:
self.draw_points = draw_points
self.vertical = self.layout_params[-1]
img_preprocessing_sub = []
layout_level_2 = []
width_2, height_2 = [[], []]
gap_x_y_2 = [[], []]
# show original img
self.show_original = self.layout_params[16]
self.one_img = self.layout_params[20]
num_per_img = self.layout_params[1] if self.one_img else 1
self.to_size = [
int(self.img_resolution[0]/num_per_img), self.img_resolution[1]]
if self.show_original:
layout_level_2.append(1)
img_preprocessing_sub.append(self.ImgF.identity_transformation)
width_2.append(self.to_size[0])
height_2.append(self.to_size[1])
gap_x_y_2[0].append(0)
gap_x_y_2[1].append(0)
else:
layout_level_2.append(0)
# show magnifier img
self.magnifier_flag = self.layout_params[7]
self.show_crop = self.layout_params[18]
if layout_level_2[0]==0:
self.box_position=0
else:
self.box_position=self.layout_params[21]
if len(draw_points) == 0:
self.show_crop = 0
if self.show_crop:
layout_level_2.append(1)
self.crop_points_process(copy.deepcopy(
draw_points), img_mode=img_mode)
# get magnifier size
crop_width = self.crop_points[0][2]-self.crop_points[0][0]
crop_height = self.crop_points[0][3]-self.crop_points[0][1]
_, delta, magnifier_img_all_size = self.ImgF.cal_magnifier_size(
self.layout_params[8], [crop_width, crop_height], 0, self.layout_params[3][4], self.to_size, len(self.crop_points), self.show_original, self.layout_params[3][3], box_position=self.box_position, vertical=self.vertical)
img_preprocessing_sub.append(self.magnifier_preprocessing)
if layout_level_2[0]==0:
gap_x_y_2[0].append(0)
gap_x_y_2[1].append(0)
width_2.append(magnifier_img_all_size[0])
height_2.append(magnifier_img_all_size[1])
else:
gap_x_y_2[0].append(delta[0])
gap_x_y_2[1].append(delta[1])
if self.layout_params[21] == 0:
width_2.append(magnifier_img_all_size[0])
height_2.append(magnifier_img_all_size[1])
else:
width_2.append(0)
height_2.append(0)
else:
layout_level_2.append(0)
# show title
self.title_setting = self.layout_params[17]
if self.title_setting[1]:
if len(width_2) != 0:
title_width_height = self.title_init(width_2, height_2)
if self.title_setting[2]:
# up
width_2 = [title_width_height[0]]+width_2
height_2 = [title_width_height[1]]+height_2
img_preprocessing_sub = [
self.title_preprocessing] + img_preprocessing_sub
layout_level_2 = [1]+layout_level_2
if self.vertical:
gap_x_y_2[0][0] = self.layout_params[3][3]
else:
gap_x_y_2[1][0] = self.layout_params[3][3]
gap_x_y_2[0] = [0]+gap_x_y_2[0]
gap_x_y_2[1] = [0]+gap_x_y_2[1]
else:
# down
width_2.append(title_width_height[0])
height_2.append(title_width_height[1])
img_preprocessing_sub.append(self.title_preprocessing)
layout_level_2.append(1)
if self.vertical:
gap_x_y_2[1].append(0)
if gap_x_y_2[0][-1] >= 0:
gap_x_y_2[0].append(self.layout_params[3][3])
else:
gap_x_y_2[0].append(-gap_x_y_2[0]
[-1]+self.layout_params[3][3])
else:
gap_x_y_2[0].append(0)
if gap_x_y_2[1][-1] >= 0:
gap_x_y_2[1].append(self.layout_params[3][3])
else:
gap_x_y_2[1].append(-gap_x_y_2[1]
[-1]+self.layout_params[3][3])