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

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

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

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

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

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

  5. 依赖库

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

主要流程:

  • 加载模型 :通过 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)
相关推荐
啟明起鸣2 分钟前
【网络编程】从与 TCP 服务器的对比中探讨出 UDP 协议服务器的并发方案(C 语言)
服务器·c语言·开发语言·网络·tcp/ip·udp
007php00710 分钟前
Redis高级面试题解析:深入理解Redis的工作原理与优化策略
java·开发语言·redis·nginx·缓存·面试·职场和发展
潜龙952713 分钟前
第6.2节 Android Agent开发<二>
android·python·覆盖率数据
九章云极AladdinEdu23 分钟前
深度学习优化器进化史:从SGD到AdamW的原理与选择
linux·服务器·开发语言·网络·人工智能·深度学习·gpu算力
axban25 分钟前
QT M/V架构开发实战:QStandardItemModel介绍
开发语言·数据库·qt
猿究院-赵晨鹤39 分钟前
String、StringBuffer 和 StringBuilder 的区别
java·开发语言
I'm a winner1 小时前
第五章:Python 数据结构:列表、元组与字典(一)
开发语言·数据结构·python
葵野寺1 小时前
【RelayMQ】基于 Java 实现轻量级消息队列(九)
java·开发语言·rabbitmq·java-rabbitmq
番薯大佬1 小时前
Python学习-day9 字典Dictionary
网络·python·学习
nightunderblackcat1 小时前
新手向:C语言、Java、Python 的选择与未来指南
java·c语言·python