如何对齐和裁剪位于子目录中的图像以进行人脸识别?

问题描述

因此,我有一个包含132个子文件夹的文件夹,其中人的名字作为文件名称。每个子文件夹都有5张脸部图像。我想遍历所有子文件夹,对齐并裁剪图像以进行人脸识别,并将所有子文件夹存储在名为“ aligned_face”的新文件夹中。我找到了用于面部裁剪和对齐的代码。我的问题是,如何使用此代码循环遍历我的132个子文件夹并将所有对齐并裁剪的面存储在前面提到的名为“ aligned_face”的文件夹中?

gettext

解决方法

问题似乎是“如何循环浏览文件并写回”?

关于如何遍历文件的几个问题: 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

要裁剪图像,可以使用枕头:https://pillow.readthedocs.io/en/stable/

要保存图像:

f = open('filepath/filename.png','wb') #wb = write byte. Path from the recursive search
f.write(image) #From opencv+numpy->pillow
f.close()
,

首先,遍历所有目录和子目录。以下代码块将在子目录中存储图像的确切路径。

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)

员工列表存储确切的图像路径。我们需要检测并对齐面部。在这里,deepface在一个功能中提供了检测和对齐功能。

#!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

这会将检测到并对齐的脸部保存在aligned_face文件夹中。

Deepface还提供了面部识别模块,但是您询问了如何检测和对齐面部。