Plana-Archive commited on
Commit
dbe3410
·
verified ·
1 Parent(s): 7b57f77

Upload character_splitter/app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. character_splitter/app.py +62 -0
character_splitter/app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from imgutils.detect import detect_person, detect_halfbody, detect_heads, detection_visualize
5
+
6
+
7
+ def _split_image(image, head_scale: float):
8
+ retval = []
9
+ all_detects = []
10
+ for i, (px, _, score) in enumerate(detect_person(image), start=1):
11
+ person_image = image.crop(px)
12
+ person_label = f'Person #{i} ({score * 100.0:.1f}%)'
13
+ retval.append((person_image, person_label))
14
+ all_detects.append((px, 'person', score))
15
+ px0, py0, _, _ = px
16
+
17
+ half_detects = detect_halfbody(person_image)
18
+ if half_detects:
19
+ halfbody_image = person_image.crop(half_detects[0][0])
20
+ halfbody_label = f'Person #{i} - Half Body'
21
+ retval.append((halfbody_image, halfbody_label))
22
+ bx0, by0, bx1, by1 = half_detects[0][0]
23
+ all_detects.append(((bx0 + px0, by0 + py0, bx1 + px0, by1 + py0), 'halfbody', half_detects[0][2]))
24
+
25
+ head_detects = detect_heads(person_image)
26
+ if head_detects:
27
+ (hx0, hy0, hx1, hy1), _, head_score = head_detects[0]
28
+ cx, cy = (hx0 + hx1) / 2, (hy0 + hy1) / 2
29
+ width, height = hx1 - hx0, hy1 - hy0
30
+ width = height = max(width, height) * head_scale
31
+ x0, y0 = int(max(cx - width / 2, 0)), int(max(cy - height / 2, 0))
32
+ x1, y1 = int(min(cx + width / 2, person_image.width)), int(min(cy + height / 2, person_image.height))
33
+ head_image = person_image.crop((x0, y0, x1, y1))
34
+ head_label = f'Person #{i} - Head'
35
+ retval.append((head_image, head_label))
36
+ all_detects.append(((x0 + px0, y0 + py0, x1 + px0, y1 + py0), 'head', head_score))
37
+
38
+ return detection_visualize(image, all_detects), retval
39
+
40
+
41
+ if __name__ == '__main__':
42
+ with gr.Blocks() as demo:
43
+ with gr.Row():
44
+ with gr.Column():
45
+ gr_input = gr.Image(type='pil', label='Original Image')
46
+ gr_head_scale = gr.Slider(0.8, 2.5, 1.5, label='Head Scale')
47
+ gr_button = gr.Button(value='Crop', variant='primary')
48
+
49
+ with gr.Column():
50
+ with gr.Tabs():
51
+ with gr.Tab('Detected'):
52
+ gr_detected = gr.Image(type='pil', label='Detection')
53
+ with gr.Tab('Cropped'):
54
+ gr_gallery = gr.Gallery(label='Cropped Images')
55
+
56
+ gr_button.click(
57
+ _split_image,
58
+ inputs=[gr_input, gr_head_scale],
59
+ outputs=[gr_detected, gr_gallery],
60
+ )
61
+
62
+ demo.queue(os.cpu_count()).launch()