Skip to content

Commit

Permalink
Detect with Retina and crop faces to 300px.
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilm committed Jul 13, 2022
1 parent 544d8da commit 15aab04
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 3 deletions.
52 changes: 52 additions & 0 deletions recognition/crop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from autocrop.autocrop import Cropper, open_file, ImageReadError, check_underexposed, bgr_to_rbg
import cv2


class CustomCrop(Cropper):
def __init__(self, width=500,
height=500,
face_percent=50,
padding=None,
fix_gamma=True):
super().__init__(width=width, height=height, face_percent=face_percent, padding=padding, fix_gamma=fix_gamma)

def crop(self, path_or_array, left, top, right, bottom):

if isinstance(path_or_array, str):
image = open_file(path_or_array)
else:
image = path_or_array

# Some grayscale color profiles can throw errors, catch them
try:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
except cv2.error:
gray = image

try:
img_height, img_width = image.shape[:2]
except AttributeError:
raise ImageReadError

x, y, w, h = left, top, right-left, bottom-top
pos = self._crop_positions(
img_height,
img_width,
x,
y,
w,
h,
)

# ====== Actual cropping ======
image = image[pos[0]: pos[1], pos[2]: pos[3]]

# Resize
image = cv2.resize(
image, (self.width, self.height), interpolation=cv2.INTER_AREA
)

# Underexposition
if self.gamma:
image = check_underexposed(image, gray)
return bgr_to_rbg(image)
21 changes: 18 additions & 3 deletions recognition/extract_all_faces.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,31 @@
from retinaface import RetinaFace
from pathlib import Path
from PIL import Image
from crop import CustomCrop

out_dir = Path("../images/ungrouped_faces/")
image_paths = Path("../images/original_photos/").glob("*jpg")

faces_idx = 1

for img_path in image_paths:
faces = RetinaFace.extract_faces(img_path=str(img_path))
for face_img in faces:
im = Image.fromarray(face_img)
detected_faces_desc = RetinaFace.detect_faces(str(img_path))
if type(detected_faces_desc) != dict:
continue

for face_details in detected_faces_desc.values():

match_score = float(face_details['score'])
if match_score < 0.95:
continue

face_roi = face_details['facial_area']
try:
cropped_face_img = CustomCrop(width=300, height=300, face_percent=80).crop(str(img_path), *face_roi)
except Exception:
continue

im = Image.fromarray(cropped_face_img)
face_path = out_dir / f"{faces_idx}.jpg"
im.save(str(face_path))
faces_idx += 1

0 comments on commit 15aab04

Please sign in to comment.