Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,6 @@ import torch
|
|
| 5 |
from torchvision import transforms
|
| 6 |
import cv2
|
| 7 |
import numpy as np
|
| 8 |
-
from facenet_pytorch import MTCNN
|
| 9 |
|
| 10 |
# Function to load the ViT model
|
| 11 |
def load_model(model_path):
|
|
@@ -14,26 +13,23 @@ def load_model(model_path):
|
|
| 14 |
model.to(device)
|
| 15 |
return model, device
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
mtcnn = MTCNN(keep_all=True, device=device)
|
| 20 |
|
| 21 |
-
# Function to preprocess the image using
|
| 22 |
def preprocess_image(image, device):
|
| 23 |
# Convert PIL image to OpenCV format
|
| 24 |
open_cv_image = np.array(image.convert("RGB"))
|
| 25 |
# Convert RGB to BGR for OpenCV
|
| 26 |
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR)
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
|
| 31 |
-
|
| 32 |
-
boxes, _ = mtcnn.detect(pil_image)
|
| 33 |
-
if boxes is not None:
|
| 34 |
# Crop the first detected face (for simplicity)
|
| 35 |
-
|
| 36 |
-
cropped_face = open_cv_image[
|
| 37 |
# Convert cropped face back to PIL for further processing
|
| 38 |
processed_image = Image.fromarray(cv2.cvtColor(cropped_face, cv2.COLOR_BGR2RGB))
|
| 39 |
else:
|
|
|
|
| 5 |
from torchvision import transforms
|
| 6 |
import cv2
|
| 7 |
import numpy as np
|
|
|
|
| 8 |
|
| 9 |
# Function to load the ViT model
|
| 10 |
def load_model(model_path):
|
|
|
|
| 13 |
model.to(device)
|
| 14 |
return model, device
|
| 15 |
|
| 16 |
+
# Load Haar Cascade for face detection
|
| 17 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
|
|
| 18 |
|
| 19 |
+
# Function to preprocess the image using Haar Cascade for face detection
|
| 20 |
def preprocess_image(image, device):
|
| 21 |
# Convert PIL image to OpenCV format
|
| 22 |
open_cv_image = np.array(image.convert("RGB"))
|
| 23 |
# Convert RGB to BGR for OpenCV
|
| 24 |
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR)
|
| 25 |
|
| 26 |
+
# Detect faces using Haar Cascade
|
| 27 |
+
faces = face_cascade.detectMultiScale(open_cv_image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
| 28 |
|
| 29 |
+
if len(faces) > 0:
|
|
|
|
|
|
|
| 30 |
# Crop the first detected face (for simplicity)
|
| 31 |
+
(x, y, w, h) = faces[0]
|
| 32 |
+
cropped_face = open_cv_image[y:y+h, x:x+w]
|
| 33 |
# Convert cropped face back to PIL for further processing
|
| 34 |
processed_image = Image.fromarray(cv2.cvtColor(cropped_face, cv2.COLOR_BGR2RGB))
|
| 35 |
else:
|