Python 人脸检测:使用 Dlib 和 OpenCV

简介

本文用Python、Dlib 和 OpenCV 库来检测图像中的人脸,并在人脸上绘制矩形框进行窗口显示。

环境准备

在开始之前,请确保您的计算机上已安装 Python。此外,您还需要安装以下库:

  • dlib:一个包含多种机器学习算法的库,包括人脸检测。
  • opencv-python(即 OpenCV):一个强大的计算机视觉库,用于图像处理和视频分析。
  • numpy:一个用于科学计算的库,用于处理多维数组和矩阵。

您可以使用 pip 来安装这些库:

bash 复制代码
pip install dlib opencv-python numpy

另外,dlib的安装可能出现问题,可以参考该文:https://blog.csdn.net/qq_43466323/article/details/120855699

代码解析

python 复制代码
import dlib
import cv2
import numpy as np
from pathlib import Path
from time import time

# 加载dlib人脸检测器
detector = dlib.get_frontal_face_detector()


def read_image(file, flags=1):
    """读取图像,特别适合文件路径出现中文的情况"""
    return cv2.imdecode(np.fromfile(file, np.uint8), flags)


def scale_image(img, max_width=1920, max_height=1080):
    """比例缩放图片"""
    # 获取原始图片的尺寸
    height, width = img.shape[:2]
    # 只有图片宽度或高度超出指定范围,才缩放图片
    if width > max_width or height > max_height:
        # 计算缩放比例
        ratio = min(max_width / width, max_height / height)
    else:
        ratio = 1
    # 缩放图片
    return cv2.resize(img, None, fx=ratio, fy=ratio)


def detect_image(img):
    """人脸检测并绘制人脸矩形框  """
    # 只对BGR图转化灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 检测人脸
    faces = detector(gray)
    # 绘制人脸矩形框
    for face in faces:
        x, y, w, h = face.left(), face.top(), face.width(), face.height()
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    return img


def run(file):
    """将绘制人脸矩形框的图片进行显示"""
    start_time = time()
    # 人脸检测
    img = detect_image(scale_image(read_image(file)))
    # 计算人脸检测耗时并作为窗口标题显示
    win_name = f'duration:{time() - start_time:.2f}'
    cv2.imshow(win_name, img)
    key = cv2.waitKey()
    cv2.destroyAllWindows()
    return key


def run_many(dir_path):
    """依次检测指定目录的图片并显示"""
    print('温馨提示:按q键退出,其他按键切换图片')
    for file in Path(dir_path).iterdir():
        # 按q键退出
        if ord('q') == run(file):
            break

导入库

python 复制代码
import dlib
import cv2
import numpy as np
from pathlib import Path
from time import time

这段代码导入了我们所需的所有外部库。

初始化人脸检测器

python 复制代码
detector = dlib.get_frontal_face_detector()

这行代码初始化了 Dlib 的人脸检测器,用于后续的人脸检测操作。

读取图像函数

python 复制代码
def read_image(file, flags=1):
    return cv2.imdecode(np.fromfile(file, np.uint8), flags)

这个函数用于读取图像文件,特别适合处理包含中文路径的文件。

缩放图像函数

python 复制代码
def scale_image(img, max_width=1920, max_height=1080):
    height, width = img.shape[:2]
    if width > max_width or height > max_height:
        ratio = min(max_width / width, max_height / height)
    else:
        ratio = 1
    return cv2.resize(img, None, fx=ratio, fy=ratio)

这个函数用于按比例缩放图像,以确保图像的宽度和高度不会超过指定的最大值。

人脸检测函数

python 复制代码
def detect_image(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector(gray)
    for face in faces:
        x, y, w, h = face.left(), face.top(), face.width(), face.height()
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    return img

这个函数将图像转换为灰度图,然后使用 Dlib 的检测器来检测人脸,并在每个检测到的人脸周围绘制一个绿色的矩形框。

运行检测函数(主函数)

python 复制代码
def run(file):
    start_time = time()
    img = detect_image(scale_image(read_image(file)))
    win_name = f'duration:{time() - start_time:.2f}'
    cv2.imshow(win_name, img)
    key = cv2.waitKey()
    cv2.destroyAllWindows()
    return key

这个函数读取一个图像文件,对其进行缩放和人脸检测,然后显示结果。

批量检测函数(主函数)

python 复制代码
def run_many(dir_path):
    print('温馨提示:按q键退出,其他按键切换图片')
    for file in Path(dir_path).iterdir():
        if ord('q') == run(file):
            break

这个函数遍历指定目录下的所有图像文件,并使用 run 函数对每个文件进行人脸检测和显示。

相关推荐
CCblandy1 小时前
前缀缓存命中率不靠引擎靠排列:本机仿真 3 轮,易变字段放开头 98.0%→0.0%
人工智能·python·算法·自然语言处理·性能优化
Sakura_j_h_1 小时前
给 FastAPI 接大模型:超时、重试和 token 成本该怎么管
python·大模型·fastapi·超时重试·token计费
forest_091 小时前
用Python复刻ClaudeDuet:主动式Agent四件套,定时晨报、后台巡检、危险动作审批(附完整可运行代码)
人工智能·python·架构·prompt·agi
小小张说故事2 小时前
Python 的函数调用到底贵在哪?拆开一次 call:51 纳秒栈帧与 *args 的 40 纳秒罚单
python
程序猿乐锅3 小时前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节
lzqrzpt3 小时前
太阳能控制器选型要点:电路工艺与工程适配技术解析
python·1024程序员节
databook3 小时前
时间序列数据中,如何找出缺失值
python·数据分析
小小龙学IT4 小时前
Python Polars 高性能数据处理引擎深度解析
开发语言·python·rust·1024程序员节
csdn_aspnet5 小时前
JavaScript 未排序数组中第 k 个最小/最大元素 (预期线性时间)
python
quantdash_cc5 小时前
如何利用标的信息为研究股票池补充名称和交易所信息?
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash