Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added buffalo_l model to deepface #1439

Merged
merged 24 commits into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion deepface/DeepFace.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def build_model(model_name: str, task: str = "facial_recognition") -> Any:
Args:
model_name (str): model identifier
- VGG-Face, Facenet, Facenet512, OpenFace, DeepFace, DeepID, Dlib,
ArcFace, SFace and GhostFaceNet for face recognition
ArcFace, SFace GhostFaceNet and buffalo_l for face recognition
- Age, Gender, Emotion, Race for facial attributes
- opencv, mtcnn, ssd, dlib, retinaface, mediapipe, yolov8, yolov11n,
yolov11s, yolov11m, yunet, fastmtcnn or centerface for face detectors
Expand Down
73 changes: 73 additions & 0 deletions deepface/models/facial_recognition/Buffalo_L.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import cv2
import numpy as np
from deepface.models.FacialRecognition import FacialRecognition
from deepface.commons.logger import Logger
from deepface.basemodel import get_weights_path
from deepface.common import weight_utils
import os

logger = Logger()

# Check for insightface dependency
try:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DeepFace. py depends on Buffalo_L.py, and insightface is not a mandatory dependency.

When i import DeepFace, i am getting InsightFace is an optional dependency for the Buffalo_L model.You can install it with: pip install insightface>=0.7.3. So, this will cause having errors for all users who don't have insightface dependency.

So, you must import this in the Buffalo_L class. For instance, MediaPipe module imports mediapipe library not in global level - https://github.com/serengil/deepface/blob/master/deepface/models/face_detection/MediaPipe.py#L27

from insightface.model_zoo import get_model
except ModuleNotFoundError:
raise ModuleNotFoundError(
"InsightFace is an optional dependency for the Buffalo_L model."
"You can install it with: pip install insightface>=0.7.3"
)

class Buffalo_L(FacialRecognition):
def __init__(self):
self.model = None
self.input_shape = (112, 112) # Buffalo_L recognition model expects 112x112
self.output_shape = 512 # Embedding size for Buffalo_L
self.load_model()

def load_model(self):
root = os.path.join(get_weights_path(), 'insightface')
model_name = 'buffalo_l/w600k_r50.onnx'
model_path = os.path.join(root, model_name)

if not os.path.exists(model_path):
url = 'https://drive.google.com/file/d/1N0GL-8ehw_bz2eZQWz2b0A5XBdXdxZhg/view?usp=sharing'
weight_utils.download_file(url, model_path)

self.model = get_model(model_name, root=root)
self.model.prepare(ctx_id=-1, input_size=self.input_shape)

def preprocess(self, img):
"""
Preprocess the image to match InsightFace recognition model expectations.
Args:
img (numpy array): Image in shape (1, 112, 112, 3) or (112, 112, 3)
Returns:
numpy array: Preprocessed image
"""
if len(img.shape) == 4: # (1, 112, 112, 3)
img = img[0] # Remove batch dimension
if img.max() <= 1.0: # If normalized to [0, 1]
img = (img * 255).astype(np.uint8)
# Always convert RGB to BGR (InsightFace expects BGR, DeepFace provides RGB)
img = img[:, :, ::-1]
return img

def forward(self, img):
"""
Extract face embedding from a pre-cropped face image.
Args:
img (numpy array): Preprocessed face image with shape (1, 112, 112, 3)
Returns:
numpy array: Face embedding
"""
img = self.preprocess(img)
embedding = self.model.get_feat(img)

# Handle different embedding formats
if isinstance(embedding, np.ndarray):
if len(embedding.shape) > 1:
embedding = embedding.flatten()
elif isinstance(embedding, list):
embedding = np.array(embedding).flatten()

return embedding
6 changes: 4 additions & 2 deletions deepface/modules/modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
SFace,
Dlib,
Facenet,
GhostFaceNet
GhostFaceNet,
Buffalo_L
)
from deepface.models.face_detection import (
FastMtCnn,
Expand Down Expand Up @@ -59,7 +60,8 @@ def build_model(task: str, model_name: str) -> Any:
"Dlib": Dlib.DlibClient,
"ArcFace": ArcFace.ArcFaceClient,
"SFace": SFace.SFaceClient,
"GhostFaceNet": GhostFaceNet.GhostFaceNetClient
"GhostFaceNet": GhostFaceNet.GhostFaceNetClient,
"Buffalo_L": Buffalo_L.Buffalo_L
},
"spoofing": {
"Fasnet": FasNet.Fasnet,
Expand Down
1 change: 1 addition & 0 deletions deepface/modules/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ def find_threshold(model_name: str, distance_metric: str) -> float:
"DeepFace": {"cosine": 0.23, "euclidean": 64, "euclidean_l2": 0.64},
"DeepID": {"cosine": 0.015, "euclidean": 45, "euclidean_l2": 0.17},
"GhostFaceNet": {"cosine": 0.65, "euclidean": 35.71, "euclidean_l2": 1.10},
"Buffalo_L": {"cosine": 0.65, "euclidean": 11.13, "euclidean_l2": 1.1},
}

threshold = thresholds.get(model_name, base_threshold).get(distance_metric, 0.4)
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ flask_cors>=4.0.1
mtcnn>=0.1.0
retina-face>=0.0.14
fire>=0.4.0
gunicorn>=20.1.0
gunicorn>=20.1.0
5 changes: 4 additions & 1 deletion requirements_additional.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ mediapipe>=0.8.7.3
dlib>=19.20.0
ultralytics>=8.0.122
facenet-pytorch>=2.5.3
torch>=2.1.2
torch>=2.1.2
insightface>=0.7.3
onnxruntime>=1.9.0
tf-keras