文章基于opencv的shape_predictor_68_face_landmarks.dat模型,进行一些简单的人脸检测。
代码1: 检测人脸–描点
import matplotlib.pyplot as plt
import cv2
import numpy as np
import dlib
# 如果未检测到人脸,那么返回false,否则返回true
face_detector = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor("class\shape_predictor_68_face_landmarks.dat") #加载人脸特征点模型
def geteye_rect(imgpath):
bgrImg = cv2.imread(imgpath)
if bgrImg is None:
return False
rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)
facesrect = face_detector(rgbImg, 1)
if len(facesrect) <= 0:
return False
for k, d in enumerate(facesrect):
shape = landmark_predictor(rgbImg, d)
for i in range(68):
pt = shape.part(i)
plt.plot(pt.x, pt.y, 'ro')
plt.imshow(rgbImg)
plt.show()
aa='img/t1.jpg'
geteye_rect(aa)
代码2: 检测人脸–画框
import cv2
face_cascade=cv2.CascadeClassifier("class/haarcascade_frontalface_alt.xml")
image = cv2.imread("img/a2.jpg") #读取图片
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #灰度转换
faces = face_cascade.detectMultiScale( #探测人脸
gray,
scaleFactor = 1.15,
minNeighbors = 3,
minSize = (50,50),
)
print("发现{0}个人脸!".format(len(faces)))
for(x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),1)
# print(x,y)
cv2.imshow("Gakki!",image) #显示图像
cv2.waitKey(0)
代码3: 检测人脸–描点并标上特征点数字
# _*_ coding:utf-8 _*_
import numpy as np
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('class/shape_predictor_68_face_landmarks.dat')
# cv2读取图像
img = cv2.imread("img/t1.jpg")
# 取灰度
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 人脸数rects
rects = detector(img_gray, 0)
for i in range(len(rects)):
landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[i]).parts()])
for idx, point in enumerate(landmarks):
# 68点的坐标
pos = (point[0, 0], point[0, 1])
print(idx,pos)
# 利用cv2.circle给每个特征点画一个圈,共68个
cv2.circle(img, pos, 5, color=(0, 255, 0))
# 利用cv2.putText输出1-68
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str(idx+1), pos, font, 0.8, (0, 0, 255), 1,cv2.LINE_AA)
cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)