在运行此代码之前,请确保已安装以下库:
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()