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 16 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
97 changes: 97 additions & 0 deletions deepface/models/facial_recognition/Buffalo_L.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import os
from typing import List
import numpy as np

from deepface.commons import weight_utils, folder_utils
from deepface.commons.logger import Logger
from deepface.models.FacialRecognition import FacialRecognition

logger = Logger()

class Buffalo_L(FacialRecognition):
def __init__(self):
self.model = None
self.input_shape = (112, 112)
self.output_shape = 512
self.load_model()

def load_model(self):
"""
Load the InsightFace Buffalo_L recognition model.
"""
try:
from insightface.model_zoo import get_model
except Exception as err:
raise ModuleNotFoundError(
"InsightFace and its dependencies are optional for the Buffalo_L model. "
"Please install them with: "
"pip install insightface>=0.7.3 onnxruntime>=1.9.0 typing-extensions pydantic"
) from err

# Define the model filename and subdirectory
sub_dir = "buffalo_l"
model_file = "w600k_r50.onnx"
model_rel_path = os.path.join(sub_dir, model_file)

# Get the DeepFace home directory and construct weights path
home = folder_utils.get_deepface_home()
weights_dir = os.path.join(home, ".deepface", "weights")
buffalo_l_dir = os.path.join(weights_dir, sub_dir)

# Ensure the buffalo_l subdirectory exists
if not os.path.exists(buffalo_l_dir):
os.makedirs(buffalo_l_dir, exist_ok=True)
logger.info(f"Created directory: {buffalo_l_dir}")

# Download the model weights if not already present
weights_path = weight_utils.download_weights_if_necessary(
file_name=model_rel_path,
source_url="https://drive.google.com/uc?export=download&confirm=pbef&id=1N0GL-8ehw_bz2eZQWz2b0A5XBdXdxZhg" # pylint: disable=line-too-long
)

# Verify the model file exists
if os.path.exists(weights_path):
Copy link
Owner

Choose a reason for hiding this comment

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

we definitely expect weights_path's existence. you may consider to raise an error in else condition.

logger.debug(f"Model file found at: {weights_path}")
else:
raise FileNotFoundError(f"Model file not found at: {weights_path}")

# Load the model
self.model = get_model(model_file, root=buffalo_l_dir)
self.model.prepare(ctx_id=-1, input_size=self.input_shape)

def preprocess(self, img: np.ndarray) -> np.ndarray:
"""
Preprocess the image to match InsightFace recognition model expectations.
Args:
img: Image in shape (1, 112, 112, 3) or (112, 112, 3)
Returns:
Preprocessed image as numpy array
"""
if len(img.shape) == 4:
img = img[0]
if len(img.shape) != 3:
raise ValueError(
f"Expected image to be 3D after preprocessing, but got shape: {img.shape}")
if img.max() <= 1.0:
img = (img * 255).astype(np.uint8)
img = img[:, :, ::-1] # Convert RGB to BGR
return img

def forward(self, img: np.ndarray) -> List[float]:
"""
Extract face embedding from a pre-cropped face image.
Args:
img: Preprocessed face image with shape (1, 112, 112, 3)
Returns:
Face embedding as a list of floats
"""
img = self.preprocess(img)
embedding = self.model.get_feat(img)
if isinstance(embedding, np.ndarray) and len(embedding.shape) > 1:
embedding = embedding.flatten()
elif isinstance(embedding, list):
embedding = np.array(embedding).flatten()
else:
raise ValueError(f"Unexpected embedding type: {type(embedding)}")
return embedding.tolist()

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 @@ -423,6 +423,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
7 changes: 6 additions & 1 deletion requirements_additional.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,9 @@ 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
typing-extensions
pydantic