Python实现人脸检测和人脸马赛克

Python实现人脸检测和人脸马赛克

目录

Python实现人脸检测和人脸马赛克

1. 人脸检测

2. 人脸马赛克

3. 完整代码 

4. 测试效果 


人脸马赛克的实现核心思路是 “先定位人脸区域,再对该区域进行像素化或模糊处理”,算法实现流程:输入数据。如图片或视频;然后进行人脸检测,定位图像中的人脸区域(矩形坐标),再对人脸区域进行像素化或模糊,实现马赛克效果;最后输出结果保存处理后的图像或实时显示。


1. 人脸检测

人脸检测方法比较多,可以参考

考虑到Python开发,本项目直接使用Dlib实现人脸检测,它是一个强大的 C++ 跨平台机器学习库,同时也提供 Python 接口,在人脸检测和关键点识别领域表现尤为突出。其人脸检测算法以高精度稳定性著称,适合复杂场景下的应用。

Dlib模型可以在这里直接下载:Index of /files


2. 人脸马赛克

人脸马赛克处理,即实现人脸像素化处理,将人脸区域缩小再放大,形成像素块。

import cv2
from pybaseutils import file_utils, image_utils

def apply_mosaic(image, boxes, radius=8, scale=[1.0, 1.0]):
    """
    马赛克
    :param image: BGR image
    :param boxes: 人脸框(xmin,ymin,xmax,ymax)
    :param radius: 马赛克强度
    :param scale: 人脸框扩大范围
    :return:
    """
    ar = (5, 20)
    h, w = image.shape[:2]
    boxes = np.asarray(boxes, dtype=np.int32)
    boxes = image_utils.extend_xyxy(boxes, scale=scale, valid_range=(0, 0, w, h))
    for box in boxes:
        x1, y1, x2, y2 = box
        roi = image[y1:y2, x1:x2]
        size = [(x2 - x1) // radius, (y2 - y1) // radius]
        size[0] = max(min(size[0], ar[1]), ar[0])
        size[1] = max(min(size[1], ar[1]), ar[0])
        img = cv2.resize(roi, tuple(size))
        # img = cv2.resize(roi, (radius, radius))
        img = cv2.resize(img, (x2 - x1, y2 - y1), interpolation=cv2.INTER_NEAREST)
        image[y1:y2, x1:x2] = img
    return image

3. 完整代码 

需要安装opencv-python,pybaseutils和dlib

pip install pybaseutils dlib

# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail : 
# @Date   : 2025-04-01 13:42:03
# @Brief  :
# --------------------------------------------------------
"""
import os
from pybaseutils import file_utils, image_utils
import dlib
import cv2


class FaceDetector(object):
    def __init__(self, model_file):
        """
        :param model_file: 检测模型文件,(https://dlib.net/files/mmod_human_face_detector.dat.bz2)直接下载,然后解压
        """
        self.model = dlib.cnn_face_detection_model_v1(model_file)

    def detect(self, image):
        rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # 读取图像并转换为 RGB
        res = self.model(rgb, 1)
        boxes = []
        for face in res:
            x, y, w, h = face.rect.left(), face.rect.top(), face.rect.width(), face.rect.height()
            boxes.append([x, y, x + w, y + h])
        return boxes

    def image_dir_detect(self, image_dir, vis=True, shuffle=False):
        """
        :param image_dir: list,*.txt ,image path or directory
        :return:
        """
        image_list = file_utils.get_files_lists(image_dir, shuffle=shuffle)
        for path in image_list:
            image = image_utils.read_image(path)
            boxes = self.detect(image)
            self.draw_result(image, boxes, vis=vis)

    def apply_mosaic(self, image, boxes):
        """对人脸框进行马赛克处理"""
        image = image_utils.apply_mosaic(image, boxes, radius=8, scale=[1.0, 1.0])
        return image

    def draw_result(self, image, boxes, vis=True):
        """
        :param image:
        :param boxes:
        :param vis:
        :return:
        """
        image = self.apply_mosaic(image, boxes)  # 马赛克处理
        image = image_utils.draw_image_boxes(image, boxes, color=(0, 255, 0), thickness=2)
        if vis: image_utils.cv_show_image("image", image)
        return image


if __name__ == '__main__':
    # 下载预训练模型文件(需手动下载)
    # 下载地址:https://dlib.net/files/mmod_human_face_detector.dat.bz2,然后解压
    model_file = "path/mmod_human_face_detector.dat"
    image_dir = "path/to/images"
    det = FaceDetector(model_file=model_file)
    det.image_dir_detect(image_dir)

4. 测试效果 

这是demo测试效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI吃大瓜

尊重原创,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值