Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
|
| 7 |
+
def crop_face(base64_image):
|
| 8 |
+
# Decode the base64 image
|
| 9 |
+
img_data = base64.b64decode(base64_image)
|
| 10 |
+
np_arr = np.frombuffer(img_data, np.uint8)
|
| 11 |
+
image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 12 |
+
|
| 13 |
+
if image is None:
|
| 14 |
+
print("Could not decode the image")
|
| 15 |
+
return None
|
| 16 |
+
|
| 17 |
+
# Load the pre-trained face detector
|
| 18 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
| 19 |
+
|
| 20 |
+
# Convert the image to grayscale
|
| 21 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 22 |
+
|
| 23 |
+
# Detect faces in the image
|
| 24 |
+
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
| 25 |
+
|
| 26 |
+
# If no faces are detected, return None
|
| 27 |
+
if len(faces) == 0:
|
| 28 |
+
print("No faces found")
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
# Crop the first face found
|
| 32 |
+
x, y, w, h = faces[0]
|
| 33 |
+
face_crop = image[y:y+h, x:x+w]
|
| 34 |
+
|
| 35 |
+
# Encode the cropped face to base64
|
| 36 |
+
_, buffer = cv2.imencode('.jpg', face_crop)
|
| 37 |
+
face_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 38 |
+
|
| 39 |
+
return face_base64
|
| 40 |
+
|
| 41 |
+
# Define the Gradio interface
|
| 42 |
+
interface = gr.Interface(
|
| 43 |
+
fn=crop_face,
|
| 44 |
+
inputs="text",
|
| 45 |
+
outputs="text",
|
| 46 |
+
title="Face Cropper",
|
| 47 |
+
description="Input a base64 encoded image to get a base64 encoded cropped face."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
interface.launch(share=True)
|