Python 检测人脸筛选指定尺寸人脸图片

主要功能是处理一个指定文件夹中的所有图像文件(.jpg 和 .png),并根据图像中检测到的人脸特征,筛选和移动符合条件的图像。具体步骤如下:

  1. 人脸检测和关键点检测 : 使用 dlib 的预训练人脸检测器(frontal_face_detector)和 68 个关键点预测器来检测图像中的人脸及其关键点(如眼睛、嘴巴等)。

  2. 条件判断: 对每张图像,如果检测到的人脸宽度小于 130 像素且两眼之间的距离小于 60 像素,则将该图片移动到指定的目标文件夹中,并保持源文件夹的目录结构不变。

  3. 目录结构保持: 在移动符合条件的图片时,保持源文件夹的目录层级结构,即原始文件夹的子目录在目标文件夹中会被保留。

  4. 无效图像处理: 如果一张图像中未检测到人脸或人脸太小,则该图像也会被移动到目标文件夹,并打印相应的提示信息。

  5. 依赖库:

    • 使用 dlib 进行人脸检测和关键点识别。
    • 使用 opencv 进行图像处理。
    • 使用 os 和 shutil 处理文件和目录操作。

主要流程:

  • 加载模型 :通过 dlib 加载人脸检测器和 68 个关键点检测模型。
  • 处理文件夹:递归遍历指定源文件夹,处理所有符合条件的图像。
  • 人脸检测与筛选:对于每张图像,检测人脸并计算人脸宽度和双眼之间的距离,符合条件的图像会被移动到目标文件夹。
  • 文件移动 :使用 shutil 进行文件的移动操作,并在目标文件夹中保持与源文件夹一致的目录结构。

这个代码可以用于图像筛选工作,尤其是基于人脸特征的筛选任务,比如选择图像中人脸较小或两眼之间距离较近的图像进行进一步处理。

复制代码
import cv2
import dlib
import math
import os
import shutil

# https://www.anaconda.com/download/success
# https://github.com/sachadee/Dlib/blob/main/dlib-19.22.99-cp38-cp38-win_amd64.whl
# https://github.com/italojs/facial-landmarks-recognition/blob/master/shape_predictor_68_face_landmarks.dat

# conda create -n python38 python=3.8
# conda activate python38
# pip install dlib-19.22.99-cp38-cp38-win_amd64.whl
# pip install opencv-python

# 加载dlib的人脸检测器和68个关键点预测模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(r'c:\python38\shape_predictor_68_face_landmarks.dat')

# 指定源文件夹和目标文件夹
source_folder = r'c:\python38\face'
target_folder = r'c:\python38\face60'

# 创建目标文件夹,如果不存在的话
if not os.path.exists(target_folder):
    os.makedirs(target_folder)

def process_image(img_path, relative_path):
    # 加载图片
    img = cv2.imread(img_path)

    if img is None:
        print(f"无法读取文件:{img_path}")
        return

    # 转换为灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = detector(gray)

    if len(faces) == 0:
        print(f"未检测到人脸或人脸太小:{img_path}")
        # 将无效人脸或没有检测到人脸的图片移动到目标文件夹
        target_subdir = os.path.join(target_folder, relative_path)
        if not os.path.exists(target_subdir):
            os.makedirs(target_subdir)
        shutil.move(img_path, os.path.join(target_subdir, os.path.basename(img_path)))
        print(f"移动文件 {img_path} 到 {target_subdir}")
        return

    for face in faces:
        # 获取人脸的边界框坐标
        x1 = face.left()
        y1 = face.top()
        x2 = face.right()
        y2 = face.bottom()

        # 计算人脸宽度
        face_width = x2 - x1

        # 打印人脸宽度
        print(f"文件: {img_path} 人脸宽度: {face_width} 像素")

        # 使用预测模型预测人脸的68个关键点
        landmarks = predictor(gray, face)

        # 获取左右眼的关键点(左眼36-41,右眼42-47)
        left_eye_x = (landmarks.part(36).x + landmarks.part(39).x) // 2
        left_eye_y = (landmarks.part(36).y + landmarks.part(39).y) // 2
        right_eye_x = (landmarks.part(42).x + landmarks.part(45).x) // 2
        right_eye_y = (landmarks.part(42).y + landmarks.part(45).y) // 2

        # 计算双眼之间的距离
        eye_distance = math.sqrt((right_eye_x - left_eye_x) ** 2 + (right_eye_y - left_eye_y) ** 2)

        # 如果人脸宽度小于130且双眼距离小于60,移动文件
        if face_width < 130 and eye_distance < 60:
            # 目标文件夹保持目录结构
            target_subdir = os.path.join(target_folder, relative_path)
            if not os.path.exists(target_subdir):
                os.makedirs(target_subdir)
            
            # 移动文件
            shutil.move(img_path, os.path.join(target_subdir, os.path.basename(img_path)))
            print(f"移动文件 {img_path} 到 {target_subdir}")

def process_folder(source_folder):
    for root, dirs, files in os.walk(source_folder):
        for file in files:
            if file.endswith('.jpg') or file.endswith('.png'):
                img_path = os.path.join(root, file)
                # 获取相对路径以保持目录结构
                relative_path = os.path.relpath(root, source_folder)
                process_image(img_path, relative_path)

# 处理整个文件夹
process_folder(source_folder)
相关推荐
摇滚侠32 分钟前
《On Java 中文版 基础卷》阅读笔记 内部类 20
java·笔记·python
维爱智VR认知学能2 小时前
VR学能软件离线断线与乱序事件测试:确定性到达表与重放
python·单元测试·软件工程·分布式系统·离线同步
郝学胜-神的一滴3 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
Thanks_ks3 小时前
SQL 注入是怎么发生的:从拼接 SQL 讲到预编译语句的防御原理
python·sqlite·orm·占位符·sql 注入·预编译语句·白名单校验
好焊孙辉4 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克6054 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴4 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio5 小时前
Java IO流核心分类与应用
java·开发语言·笔记
Kari116 小时前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
专注仿真7 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体