Repository navigation
Expand file tree
/
Copy pathparse_live2d.py
More file actions
1560 lines (1317 loc) · 65.7 KB
/
Copy pathparse_live2d.py
File metadata and controls
1560 lines (1317 loc) · 65.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PIL import Image
import random
import os
import os.path as osp
import numpy as np
from tqdm import tqdm
from einops import reduce
import click
import cv2
import sys
from utils.io_utils import load_exec_list, pil_pad_square, pil_ensure_rgb, imglist2imgrid, find_all_files_with_name, dict2json, json2dict, load_image, save_tmp_img
from live2d.scrap_model import Live2DScrapModel, compose_from_drawables, load_detected_character, init_drawable_visible_map, Drawable
from utils.visualize import pil_draw_text, visualize_segs, VALID_FACE_GROUPS, FACE_LABEL2NAME, visualize_facedet_output, LEFT_EYEBROW, RIGHT_EYEBROW, show_factorization_on_image
from utils.cv import mask2rle, rle2mask
exclude_cls = \
{
'1girl',
'smile',
'simple_background',
'white_background',
'solo',
'closed_mouth',
'looking_at_viewer',
'standing',
'full_body',
'virtual_youtuber',
'tachi-e',
'elf',
'transparent_background',
'blush',
'straight-on',
'looking_to_the_side',
'expressionless',
'holding',
}
@click.group()
def cli():
"""live2d scripts.
"""
@cli.command('build_live2d_exec_list')
@click.option('--srcd')
@click.option('--save_dir', default=None)
@click.option('--filter_p', default=None)
@click.option('--target_fno', default=-1)
@click.option('--num_chunk', default=-1)
@click.option('--save_name', default='exec_list')
def build_live2d_exec_list(srcd, save_dir, filter_p, target_fno, num_chunk, save_name):
exec_list = find_all_files_with_name(srcd, name='final', exclude_suffix=True)
tgt_list = []
filter_set = set()
if filter_p is not None:
filter_set = set(load_exec_list(filter_p))
for d in exec_list:
if d in filter_set or osp.dirname(d) in filter_set:
continue
dname = osp.basename(osp.dirname(d))
if target_fno > 0:
fno = dname.split('-')[-1]
if not fno.isdigit():
print(f'{d} is not a valid path')
continue
fno = int(fno)
if fno == target_fno:
tgt_list.append(d)
else:
tgt_list.append(d)
random.shuffle(tgt_list)
print(f'num samples: {len(tgt_list)}')
if save_dir is None:
save_dir = srcd
savep = osp.join(save_dir, f'{save_name}.txt')
with open(savep, 'w', encoding='utf8') as f:
f.write('\n'.join(tgt_list))
print(f'exec list saved to {savep}')
if num_chunk > 0:
world_size = num_chunk
for ii in range(world_size):
t = load_exec_list(tgt_list, ii, world_size=world_size)
savep = osp.join(save_dir, f'{save_name}{ii}.txt')
with open(savep, 'w', encoding='utf8') as f:
f.write('\n'.join(t))
print(f'exec list saved to {savep}')
print(f'chunk {ii} num samples: {len(t)}')
@cli.command('further_extr')
@click.option('--exec_list')
@click.option('--rank_to_worldsize', default=None)
@click.option('--save_name', default=None)
def _further_extr(*args, **kwargs):
further_extr(*args, **kwargs)
def further_extr(exec_list, rank_to_worldsize=None, save_name=None):
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
eye_mesh_dict = {
'1-2-3-2-2+eyebgs-l': 'eyebgsl',
'1-2-3-3-2+irides-l': 'iridesl',
'1-2-3-1-2+eyelashs-l': 'eyelashsl',
'1-2-3-2-1+eyebgs-r': 'eyebgsr',
'1-2-3-3-1+irides-r': 'iridesr',
'1-2-3-1-1+eyelashs-r': 'eyelashsr',
'1-2-1-1+eyebrows-r': 'eyebrowr',
'1-2-1-2+eyebrows-l': 'eyebrowl'
}
for p in tqdm(exec_list):
try:
fp = osp.join(p, 'face_parsing')
parts_dict_exist = osp.exists(osp.join(fp, 'parts.json'))
if parts_dict_exist:
parts = json2dict(osp.join(fp, 'parts.json'))
eye_parts = {}
for k, n in eye_mesh_dict.items():
imgp = osp.join(fp, k + '.png')
if not osp.exists(imgp) or not parts_dict_exist:
eye_parts[n] = {'area': 0}
continue
img = np.array(Image.open(osp.join(fp, k + '.png')))
pd = parts[k]
x, y, w, h = pd['x'], pd['y'], pd['w'], pd['h']
mask = img[..., -1] > 15
rect = cv2.boundingRect(cv2.findNonZero(mask.astype(np.uint8)))
xyxy = [x, y, x + w, y + h]
rect = [rect[0] + x, rect[1] + y, rect[2], rect[3]]
rect[2] += rect[0]
rect[3] += rect[1]
eye_parts[n] = {
'img': img,
'xyxy': xyxy,
'mask': mask,
'rect': rect,
'area': np.sum(mask)
}
lmodel = Live2DScrapModel(p, pad_to_square=False, crop_to_final=False)
lmodel.init_drawable_visible_map()
lmodel.load_body_parsing()
max_d = len(lmodel.drawables) + 1
face_max_idx = -1
face_min_idx = max_d
neck_max_idx = -1
neck_min_idx = max_d
nose_max_idx = -1
nose_min_idx = max_d
mouth_max_idx = -1
mouth_min_idx = max_d
for d in lmodel.drawables:
if d.body_part_tag == 'nose':
nose_max_idx = max(d.idx, nose_max_idx)
nose_min_idx = min(d.idx, nose_min_idx)
elif d.body_part_tag == 'mouth':
mouth_max_idx = max(d.idx, mouth_max_idx)
mouth_min_idx = min(d.idx, mouth_min_idx)
for d in lmodel.drawables:
if d.body_part_tag == 'face':
tgt_max_idx = min(d.idx, nose_min_idx, mouth_min_idx)
face_max_idx = max(tgt_max_idx, face_max_idx)
face_min_idx = min(d.idx, face_min_idx)
hair_split_idx = face_max_idx
for d in lmodel.drawables:
if d.body_part_tag is None or 'hair' not in d.body_part_tag:
continue
if d.idx > hair_split_idx:
d.body_part_tag = 'front hair'
else:
d.body_part_tag = 'back hair'
eyel_xyxy = [lmodel.final.shape[1], lmodel.final.shape[0], 0, 0]
eyer_xyxy = [lmodel.final.shape[1], lmodel.final.shape[0], 0, 0]
for k in {'iridesl', 'eyebgsl', 'eyelashsl'}:
if 'xyxy' in eye_parts[k]:
eyel_xyxy[0] = min(eyel_xyxy[0], eye_parts[k]['xyxy'][0])
eyel_xyxy[1] = min(eyel_xyxy[1], eye_parts[k]['xyxy'][1])
eyel_xyxy[2] = max(eyel_xyxy[2], eye_parts[k]['xyxy'][2])
eyel_xyxy[3] = max(eyel_xyxy[3], eye_parts[k]['xyxy'][3])
for k in {'iridesr', 'eyebgsr', 'eyelashsr'}:
if 'xyxy' in eye_parts[k]:
eyer_xyxy[0] = min(eyer_xyxy[0], eye_parts[k]['xyxy'][0])
eyer_xyxy[1] = min(eyer_xyxy[1], eye_parts[k]['xyxy'][1])
eyer_xyxy[2] = max(eyer_xyxy[2], eye_parts[k]['xyxy'][2])
eyer_xyxy[3] = max(eyer_xyxy[3], eye_parts[k]['xyxy'][3])
for d in lmodel.drawables:
if d.body_part_tag != 'eyes':
continue
eye_tag = None
score = 0.
eye_scores = {}
for ek, ed in eye_parts.items():
if ed['area'] == 0:
eye_scores[ek] = [None] * 4
continue
mask = ed['mask']
area, u_area, i_area = d.mask_union_intersection(mask, ed['xyxy'], final_vis_mask=True)
eye_scores[ek] = [area, u_area, i_area, ed['area']]
irides_scores, bg_scores = None, None
eyelash_scores = eyebrow_scores = None
if eye_scores['iridesl'][0] is not None:
irides_scores = eye_scores['iridesl']
bg_scores = eye_scores['eyebgsl']
elif eye_scores['iridesr'][0] is not None:
irides_scores = eye_scores['iridesr']
bg_scores = eye_scores['eyebgsr']
if eye_scores['eyelashsr'][0] is not None:
eyelash_scores = eye_scores['eyelashsr']
elif eye_scores['eyelashsl'][0] is not None:
eyelash_scores = eye_scores['eyelashsl']
if eye_scores['eyebrowr'][0] is not None:
eyebrow_scores = eye_scores['eyebrowr']
elif eye_scores['eyebrowl'][0] is not None:
eyebrow_scores = eye_scores['eyebrowl']
iou_i = iou_b = iou_l = iou_br = -1
scores = {'irides': 0, 'eyebg': 0, 'eyelash': 0, 'eyebrow': 0}
if irides_scores is not None and bg_scores is not None and irides_scores[2] > 0 and bg_scores[2] > 0:
scores['irides'] = irides_scores[2] / irides_scores[1]
scores['eyebg'] = bg_scores[2] / bg_scores[1]
if eyelash_scores is not None and eyelash_scores[2] > 0:
scores['eyelash'] = eyelash_scores[2] / eyelash_scores[1]
if eyebrow_scores is not None and eyebrow_scores[2] > 0:
scores['eyebrow'] = eyebrow_scores[2] / eyebrow_scores[1]
k = max(scores, key=scores.get)
def rect_include(xyxy1, dict2):
if 'xyxy' not in dict2:
return False
xyxy2 = dict2['xyxy']
return xyxy1[0] > xyxy2[0] and xyxy1[1] > xyxy2[1] and xyxy1[2] < xyxy2[2] and xyxy1[3] < xyxy2[3]
if scores[k] > 0:
d.body_part_tag = k
else:
x1, y1, x2, y2 = d.xyxy
y = (y1 + y2) / 2
if y < eyel_xyxy[1] or y < eyer_xyxy[1]:
d.body_part_tag = 'eyebrow'
elif rect_include(d.xyxy, eye_scores['iridesl']) or rect_include(d.xyxy, eye_scores['iridesr']):
d.body_part_tag = 'irides'
elif rect_include(d.xyxy, eye_scores['eyebgsl']) or rect_include(d.xyxy, eye_scores['eyebgsr']):
d.body_part_tag = 'eyebg'
else:
d.body_part_tag = 'eyelash'
if lmodel._body_parsing is not None:
metadata = lmodel._body_parsing['metadata']
else:
metadata = {}
lmodel.save_body_parsing(save_name=save_name, metadata=metadata)
# hairf = lmodel.compose_bodypart_drawables('hairf')
# hairb = lmodel.compose_bodypart_drawables('hairb')
# irides = lmodel.compose_bodypart_drawables('irides')
# eyebg = lmodel.compose_bodypart_drawables('eyebg')
# eyelash = lmodel.compose_bodypart_drawables('eyelash')
# eyebrow = lmodel.compose_bodypart_drawables('eyebrow')
# save_tmp_img(
# imglist2imgrid([lmodel.final, hairf, hairb, irides, eyebg, eyelash, eyebrow], fix_size=512)
# )
# pass
except Exception as e:
raise
print(f'failed to process {p}: {e}')
continue
def propagate_invisible_parts(lmodel: Live2DScrapModel):
voting_tree = {}
for d in lmodel.drawables:
if d.tag is None:
continue
parent = osp.dirname(d.did)
if parent == '':
parent = '_root'
if parent not in voting_tree:
voting_tree[parent] = {}
if d.tag not in voting_tree[parent]:
voting_tree[parent][d.tag] = 0
voting_tree[parent][d.tag] += 1
for d in lmodel.drawables:
if d.tag is not None:
continue
parent = osp.dirname(d.did)
target_tag = None
while True:
if parent == '':
parent = '_root'
if parent not in voting_tree:
break
if len(voting_tree[parent]) > 0:
target_tag = max(voting_tree[parent], key=voting_tree[parent].get)
break
if parent == '_root':
break
parent = osp.dirname(parent)
if target_tag is not None:
voting_tree[parent][target_tag] += 1
d.set_tag(target_tag)
def assign_tag_by_path(lmodel: Live2DScrapModel):
did_contain_arms = False
for d in lmodel.drawables:
if d.did is None:
continue
if 'eye_ball' in d.did.lower():
d.set_tag('irides')
if 'brow' in d.did.lower():
d.set_tag('eyebrow')
if 'eyewhite' in d.did.lower():
d.set_tag('eyewhite')
if 'mouth' in d.did.lower():
d.set_tag('mouth')
if 'eyelash' in d.did.lower():
d.set_tag('eyelash')
if 'tooth' in d.did.lower():
d.set_tag('mouth')
if 'arm' in d.did.lower():
did_contain_arms = True
for d in lmodel.drawables:
if d.did is None:
continue
did_lower = d.did.lower()
if d.tag == 'objects':
continue
if d.tag is None:
if 'hair' in did_lower:
d.set_tag('hair')
elif 'arm' in did_lower:
d.set_tag('handwear')
elif 'mouth' in did_lower:
d.set_tag('mouth')
elif 'body' in did_lower:
if 'body2' in did_lower:
d.set_tag('bottomwear')
# else:
# d.set_tag('topwear')
elif 'face' in did_lower:
d.set_tag('face')
elif 'ear' in did_lower:
d.set_tag('ears')
elif 'eye' in did_lower:
d.set_tag('eyes')
elif 'leg' in did_lower:
d.set_tag('legwear')
elif d.tag == 'hair':
if 'face' in did_lower:
d.set_tag('face')
elif 'arm' in did_lower:
d.set_tag('handwear')
elif 'body' in did_lower and 'hair' not in did_lower:
d.set_tag('topwear')
elif d.tag == 'handwear':
if did_contain_arms:
if 'body' in did_lower and 'arm' not in did_lower:
if 'body2' in did_lower:
d.set_tag('bottomwear')
# else:
# d.set_tag('topwear')
if 'hair' in did_lower:
d.set_tag('hair')
elif d.tag == 'topwear':
if 'hair' in did_lower:
d.set_tag('headwear')
elif 'arm' in did_lower:
d.set_tag('handwear')
elif d.tag == 'bottomwear':
if 'hair' in did_lower:
d.set_tag('headwear')
else:
if 'arm' in did_lower:
d.set_tag('handwear')
if d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', 'face', None} and 'ear' in did_lower:
d.set_tag('ears')
elif d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', 'face', None} and 'neck' in did_lower:
d.set_tag('neck')
elif d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', None} and ('hand' in did_lower or 'arm' in did_lower):
d.set_tag('handwear')
elif d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', None} and 'eye' in did_lower:
d.set_tag('eyes')
elif d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', None} and 'mouth' in did_lower:
d.set_tag('mouth')
elif d.tag in {'legwear', 'topwear', 'bottomwear', 'hair', 'face', None} and 'nose' in did_lower:
d.set_tag('nose')
@cli.command('label_l2d_wsamsegs')
@click.option('--exec_list')
@click.option('--save_dir', default='')
@click.option('--extr_more', is_flag=True, default=False, help='required if sam masks is 19 classes, further divide hair and eyes into sub parts')
@click.option('--rank_to_worldsize', default='', type=str)
def label_l2d_wsamsegs(exec_list, save_dir, extr_more, rank_to_worldsize):
from live2d.scrap_model import Drawable, VALID_BODY_PARTS_V2
from utils.cv import fgbg_hist_matching, quantize_image, random_crop, rle2mask, mask2rle, img_alpha_blending, resize_short_side_to, batch_save_masks, batch_load_masks
from utils.torch_utils import seed_everything
seed_everything(42)
exec_listp = exec_list
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
if save_dir != '':
os.makedirs(save_dir, exist_ok=True)
mask_name = 'sam_masks.json'
for ii, p in enumerate(tqdm(exec_list[0:])):
try:
instance_mask, crop_xyxy, score = load_detected_character(p)
# if instance_mask is None:
# print(f'skip {p}, no character instance detected')
# continue
lmodel = Live2DScrapModel(p, crop_xyxy=crop_xyxy, pad_to_square=False)
model_dir = lmodel.directory
if lmodel._body_parsing is not None:
metadata = lmodel._body_parsing['metadata']
else:
metadata = {}
# feet_mask_valid = metadata['tag_valid']['footwear']
masks_ann = json2dict(osp.join(model_dir, mask_name))
sam_masks = [rle2mask(m, to_bool=True) for m in masks_ann]
init_drawable_visible_map(lmodel.drawables)
for tg in lmodel.drawables:
if tg.final_visible_area < 1:
continue
score_list = []
for m in sam_masks:
area, u_area, i_area = tg.mask_union_intersection(m, final_vis_mask=True)
if i_area is None:
i_area = -1
score = i_area / tg.final_visible_area
score_list.append(score)
best_match = np.argmax(np.array(score_list))
best_match = VALID_BODY_PARTS_V2[best_match]
tg.body_part_tag = best_match
if tg.body_part_tag == 'legwear' and score_list[VALID_BODY_PARTS_V2.index('footwear') > 0.5]:
tg.body_part_tag = 'footwear'
assign_tag_by_path(lmodel)
propagate_invisible_parts(lmodel)
lmodel.save_body_parsing(metadata=metadata, save_name='body_parsing')
except Exception as e:
raise
print(f'Failed to process {p}: {e}')
if extr_more:
further_extr(exec_listp)
@cli.command('gradcam_heatmap')
@click.option('--image_file')
@click.option('--savep', default=None)
@click.option('--method', default='gradcam++')
@click.option('--model_type', default='eva')
@click.option('--gen_threshold', default=0.35)
@click.option('--eigen_smooth', is_flag=True, default=False)
@click.option('--aug_smooth', is_flag=True, default=False)
@click.option('--device', default='cuda')
def gradcam_heatmap(image_file, savep, method, model_type, gen_threshold, eigen_smooth, aug_smooth, device):
from annotators.wdv3_tagger import apply_wdv3_tagger, get_tagger_and_transform
from annotators.gradcam import apply_gradcam
from pytorch_grad_cam.utils.image import show_cam_on_image
if savep is None:
os.makedirs('workspace', exist_ok=True)
savep = osp.join('workspace', osp.basename(osp.dirname(image_file)) + '_' + model_type + '_' + method + '.png')
img_input: Image.Image = Image.open(image_file)
alpha = img_input.split()[-1]
bbox = alpha.getbbox()
# ensure image is RGB
img_input = pil_ensure_rgb(img_input)
img_input = img_input.crop(bbox)
# pad to square with white background
img_input, _ = pil_pad_square(img_input)
img_input = img_input.resize((448, 448), resample=Image.Resampling.LANCZOS)
caption, taglist, ratings, character, general = apply_wdv3_tagger(img_input, model_type=model_type, exclude_cls=exclude_cls, gen_threshold=gen_threshold)
_, transform, labels = get_tagger_and_transform(model_type)
inputs = transform(img_input).unsqueeze(0)
inputs = inputs[:, [2, 1, 0]]
imglist = []
for k, v in tqdm(general.items()):
grayscale_cam = apply_gradcam(inputs, v[1], method=method, model_type=model_type, eigen_smooth=eigen_smooth, aug_smooth=aug_smooth, device=device)
grayscale_cam = grayscale_cam[0, :]
cam_image = show_cam_on_image(np.array(img_input)[..., ::-1] / 255., grayscale_cam)
fontScale = 0.9
cam_image = cv2.putText(cam_image, k, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, fontScale, color=(255, 255, 255), thickness=2, lineType=cv2.LINE_AA)
imglist.append(cam_image)
# torch.cuda.empty_cache()
rst = imglist2imgrid(imglist)
Image.fromarray(rst[..., ::-1]).save(savep)
print(f'result saved to {savep}')
@cli.command('infer_bizarre_tagger')
@click.option('--exec_list')
@click.option('--detected_instanec_only', default=False, is_flag=True)
@click.option('--rank_to_worldsize', default='', type=str)
def infer_bizarre_tagger(exec_list, detected_instanec_only, rank_to_worldsize):
'''
apply pos estimator: bizarre tagger
'''
from annotators.bizarre_tagger import apply_pos_estimator
# model = LangSAM(sam_type="sam2.1_hiera_large")
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
for model_dir in tqdm(exec_list):
try:
if osp.isfile(model_dir):
model_dir = osp.dirname(model_dir)
crop_xyxy = None
if detected_instanec_only:
instance_mask, crop_xyxy, score = load_detected_character(model_dir)
if instance_mask is None:
print(f'skip {model_dir}, no character instance detected')
continue
lmodel = Live2DScrapModel(model_dir, crop_xyxy=crop_xyxy, crop_to_final=True, pad_to_square=False)
model_dir = lmodel.directory
# ensure image is RGB
img_input = pil_ensure_rgb(Image.fromarray(lmodel.final))
kps, scores, bbox = apply_pos_estimator(img_input, mask=lmodel.final[..., -1].astype(np.float32) / 255.)
save_rst = {'transform_stats': {'crop_xyxy': lmodel.final_bbox}, 'pos': [k for k in kps], 'scores': scores}
savep = osp.join(model_dir, 'bizarre_pos.json')
dict2json(save_rst, savep)
except Exception as e:
# raise e
print(f'failed to process {model_dir}: {e}')
@cli.command('infer_langsam')
@click.option('--exec_list')
@click.option('--box_threshold', default=0.35, type=float)
@click.option('--text_threshold', default=0.25, type=float)
@click.option('--detected_instanec_only', default=False, is_flag=True)
@click.option('--rank_to_worldsize', default='', type=str)
@click.option('--skip_exists', default=False, is_flag=True)
def infer_langsam(exec_list, box_threshold, text_threshold, detected_instanec_only, rank_to_worldsize, skip_exists):
import torch
import gc
from annotators.lang_sam import LangSAM
model = LangSAM(sam_type="sam2.1_hiera_large")
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
prompts = ['face', 'hair', 'hand', 'feet', 'leg', 'dress', 'shirt', 'skirt', 'jacket', 'neck', 'outfit', 'shoes']
prompt_list_head = ['mouth', 'nose', 'ears']
# prompt_list_head = ['hairband', 'crown']
# skip_exists = True
for model_dir in tqdm(exec_list[0:]):
try:
if osp.isfile(model_dir):
model_dir = osp.dirname(model_dir)
crop_xyxy = None
if detected_instanec_only:
instance_mask, crop_xyxy, score = load_detected_character(model_dir)
if instance_mask is None:
print(f'skip {model_dir}, no character instance detected')
continue
lmodel = Live2DScrapModel(model_dir, crop_xyxy=crop_xyxy, crop_to_final=True, pad_to_square=False)
model_dir = lmodel.directory
# ensure image is RGB
img_input = pil_ensure_rgb(Image.fromarray(lmodel.final))
savep = osp.join(model_dir, 'langsam_masks.json')
if osp.exists(savep) and skip_exists:
save_rst = json2dict(savep)
else:
save_rst = {'transform_stats': {'crop_xyxy': lmodel.final_bbox}, 'instances': {}}
if skip_exists:
prompt_list = [k for k in prompts if (k not in save_rst['instances'])]
else:
prompt_list = prompts
if len(prompt_list) > 0:
rst = model.predict_multi_prompts(img_input, prompt_list, box_threshold=box_threshold, text_threshold=text_threshold)
for p, ins in zip(prompt_list, rst):
masks = [np.squeeze(m, 0) if m.ndim == 3 else m for m in ins['masks']]
masks = [mask2rle(m) for m in masks]
ins['boxes'] = [b for b in ins['boxes']]
ins['masks'] = masks
save_rst['instances'][p] = ins
if skip_exists:
prompt_list = [k for k in prompt_list_head if (k not in save_rst['instances'])]
else:
prompt_list = prompt_list_head
crop_head_for_head_prompt = True
if len(prompt_list) > 0:
head_crop = head_pad = None
head_input = img_input
h, w = img_input.height, img_input.width
if crop_head_for_head_prompt and lmodel.face_detected():
facedet = lmodel.facedet[0]
x1, y1, x2, y2 = facedet['bbox'][:4]
p = int(round(max(x2 - x1, y2 - y1) * 1.0))
if p > 0:
head_crop = [max(x1 - p, 0), max(y1 - p, 0), min(x2 + p, w), min(y2 + p, h)]
hw, hh = head_crop[2] - head_crop[0], head_crop[3] - head_crop[1]
head_pad = [head_crop[0], head_crop[1], w - head_crop[2], h - head_crop[3]]
if np.all(np.array(head_pad) == 0) or hw <= 0 or hh <= 0:
head_pad = None
else:
head_input = head_input.crop(head_crop)
rst = model.predict_multi_prompts(head_input, prompt_list, box_threshold=box_threshold, text_threshold=text_threshold)
for p, ins in zip(prompt_list, rst):
masks = [np.squeeze(m, 0) if m.ndim == 3 else m for m in ins['masks']]
if head_pad is not None:
masks = [cv2.copyMakeBorder(m.astype(np.uint8), head_pad[1], head_pad[3], head_pad[0], head_pad[2], value=0, borderType=cv2.BORDER_CONSTANT) for m in masks]
masks = [mask2rle(m) for m in masks]
ins['boxes'] = [b for b in ins['boxes']]
ins['masks'] = masks
save_rst['instances'][p] = ins
# from utils.visualize import visualize_segs_with_labels
# from utils.cv import rle2mask
# masks = []
# for p in prompt_list:
# msk = [rle2mask(m) for m in save_rst['instances'][p]['masks']]
# if len(msk) > 0:
# msk = np.logical_or.reduce(np.stack(msk, 0), axis=0)
# else:
# msk = np.zeros_like(lmodel.final[..., 0])
# masks.append(msk)
# t = json2dict(osp.join(model_dir, 'general_tags.json'))
# print(t.keys())
# print(has_animal_ear(t.keys()))
# save_tmp_img(visualize_segs_with_labels(masks, lmodel.final, prompt_list))
# pass
savep = osp.join(model_dir, 'langsam_masks.json')
dict2json(save_rst, savep)
# pad to square with white background
except Exception as e:
# raise
print(f'failed to process {model_dir}: {e}')
gc.collect()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
@cli.command('parse_live2d')
@click.option('--exec_list')
@click.option('--method', default='gradcam')
@click.option('--model_type', default='eva')
@click.option('--gen_threshold', default=0.3)
@click.option('--eigen_smooth', is_flag=True, default=False)
@click.option('--aug_smooth', is_flag=True, default=False)
@click.option('--save_gradcam_heatmap', is_flag=True, default=False)
@click.option('--device', default='cuda')
@click.option('--tag_only', default=False, is_flag=True)
@click.option('--detected_instanec_only', default=False, is_flag=True)
@click.option('--rank_to_worldsize', default='', type=str)
def parse_live2d(exec_list, method, model_type, gen_threshold, eigen_smooth, aug_smooth, save_gradcam_heatmap, device, tag_only, detected_instanec_only, rank_to_worldsize):
from annotators.wdv3_tagger import apply_wdv3_tagger, get_tagger_and_transform
from annotators.gradcam import apply_gradcam
from pytorch_grad_cam.utils.image import show_cam_on_image
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
for model_dir in tqdm(exec_list):
try:
crop_xyxy = None
if detected_instanec_only:
instance_mask, crop_xyxy, score = load_detected_character(model_dir)
if instance_mask is None:
print(f'skip {model_dir}, no character instance detected')
continue
model = Live2DScrapModel(model_dir, target_frame_size=448, crop_to_final=True, pad_to_square=True, crop_xyxy=crop_xyxy, pad_drawable_img=False)
model_dir = model.directory
# ensure image is RGB
img_input = pil_ensure_rgb(Image.fromarray(model.final))
# pad to square with white background
caption, taglist, ratings, character, general = apply_wdv3_tagger(img_input, model_type=model_type, exclude_cls=exclude_cls, gen_threshold=gen_threshold)
dict2json(general, osp.join(model_dir, 'general_tags.json'))
if tag_only:
continue
model.init_drawable_visible_map()
_, transform, labels = get_tagger_and_transform(model_type)
inputs = transform(img_input).unsqueeze(0)
inputs = inputs[:, [2, 1, 0]]
gradcam_heatmap_vis = []
for cls_name, v in general.items():
cls_score, cls_idx = v[0], v[1]
score_map = apply_gradcam(inputs, cls_idx, method=method, model_type=model_type, eigen_smooth=eigen_smooth, aug_smooth=aug_smooth, device=device)
model.update_tag_stats(score_map[0], cls_idx, cls_name, filter_scoremap=True)
if save_gradcam_heatmap:
cam_image = show_cam_on_image(np.array(img_input)[..., ::-1] / 255., score_map[0])
fontScale = 0.9
cam_image = cv2.putText(cam_image, cls_name, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, fontScale, color=(255, 255, 255), thickness=2, lineType=cv2.LINE_AA)
gradcam_heatmap_vis.append(cam_image)
if save_gradcam_heatmap:
gradcam_heatmap_vis = imglist2imgrid(gradcam_heatmap_vis, cols=6)
savep = osp.join(model_dir, 'heatmap_' + model_type + '_' + method + '.png')
Image.fromarray(gradcam_heatmap_vis[..., ::-1]).save(savep)
model.save_tag_stats()
except Exception as e:
print(f'failed to process {model_dir}: {e}')
pass
# # assign drawable to the tag with maximum
# avgscore_lst = []
# for tag, tag_info in model.tag_stats.items():
# avgscore_map = np.zeros_like(model.final[..., 0]).astype(np.float32)
# for drawable in model.drawables:
# if drawable.final_visible_area < 1:
# continue
# x1, y1, x2, y2 = drawable.xyxy
# avgscore_map[y1: y2, x1: x2] += drawable.final_visible_mask.astype(np.float32) * drawable.tag_stats[tag]['avg_score']
# avgscore_lst.append(avgscore_map)
# avgscore_lst = np.stack(avgscore_lst).clip(0, 1)
# concept_labels = list(model.tag_stats.keys())
# vis = show_factorization_on_image(model.final[..., :3] / 255., avgscore_lst, concept_labels=concept_labels, image_weight=0.1, visible_mask=model.final_visible_mask[..., None])
# Image.fromarray(vis).save(osp.join(model_dir, 'segmentation_' + model_type + '_' + method + '.png'))
@cli.command('dump_body_tags')
@click.option('--src_dir', default='workspace/tags_raw/bodyparts')
@click.option('--savep', default='workspace/tagcluster_bodypart.json')
def dump_body_tags(src_dir, savep):
from utils.io_utils import json2dict, dict2json
spliters = [',', '|']
tag_set_cleaned = {}
sets_duplicated = {}
for d in os.listdir(src_dir):
p = osp.join(src_dir, d)
with open(p, 'r', encoding='utf8') as f:
lines = f.read().split('\n')
lines_lst = []
for l in lines:
l = l.strip().lower()
if l.startswith('#'):
continue
for s in spliters:
l = l.split(s)[0].strip()
if len(l) > 0:
l = '_'.join(l.split(' '))
lines_lst.append(l)
tag_set_cleaned[d] = lines_lst
dict2json(tag_set_cleaned, savep)
@cli.command('facedet')
@click.option('--exec_list')
@click.option('--twopass', is_flag=True, default=False)
@click.option('--rank_to_worldsize', default='', type=str)
@click.option('--skip_exists', default=False, is_flag=True)
def facedet(exec_list, twopass, rank_to_worldsize, skip_exists):
from annotators import anime_face_detector
if exec_list.endswith('.json') or exec_list.endswith('.json.gz'):
exec_list = json2dict(exec_list)
exec_list = list(exec_list.keys())
exec_list = load_exec_list(exec_list, rank_to_worldsize=rank_to_worldsize)
device = 'cuda' #@param ['cuda:0', 'cpu']
model = 'yolov3' #@param ['yolov3', 'faster-rcnn']
detector = anime_face_detector.create_detector(model, device=device)
if skip_exists:
new_exec_list = []
for srcp in exec_list:
if osp.isfile(srcp):
srcp = osp.dirname(srcp)
if osp.exists(osp.join(srcp, 'facedet.json')):
print(f'skip {srcp} due to result exists')
continue
new_exec_list.append(srcp)
exec_list = new_exec_list
for srcp in tqdm(exec_list):
try:
if osp.isfile(srcp):
srcp = osp.dirname(srcp)
savep = osp.join(srcp, 'facedet.json')
lmodel = Live2DScrapModel(srcp, crop_to_final=True, pad_to_square=False)
image = Image.fromarray(lmodel.final)
if twopass:
lmodel.init_drawable_visible_map()
image = pil_ensure_rgb(image)
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
preds = detector(image)
if len(preds) > 0:
pred = max(preds, key=lambda x: x['bbox'][-1])
bbox = pred['bbox']
keypoints = pred['keypoints']
if twopass:
bbox_input = bbox.copy()
# bbox_input[..., :4] = lmodel.processor.scale_coordinates(bbox_input[..., :4].reshape((2, 2))).flatten()
x1, y1, x2, y2, _ = np.round(bbox_input).astype(np.int32)
# vis_face_det = visualize_facedet_output(model.final, [facedet])[y1: y2, x1: x2, :3]
# vis_face_det = np.concatenate([vis_face_det, np.full_like(vis_face_det[..., [0]], fill_value=255)], axis=2)
xyxy = [x1, y1, x2, y2]
valid_drawables = []
for drawable in lmodel.drawables:
if drawable.final_visible_area < 1:
continue
bbox_i, vis_mask = drawable.get_vis_mask(xyxy, final_vis_mask=True)
if bbox_i is None or vis_mask.sum() / drawable.final_visible_area < 0.8:
continue
valid_drawables.append(drawable)
face_crop = compose_from_drawables(valid_drawables, xyxy=xyxy)
facedet2 = detector(face_crop, boxes=[np.array([0, 0, x2-x1, y2-y1, 1])])
keypoints2 = facedet2[0]['keypoints']
px1 = x1 + lmodel.final_bbox[0]
py1 = y1 + lmodel.final_bbox[1]
keypoints2[:, 0] += px1
keypoints2[:, 1] += py1
keypoints[LEFT_EYEBROW] = keypoints2[LEFT_EYEBROW]
keypoints[RIGHT_EYEBROW] = keypoints2[RIGHT_EYEBROW]
# Image.fromarray(face_crop).save('local_tst.png')
pass
bbox[-1] = np.round(bbox[-1] * 100)
bbox[:-1] = np.round(bbox[:-1])
pred['bbox'] = bbox.astype(np.int32)
if lmodel.final_bbox is not None:
pred['bbox'][[0, 2]] += lmodel.final_bbox[0]
pred['bbox'][[1, 3]] += lmodel.final_bbox[1]
# print(lmodel.final_bbox)
# save_tmp_img(imread(osp.join(srcp, 'final.jxl'))[pred['bbox'][1]: pred['bbox'][3], pred['bbox'][0]: pred['bbox'][2]])
# break
keypoints[:, 2] = np.round(keypoints[:, 2] * 100)
keypoints[:, :2] = np.round(keypoints[:, :2])
pred['keypoints'] = [k for k in keypoints.astype(np.int32)]
else:
pass
dict2json(preds, savep)
except Exception as e:
print(f'failed to process {srcp}: {e}')
def hflip_aug_mask(mask: np.ndarray, x: int, aug=True):
'''
mask: (h, w) or (c, h, w)
'''
if mask.ndim == 3:
if mask.shape[0] == 1:
mask = mask[0]
else:
mask = np.logical_or.reduce(mask, axis=0)
h, w = mask.shape[:2]
mid = w // 2
if x <= mid:
x1 = 0
x2 = x * 2
else:
x2 = w
x1 = w - (w - x) * 2
mask_or = mask[:, x1: x2]
if aug:
mask[:, x1: x2] = np.bitwise_or(mask_or, mask_or[:, ::-1])
mask_l = mask.copy()
mask_l[:, mid:] = 0
mask[:, :mid] = 0
# imglist2imgrid([mask_l.astype(np.uint8) * 255, mask.astype(np.uint8) * 255], output_type='pil').save('local_tst.png')
return mask_l, mask
def part_morph_transform(masks, target_cls, ksize=1, op='dilate'):
mask = masks[target_cls].astype(np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * ksize + 1, 2 * ksize + 1),(ksize, ksize))
if op == 'dilate':
mask = cv2.dilate(mask, element)
else:
mask = cv2.erode(mask, element)
masks[target_cls] = mask.astype(bool)
def split_lr_part(lmodel: Live2DScrapModel, target_ids: list):
from sklearn.cluster import MiniBatchKMeans, KMeans
eye_xs = []
eye_drawables = []
for d in lmodel.drawables:
if d.face_part_id in target_ids:
dx, dy, dw, dh = cv2.boundingRect(cv2.findNonZero(d.final_visible_mask.astype(np.uint8)))
dx += d.x
dy += d.y
eye_xs.append(dx + dw / 2)
eye_drawables.append(d)
if len(eye_drawables) < 2:
return False
eye_xs = np.array(eye_xs)
eye_xs_mean = np.mean(eye_xs) + 1e-6
eye_xs = eye_xs[:, None] / eye_xs_mean - 1
rst = KMeans(2, max_iter=50).fit(eye_xs)
labels = rst.predict(eye_xs)
if rst.cluster_centers_[0, 0] > rst.cluster_centers_[1, 0]:
labels = 1 - labels
for d, l in zip(eye_drawables, labels):
d.face_part_id = target_ids[l]
return True
def split_lr_mask(masks: np.ndarray, split_channels):
ms = masks[split_channels]
ms = np.logical_or.reduce(ms, axis=0)
xs = np.where(ms > 0)
pass
def find_brow(lmodel: Live2DScrapModel, brow_id, face_xyxy=None):
btop = 100000
eye_id = brow_id + 2
eye_mask = lmodel.compose_face_drawables(eye_id, mask_only=True, final_visible_mask=True, xyxy=face_xyxy)
ex, ey, ew, eh = cv2.boundingRect(cv2.findNonZero(eye_mask.astype(np.uint8)))
tgt_brow = None
for d in lmodel.drawables:
if d.face_part_id != eye_id:
continue
dx, dy, dw, dh = d.get_bbox(xyxy=face_xyxy)
if dy < btop and dw / ew > 0.5:
tgt_brow = d
btop = dy
if tgt_brow is not None:
tgt_brow.face_part_id = brow_id
return True
return False
@cli.command('facedet_sam')
@click.option('--exec_list')
@click.option('--ckpt')
@click.option('--mask_decoder', default='mlp_variant')
@click.option('--class_num', default=19)
@click.option('--save_segs', default=False, is_flag=True)
@click.option('--save_preview', default=False, is_flag=True)