DEVAN CHAUHAN commited on
Commit
2418377
·
1 Parent(s): 80e1925

[add] anime face detection and crop

Browse files
Files changed (2) hide show
  1. app.py +113 -54
  2. lbpcascade_animeface.xml +0 -0
app.py CHANGED
@@ -1,56 +1,94 @@
1
  import gradio as gr
2
  print("Loading models...")
3
- from retinaface import RetinaFace
4
- print("retinaface loaded")
5
  import cv2
6
- print("opencv loaded")
7
  import numpy as np
8
- print("numpy loaded")
9
  from PIL import Image
10
- print("PIL loaded")
11
  from rembg import remove
12
- print("rembg loaded")
13
  from sentence_transformers import SentenceTransformer
14
- print("sentence_transformers loaded")
 
 
 
15
 
 
16
  image_model = SentenceTransformer("clip-ViT-B-32")
17
  print("CLIP loaded")
18
 
19
- def get_image_embedding(image):
20
- emb = image_model.encode(image)
21
- return {"embedding": emb.tolist()}
22
 
23
- def process_image(input_image):
24
- # Convert PIL → OpenCV
25
- img = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
 
 
 
 
 
26
 
27
- # Detect faces
28
- faces = RetinaFace.detect_faces(img)
29
 
30
- if not faces:
31
- return "No face detected", None
32
 
33
- face = list(faces.values())[0]
34
- x1, y1, x2, y2 = face["facial_area"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- h, w, _ = img.shape
 
37
 
38
- # Expand bounding box (hair included)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  top_expand = 0.5
40
  side_expand = 0.3
41
  bottom_expand = 0.2
42
 
43
- box_width = x2 - x1
44
- box_height = y2 - y1
45
-
46
- x1_new = int(max(0, x1 - box_width * side_expand))
47
- x2_new = int(min(w, x2 + box_width * side_expand))
48
- y1_new = int(max(0, y1 - box_height * top_expand))
49
- y2_new = int(min(h, y2 + box_height * bottom_expand))
50
 
51
- cropped = img[y1_new:y2_new, x1_new:x2_new]
52
 
53
- # Convert back to PIL
54
  pil_image = Image.fromarray(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB))
55
 
56
  # Background removal
@@ -62,31 +100,52 @@ def process_image(input_image):
62
  return "Success ✅", output
63
 
64
 
 
65
  with gr.Blocks() as demo:
66
- with gr.Tab("Image Embedding"):
 
 
 
 
 
 
 
67
  img_input = gr.Image(type="pil")
