文章目录
文章参考: https://blog.csdn.net/liuxiao214/article/details/83411820
1 python实现
1.1 dlib准备:
(1)dlib安装:
pip install dlib
大约等10分钟,中途会卡在“Building wheel for dlib (setup.py) …”
其他安装方法参考:
1)https://blog.csdn.net/qq_41185868/article/details/79678783
2)python37 https://www.jianshu.com/p/9503b1434529
3)python35, python36 https://github.com/coneypo/Dlib_install/tree/master/for_windows
(2)dlib检测模型(离线包)下载链接:http://dlib.net/files/
人脸68个特征点模型:shape_predictor_68_face_landmarks.dat.bz2
1.2 人脸框检测
人脸框检测不用加载离线包
demo:
# -*- coding: utf-8 -*-
import dlib
import numpy as np
import cv2
def rect_to_bb(rect): # 获得人脸矩形的坐标信息
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return (x, y, w, h)
def resize(image, width=1200): # 将待检测的image进行resize
r = width * 1.0 / image.shape[1]
dim = (width, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
return resized
def detect():
image_file = "234.jpg"
detector = dlib.get_frontal_face_detector()
image = cv2.imread(image_file)
# image = resize(image, width=500)
image = resize(image, width=1200)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 3) # 2表示采样次数,数字越大检测到人头越多。对于多人头,该值越大检测到人头越多。图片变大也可以检测到多人头。
for (i, rect) in enumerate(rects):
(x, y, w, h) = rect_to_bb(rect)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# cv2.putText(image, "Face: {}".format(i + 1), (x - 10, y - 10), cv2.FONT_HERSHEY_COMPLEX, 2, (255, 0, 0),2)
cv2.imshow("Output", image)
cv2.waitKey(0)
if __name__ == "__main__":
detect()
测试结果:
1.3 人脸68个关键点检测
68个关键点检测需要加载离线包,离线包下载慢可以用下面链接下载:
https://download.csdn.net/download/weixin_41874898/14354822
demo:
# encoding:utf-8
import dlib
import numpy as np
import cv2
def rect_to_bb(rect): # 获得人脸矩形的坐标信息
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return (x, y, w, h)
def shape_to_np(shape, dtype="int"): # 将包含68个特征的的shape转换为numpy array格式
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
def resize(image, width=1200): # 将待检测的image进行resize
r = width * 1.0 / image.shape[1]
dim = (width, int(image.shape[0] * r))
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
return resized
def feature():
image_file = "test.jpg"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
image = cv2.imread(image_file)
image = resize(image, width=1200)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
shapes = []
for (i, rect) in enumerate(rects):
shape = predictor(gray, rect)
shape = shape_to_np(shape)
shapes.append(shape)
(x, y, w, h) = rect_to_bb(rect)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, "Face: {}".format(i + 1), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5