import dlib
import numpy as np
import cv2
import imutils
from imutils import face_utils# 使用 Dlib 的正面人脸检测器 frontal_face_detector
detector = dlib.get_frontal_face_detector()
# 使用训练好的模型shape_predictor_68_face_landmarks.dat,在检测出人脸的同时,检测出人脸上的68个关键点
predictor=dlib.shape_predictor(r'C:\Python\Pycharm\docxprocess\face_detector\shape_predictor_68_face_landmarks.dat')# 图片所在路径
imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui1.jpg' #21
imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui2.png' #6
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\ldh\angry.png'
imgname = r'C:\Python\Pycharm\docxprocess\picture\other\ldh\ldh.png'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\ldh\happy.png'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\ldh\shigu.jpeg'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui4.png' #24
# 读取图片,转换灰度
img = cv2.imread(imgname)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)# 人脸检测,获得人脸数据
faces = detector(img_gray, 1)
# rectangles[[(941, 254) (977, 290)], [(361, 210) (397, 246)], [(717, 138) (753, 174)], [(801, 214) (837, 250)],
# [(573, 138) (609, 174)], [(45, 210) (81, 246)], [(585, 202) (621, 238)], [(189, 254) (225, 290)],
# [(245, 214) (281, 250)], [(689, 210) (725, 246)], [(419, 247) (463, 290)], [(553, 242) (589, 278)],
# [(901, 218) (937, 254)], [(77, 246) (113, 282)], [(141, 222) (177, 258)], [(741, 242) (777, 278)],
# [(485, 202) (521, 238)], [(161, 110) (197, 146)], [(297, 166) (333, 202)], [(905, 138) (941, 174)],
# [(301, 246) (337, 282)], [(865, 106) (901, 142)], [(389, 146) (425, 182)], [(241, 138) (277, 174)]]
if len(faces) < 1:
print("未检测到人脸")
else:
print("人脸数总数为", len(faces))
for(i, rect) in enumerate(faces):# 返回人脸框的左上角坐标和矩形框的尺寸
(x, y, w, h) = face_utils.rect_to_bb(rect)
# 在图片上画矩形框和输出检测的人脸数量
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(img, "Face #{}".format(i + 1), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# 标记人脸中的68个landmark点
shape = predictor(img_gray, rect)
#
# shape转换成68个坐标点矩阵
shape = face_utils.shape_to_np(shape)
# [[245 149]
# [245 152]
# ...
# [246 159]]
# [[364 225]
# [365 228]
# ...
# [366 236]]
# 在源图上输出landmark点
for j,(x, y) in enumerate(shape):
cv2.circle(img, (x, y), 2, (0, 0, 255), -1)
cv2.putText(img, "{}".format(j + 1), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)cv2.imshow("Output", img)
cv2.waitKey(0)
关于OpenCV for Python入门之Dlib实现人脸检测
相关推荐
内容页底部广告位3 |
留言与评论(共有 0 条评论) |