68
- img_output = gr.JSON()
69
- img_btn = gr.Button("Generate")
70
- img_btn.click(get_image_embedding, img_input, img_output)
71
-
72
- with gr.Tab("Face Crop & Background Removal"):
73
- face_input = gr.Image(type="pil")
74
- face_output = gr.Image()
75
- face_status = gr.Text()
76
- face_btn = gr.Button("Process")
77
- face_btn.click(process_image, face_input, [face_status, face_output])
78
-
79
- with gr.Tab("Pipe"):
80
- pipe_input = gr.Image(type="pil")
81
- pipe_output = gr.JSON()
82
- pipe_btn = gr.Button("Run Pipe")
83
- def run_pipe(img):
84
- status, processed_img = process_image(img)
85
- if status != "Success ✅":
86
- return {"status": status, "embedding": None}
87
- return get_image_embedding(processed_img)
88
-
89
- pipe_btn.click(run_pipe, pipe_input, pipe_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  print("Launching demo...")
92
- demo.launch()
 
1
  import gradio as gr
2
  print("Loading models...")
3
+
 
4
  import cv2
 
5
  import numpy as np
 
6
  from PIL import Image
 
7
  from rembg import remove
 
8
  from sentence_transformers import SentenceTransformer
9
+ import urllib.request
10
+ import pathlib
11
+
12
+ print("Libraries loaded")
13
 
14
+ # Load CLIP Model
15
  image_model = SentenceTransformer("clip-ViT-B-32")
16
  print("CLIP loaded")
17
 
 
 
 
18
 
19
+ # Load Anime Face Cascade
20
+ def load_anime_model():
21
+ url = "https://raw.githubusercontent.com/nagadomi/lbpcascade_animeface/master/lbpcascade_animeface.xml"
22
+ path = pathlib.Path("lbpcascade_animeface.xml")
23
+
24
+ if not path.exists():
25
+ print("Downloading anime face model...")
26
+ urllib.request.urlretrieve(url, path.as_posix())
27
 
28
+ return cv2.CascadeClassifier(path.as_posix())
 
29
 
 
 
30
 
31
+ # Load Human Face Cascade
32
+ def load_human_model():
33
+ path = pathlib.Path(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
34
+ return cv2.CascadeClassifier(path.as_posix())
35
+
36
+
37
+ anime_detector = load_anime_model()
38
+ human_detector = load_human_model()
39
+
40
+ print("Anime + Human detectors loaded")
41
+
42
+
43
+ # Embedding Function
44
+ def get_image_embedding(image):
45
+ emb = image_model.encode(image)
46
+ return {"embedding": emb.tolist()}
47
+
48
 
49
+ # Face Crop + Background Remove
50
+ def process_image(input_image, mode):
51
 
52
+ img = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
53
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
54
+
55
+ # Choose detector
56
+ if mode == "Anime":
57
+ detector = anime_detector
58
+ else:
59
+ detector = human_detector
60
+
61
+ faces = detector.detectMultiScale(
62
+ gray,
63
+ scaleFactor=1.1,
64
+ minNeighbors=5,
65
+ minSize=(24, 24)
66
+ )
67
+
68
+ if len(faces) == 0:
69
+ print("direct to background removal")
70
+ pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
71
+ output = remove(pil_image)
72
+ output = output.resize((224, 224))
73
+
74
+ return "Success ✅", output
75
+
76
+ x, y, w, h = faces[0]
77
+
78
+ height, width, _ = img.shape
79
+
80
+ # Expand bounding box
81
  top_expand = 0.5
82
  side_expand = 0.3
83
  bottom_expand = 0.2
84
 
85
+ x1 = int(max(0, x - w * side_expand))
86
+ x2 = int(min(width, x + w + w * side_expand))
87
+ y1 = int(max(0, y - h * top_expand))
88
+ y2 = int(min(height, y + h + h * bottom_expand))
 
 
 
89
 
90
+ cropped = img[y1:y2, x1:x2]
91
 
 
92
  pil_image = Image.fromarray(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB))
93
 
94
  # Background removal
 
100
  return "Success ✅", output
101
 
102
 
103
+ # Gradio UI
104
  with gr.Blocks() as demo:
105
+
106
+ with gr.Tab("Full Pipeline"):
107
+ mode_selector = gr.Dropdown(
108
+ choices=["Anime", "Human"],
109
+ value="Anime",
110
+ label="Detection Mode"
111
+ )
112
+
113
  img_input = gr.Image(type="pil")
114
+ status = gr.Text()
115
+ img_output = gr.Image()
116
+ embedding_output = gr.JSON()
117
+
118
+ run_btn = gr.Button("Run Pipeline")
119
+
120
+ def run_pipeline(img, mode):
121
+ status_msg, processed_img = process_image(img, mode)
122
+ if status_msg != "Success ✅":
123
+ return status_msg, None, {"embedding": None}
124
+
125
+ embedding = get_image_embedding(processed_img)
126
+ return status_msg, processed_img, embedding
127
+
128
+ run_btn.click(
129
+ run_pipeline,
130
+ inputs=[img_input, mode_selector],
131
+ outputs=[status, img_output, embedding_output]
132
+ )
133
+
134
+ with gr.Tab("Embedding Only"):
135
+ img_input2 = gr.Image(type="pil")
136
+ embedding_output2 = gr.JSON()
137
+ run_btn2 = gr.Button("Get Embedding")
138
+
139
+ def get_embedding_only(img):
140
+ embedding = get_image_embedding(img)
141
+ return embedding
142
+
143
+ run_btn2.click(
144
+ get_embedding_only,
145
+ inputs=img_input2,
146
+ outputs=embedding_output2
147
+ )
148
+
149
 
150
  print("Launching demo...")
151
+ demo.queue(max_size=15).launch()
lbpcascade_animeface.xml ADDED
The diff for this file is too large to render. See raw diff