python – How do I align and crop the images located in subdirectories for face recognition?
Seems like the question is How do I loop through files and write back?
Several questions on how to iterate through files:
How do I align and crop the images located in subdirectories for face recognition?, Recursive sub folder search and return files in a list python
To crop images you can use Pillow: https://pillow.readthedocs.io/en/stable/
To save images:
f = open(filepath/filename.png,wb) #wb = write byte. Path from the recursive search f.write(image) #From opencv+numpy->pillow f.close()
Firstly, walk all directories and sub directories. The following code block will store the exact paths of images in sub-directories.
employees =  for r, d, f in os.walk(db_path): # r=root, d=directories, f = files for file in f: if (.jpg in file): exact_path = r + / + file employees.append(exact_path)
employees list stores exact image paths. We need to detect and align faces. Herein, deepface offers detection and alignment in a single function.
#!pip install deepface from deepface import DeepFace import cv2 index = 0 for employee in employees: aligned_face = DeepFace.detectFace(employee) cv2.imwrite(aligned_face/%d.jpg % (index), aligned_face) index = index + 1
This will save detected and aligned faces in aligned_face folder.
Deepface also offers a face recognition module as well but you asked how to detect and align faces.