使用Python、OpenCV和Dlib库的示例代码,基于人脸5个特征点给人脸口部区域添加口罩掩膜

在运行此代码之前,请确保已安装以下库:

OpenCV (pip install opencv-python)
Dlib (pip install dlib)

同时,请确保下载并提供以下文件:

一个包含口罩图像的PNG文件,文件名为 "mask.png"(或其他名称,但需要在代码中相应地更改)。确保口罩图像具有透明背景。
Dlib的预训练模型文件 "shape_predictor_5_face_landmarks.dat",可从 [模型文件](http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2)下载。下载后,将其解压缩以获取.dat文件。

此示例代码将打开计算机的摄像头,并在检测到的人脸上添加口罩。按 “q” 键退出程序。

import cv2
import dlib
import numpy as np

def add_mask(face_image, mask_image_path, landmarks):
    mask_image = cv2.imread(mask_image_path, cv2.IMREAD_UNCHANGED)
    mask_height, mask_width, _ = mask_image.shape

    left_eye_x = landmarks.part(36).x
    left_eye_y = landmarks.part(36).y
    right_eye_x = landmarks.part(45).x
    right_eye_y = landmarks.part(45).y
    mouth_x = landmarks.part(57).x
    mouth_y = landmarks.part(57).y

    mask_width = int(abs(right_eye_x - left_eye_x) * 1.5)
    mask_height = int(mask_width * (mask_height / mask_width))

    mask_resized = cv2.resize(mask_image, (mask_width, mask_height), interpolation=cv2.INTER_CUBIC)

    mask_alpha = mask_resized[:, :, 3] / 255
    mask_alpha_inv = 1.0 - mask_alpha

    mask_start_x = left_eye_x - int(mask_width * 0.2)
    mask_start_y = left_eye_y + int(mask_height * 0.2)
    mask_end_x = mask_start_x + mask_width
    mask_end_y = mask_start_y + mask_height

    face_roi = face_image[mask_start_y:mask_end_y, mask_start_x:mask_end_x]

    for c in range(0, 3):
        face_roi[:, :, c] = (mask_alpha * mask_resized[:, :, c] + mask_alpha_inv * face_roi[:, :, c])

    face_image[mask_start_y:mask_end_y, mask_start_x:mask_end_x] = face_roi

    return face_image

def main():
    face_detector = dlib.get_frontal_face_detector()
    landmark_predictor = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat")

    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()

        if not ret:
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_detector(gray)

        for face in faces:
            landmarks = landmark_predictor(gray, face)
            frame = add_mask(frame, "mask.png", landmarks)

        cv2.imshow("Masked Face", frame)

        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值