Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,40 +6,44 @@ import gradio as gr
|
|
| 6 |
from PIL import Image
|
| 7 |
from io import BytesIO
|
| 8 |
|
|
|
|
| 9 |
@spaces.GPU
|
| 10 |
def crop_face(base64_image):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
return None
|
| 33 |
|
| 34 |
-
|
| 35 |
-
x, y, w, h = faces[0]
|
| 36 |
-
face_crop = image[y:y+h, x:x+w]
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
face_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 41 |
|
| 42 |
-
return face_base64
|
| 43 |
|
| 44 |
def image_to_base64(image):
|
| 45 |
# Convert PIL Image to Bytes
|
|
@@ -66,4 +70,4 @@ base64_converter_interface = gr.Interface(
|
|
| 66 |
)
|
| 67 |
|
| 68 |
if __name__ == "__main__":
|
| 69 |
-
gr.TabbedInterface([face_crop_interface, base64_converter_interface], ["Crop Face", "Convert to Base64"]).launch(
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
from io import BytesIO
|
| 8 |
|
| 9 |
+
@spaces.GPU
|
| 10 |
@spaces.GPU
|
| 11 |
def crop_face(base64_image):
|
| 12 |
+
try:
|
| 13 |
+
# Decode the base64 image
|
| 14 |
+
img_data = base64.b64decode(base64_image)
|
| 15 |
+
np_arr = np.frombuffer(img_data, np.uint8)
|
| 16 |
+
image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 17 |
+
|
| 18 |
+
if image is None:
|
| 19 |
+
return "Could not decode the image or no data in buffer"
|
| 20 |
|
| 21 |
+
# Load the pre-trained face detector
|
| 22 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
| 23 |
+
|
| 24 |
+
# Convert the image to grayscale
|
| 25 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 26 |
|
| 27 |
+
# Detect faces in the image
|
| 28 |
+
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
| 29 |
|
| 30 |
+
# If no faces are detected, return message
|
| 31 |
+
if len(faces) == 0:
|
| 32 |
+
return "No faces found"
|
| 33 |
|
| 34 |
+
# Crop the first face found
|
| 35 |
+
x, y, w, h = faces[0]
|
| 36 |
+
face_crop = image[y:y+h, x:x+w]
|
| 37 |
|
| 38 |
+
# Encode the cropped face to base64
|
| 39 |
+
_, buffer = cv2.imencode('.jpg', face_crop)
|
| 40 |
+
face_base64 = base64.b64encode(buffer).decode('utf-8')
|
|
|
|
| 41 |
|
| 42 |
+
return face_base64
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return f"An error occurred: {str(e)}"
|
|
|
|
| 46 |
|
|
|
|
| 47 |
|
| 48 |
def image_to_base64(image):
|
| 49 |
# Convert PIL Image to Bytes
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
if __name__ == "__main__":
|
| 73 |
+
gr.TabbedInterface([face_crop_interface, base64_converter_interface], ["Crop Face", "Convert to Base64"]).launch()
|