
pip install opencv-python
pip install dlib
人脸检测基于事先训练好的模型数据,从这里可以下到模型数据
下载到本地路径后解压,记下解压后的文件路径,程序中会用到。
dlib的人脸特征点
上面下载的模型数据是用来估计人脸上68个特征点(x, y)的坐标位置,这68个坐标点的位置如下图所示:
import sys
import numpy as np
import dlib
import cv2
#if len(sys.argv) < 2:
# print "Usage: %s" %sys.argv[0]
# sys.exit(1)
#image_file = sys.argv[1]
image_file =('psb2.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=900)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
def rect_to_bb(rect):
x = rect.left()
y = rect.top()
w = rect.right() -x
h = rect.bottom() - y
return (x, y, w,h)
这个函数里的rect是dlib脸部区域检测的输出。这里将rect转换成一个序列,序列的内容是矩形区域的边界信息。imread
def shape_to_np(shape, dtype="int"):
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
这个函数里的shape是dlib脸部特征检测的输出,一个shape里包含了前面说到的脸部特征的68个点。这个函数将shape转换成Numpyarray,为方便后续处理。

def resize(image, width=1200):
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
这个函数里的image就是我们要检测的图片。在人脸检测程序的最后,我们会显示检测的结果图片来验证,这里做resize是为了避免图片过大,超出屏幕范围。imread
for (i, rect) in enumerate(rects):
shape = predictor(gray,rect)
shape =shape_to_np(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 - 15, y - 15),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
for (x, y) inshape:
cv2.circle(image, (x, y), 1, (0, 0, 255),-1)
对于每一张检测到的脸,我们进一步检测脸部的特征(鼻子、眼睛、眉毛等)。对于脸部区域,我们用绿色的框在照片上标出;对于脸部特征,我们用红色的点标出来。
最后我们把加了检测标识的照片显示出来,waitKey(0)表示按任意键可退出程序。
#point size
cv2.imshow("Output", image)
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-65135-1.html
到你现在几千元