图片加口罩代码

import cv2
import dlib
import time


def get_mouth(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    width_w, height_h = img_gray.shape[0], img_gray.shape[1]
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('models/shape_predictor_68_face_landmarks.dat')
    faces = detector(img_gray, 0)
    for k, d in enumerate(faces):
        x = []
        y = []
        height = d.bottom() - d.top()
        width = d.right() - d.left()
        shape = predictor(img_gray, d)
        for i in range(48, 68):
            x.append(shape.part(i).x)
            y.append(shape.part(i).y)
        y_max = int(max(y) + height / 3) if int(max(y) + height / 3) < height_h else height_h
        y_min = int(min(y) - height / 3) if int(max(y) - height / 3) > 0 else 0
        x_max = int(max(x) + width / 3) if int(max(x) + width / 3) < width_w else width_w
        x_min = int(min(x) - width / 3) if int(max(x) - width / 3) > 0 else 0
        size = ((x_max-x_min), (y_max-y_min))
        return x_min, x_max, y_min, y_max, size


start_time = time.time()
img = cv2.imread('./alignment_imgs/anchor_imgs/376390.jpg')
x_min, x_max, y_min, y_max, size = get_mouth(img)
img2 = cv2.imread('masks/4.png', cv2.IMREAD_UNCHANGED)
img2 = cv2.resize(img2, size)
alpha_channel = img2[:, :, 3]
_, mask = cv2.threshold(alpha_channel, 220, 255, cv2.THRESH_BINARY)
color = img2[:, :, :3]
img2 = cv2.bitwise_not(cv2.bitwise_not(color, mask=mask))

rows, cols, channels = img2.shape
roi = img[y_min: y_min + rows, x_min:x_min + cols]

img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 254, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
img1_bg = cv2.bitwise_and(roi, roi, mask=mask)
img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)
dst = cv2.add(img1_bg, img2_fg)
img[y_min: y_min + rows, x_min:x_min + cols] = dst
print('Process time is {} s'.format(time.time() - start_time))
cv2.imwrite('result.jpg', img)

猜你喜欢

转载自blog.csdn.net/linghu8812/article/details/104409841
今日推荐