diff --git a/deepface/modules/detection.py b/deepface/modules/detection.py index cbef0b5..6b5ab2e 100644 --- a/deepface/modules/detection.py +++ b/deepface/modules/detection.py @@ -85,7 +85,9 @@ def extract_faces( if img is None: raise ValueError(f"Exception while loading {img_name}") - base_region = FacialAreaRegion(x=0, y=0, w=img.shape[1], h=img.shape[0], confidence=0) + height, width, _ = img.shape + + base_region = FacialAreaRegion(x=0, y=0, w=width, h=height, confidence=0) if detector_backend == "skip": face_objs = [DetectedFace(img=img, facial_area=base_region, confidence=0)] @@ -137,10 +139,11 @@ def extract_faces( if normalize_face: current_img = current_img / 255 # normalize input in [0, 1] - x = int(current_region.x) - y = int(current_region.y) - w = int(current_region.w) - h = int(current_region.h) + # cast to int for flask, and do final checks for borders + x = max(0, int(current_region.x)) + y = max(0, int(current_region.y)) + w = min(width - x - 1, int(current_region.w)) + h = min(height - y - 1, int(current_region.h)) resp_obj = { "face": current_img, diff --git a/tests/dataset/selfie-many-people.jpg b/tests/dataset/selfie-many-people.jpg new file mode 100644 index 0000000..a6fed51 Binary files /dev/null and b/tests/dataset/selfie-many-people.jpg differ diff --git a/tests/test_extract_faces.py b/tests/test_extract_faces.py index fe94705..1d8f849 100644 --- a/tests/test_extract_faces.py +++ b/tests/test_extract_faces.py @@ -98,3 +98,28 @@ def image_to_base64(image_path): with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") return "data:image/jpeg," + encoded_string + + +def test_facial_coordinates_are_in_borders(): + img_path = "dataset/selfie-many-people.jpg" + img = cv2.imread(img_path) + height, width, _ = img.shape + + results = DeepFace.extract_faces(img_path=img_path) + + assert len(results) > 0 + + for result in results: + facial_area = result["facial_area"] + + x = facial_area["x"] + y = facial_area["y"] + w = facial_area["w"] + h = facial_area["h"] + + assert x >= 0 + assert y >= 0 + assert x + w < width + assert y + h < height + + logger.info("✅ facial area coordinates are all in image borders")