Python常用工具_dlib库的使用:人脸检测,人脸关键点

 西瓜视频主页常住: @智能之心

import cv2
import collections
import numpy as np
import PIL.Image as Image
from typing import Union, List
import matplotlib.pyplot as plt


def display_faces(img, faces, fig_size=[4, 4]):
    # 画图- 人脸定位
    for face in faces:
        cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (255,0,0), 4)
        pass
    fig = plt.figure(figsize=fig_size)
    plt.imshow(img)
    plt.show()

def display_facial_landmarks(
    img: Image, 
    landmarks: List[np.ndarray],
    fig_size=[4, 4]
):
    '''
    landmarks[0].shape = (68,2)
    '''
    plot_style = dict(
        marker='o',
        markersize=6,
        linestyle='-',
        lw=2,
    )
    pred_type = collections.namedtuple('prediction_type', ['slice', 'color'])
    pred_types = {
        'face': pred_type(slice(0, 17), (0.682, 0.780, 0.909, 0.5)),
        'eyebrow1': pred_type(slice(17, 22), (1.0, 0.498, 0.055, 0.4)),
        'eyebrow2': pred_type(slice(22, 27), (1.0, 0.498, 0.055, 0.4)),
        'nose': pred_type(slice(27, 31), (0.345, 0.239, 0.443, 0.4)),
        'nostril': pred_type(slice(31, 36), (0.345, 0.239, 0.443, 0.4)),
        'eye1': pred_type(slice(36, 42), (0.596, 0.875, 0.541, 0.3)),
        'eye2': pred_type(slice(42, 48), (0.596, 0.875, 0.541, 0.3)),
        'lips': pred_type(slice(48, 60), (0.596, 0.875, 0.541, 0.3)),
        'teeth': pred_type(slice(60, 68), (0.596, 0.875, 0.541, 0.4))
    }

    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(1, 1, 1)
    ax.imshow(img)
    ax.axis('on')
    for face in landmarks:
        for pred_type in pred_types.values():
            ax.plot(
                face[pred_type.slice, 0],
                face[pred_type.slice, 1],
                color=pred_type.color, **plot_style
            )
    plt.show()
    pass
import cv2
import dlib  # pip install cmake +  pip instal dlib :有人脸检测定位+人脸关键点检测定位-> 工具 Get - 不用自己再建立模型了
import requests
import numpy as np
import PIL.Image as Image
import matplotlib.pyplot as plt

############################################
# 图片
############################################
img_url = 'http://t10.baidu.com/it/u=3509745159,152503870&fm=30&app=106&f=PNG?w=640&h=421&s=99A9FB1508A375155D99D0C503006021'
src = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")

############################################
# 模型 - 人脸定位 -> faces
############################################
img0 = src.copy()
if isinstance(img0, Image.Image):
    img0 = np.array(img0)
    pass
detector = dlib.get_frontal_face_detector()
faces = detector(img0, 0)
# 画图- 人脸定位
from utils.plot_landmarks import display_faces
display_faces(img0, faces, [10,10])


############################################
# 模型 - 关键定位 -> landmarks
############################################
img1 = src.copy()
if isinstance(img1, Image.Image):
    img1 = np.array(img1)
    pass
shape_predictor = dlib.shape_predictor("./weights/shape_predictor_68_face_landmarks.dat")
landmarks = []
for face in faces:
    shape = shape_predictor(img1, face)
    landmarks.append(np.array([[v.x, v.y] for v in shape.parts()]))
    pass
# 画图- 关键定位
from utils.plot_landmarks import display_facial_landmarks
display_facial_landmarks(img1, landmarks, [10,10])  # 人脸关键点显示


版权声明:本文为weixin_41275726原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。