当前位置:网站首页>Dlib库实现人脸关键点检测(Opencv实现)
Dlib库实现人脸关键点检测(Opencv实现)
2022-06-30 17:20:00 【Keep_Trying_Go】
文章目录
1.dlib实现人脸实时检测
https://mydreamambitious.blog.csdn.net/article/details/124851743
2.dlib采用检测人脸的68个关键点

3.相关文件的下载
4.代码实战
(1)导入库
import os
import cv2
import dlib
import numpy as np
from collections import OrderedDict
(2)人脸关键点的整合
#对于68个检测点,将人脸的几个关键点排列成有序,便于后面的遍历
shape_predictor_68_face_landmark=OrderedDict([
('mouth',(48,68)),
('right_eyebrow',(17,22)),
('left_eye_brow',(22,27)),
('right_eye',(36,42)),
('left_eye',(42,48)),
('nose',(27,36)),
('jaw',(0,17))
])
(3)加载dlib库的人脸检测和人脸关键点检测文件
# 加载人脸检测与关键点定位
#http://dlib.net/python/index.html#dlib_pybind11.get_frontal_face_detector
detector = dlib.get_frontal_face_detector()
#http://dlib.net/python/index.html#dlib_pybind11.shape_predictor
criticPoints = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
(4)对人脸画框
#绘制人脸画矩形框
def drawRectangle(detected,frame):
margin = 0.2
img_h,img_w,_=np.shape(frame)
if len(detected) > 0:
for i, locate in enumerate(detected):
x1, y1, x2, y2, w, h = locate.left(), locate.top(), locate.right() + 1, locate.bottom() + 1, locate.width(), locate.height()
xw1 = max(int(x1 - margin * w), 0)
yw1 = max(int(y1 - margin * h), 0)
xw2 = min(int(x2 + margin * w), img_w - 1)
yw2 = min(int(y2 + margin * h), img_h - 1)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
face = frame[yw1:yw2 + 1, xw1:xw2 + 1, :]
cv2.putText(frame, 'Person', (locate.left(), locate.top() - 10),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 0, 0), 3)
return frame
(5)对检测得到的人脸关键点坐标重新整理
#对检测之后获取的人脸关键点坐标进行转换
def predict2Np(predict):
# 创建68*2关键点的二维空数组[(x1,y1),(x2,y2)……]
dims=np.zeros(shape=(predict.num_parts,2),dtype=np.int)
#遍历人脸的每个关键点获取二维坐标
length=predict.num_parts
for i in range(0,length):
dims[i]=(predict.part(i).x,predict.part(i).y)
return dims
(6)对人脸的关键点绘制点
#遍历预测框,进行人脸的关键点绘制
def drawCriticPoints(detected,frame):
for (step,locate) in enumerate(detected):
#对获取的人脸框再进行人脸关键点检测
#获取68个关键点的坐标值
dims=criticPoints(frame,locate)
#将得到的坐标值转换为二维
dims=predict2Np(dims)
#通过得到的关键点坐标进行关键点绘制
# 从i->j这个范围内的都是同一个区域:比如上面的鼻子就是从27->36
for (name,(i,j)) in shape_predictor_68_face_landmark.items():
#对每个部位进行绘点
for (x,y) in dims[i:j]:
cv2.circle(img=frame,center=(x,y),
radius=2,color=(0,255,0),thickness=-1)
return frame
(7)整体代码
import os
import cv2
import dlib
import numpy as np
from collections import OrderedDict
#https://mydreamambitious.blog.csdn.net/article/details/123535760
#对于68个检测点,将人脸的几个关键点排列成有序,便于后面的遍历
shape_predictor_68_face_landmark=OrderedDict([
('mouth',(48,68)),
('right_eyebrow',(17,22)),
('left_eye_brow',(22,27)),
('right_eye',(36,42)),
('left_eye',(42,48)),
('nose',(27,36)),
('jaw',(0,17))
])
#绘制人脸画矩形框
def drawRectangle(detected,frame):
margin = 0.2
img_h,img_w,_=np.shape(frame)
if len(detected) > 0:
for i, locate in enumerate(detected):
x1, y1, x2, y2, w, h = locate.left(), locate.top(), locate.right() + 1, locate.bottom() + 1, locate.width(), locate.height()
xw1 = max(int(x1 - margin * w), 0)
yw1 = max(int(y1 - margin * h), 0)
xw2 = min(int(x2 + margin * w), img_w - 1)
yw2 = min(int(y2 + margin * h), img_h - 1)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
face = frame[yw1:yw2 + 1, xw1:xw2 + 1, :]
cv2.putText(frame, 'Person', (locate.left(), locate.top() - 10),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 0, 0), 3)
return frame
#对检测之后获取的人脸关键点坐标进行转换
def predict2Np(predict):
# 创建68*2关键点的二维空数组[(x1,y1),(x2,y2)……]
dims=np.zeros(shape=(predict.num_parts,2),dtype=np.int)
#遍历人脸的每个关键点获取二维坐标
length=predict.num_parts
for i in range(0,length):
dims[i]=(predict.part(i).x,predict.part(i).y)
return dims
# 加载人脸检测与关键点定位
#http://dlib.net/python/index.html#dlib_pybind11.get_frontal_face_detector
detector = dlib.get_frontal_face_detector()
#http://dlib.net/python/index.html#dlib_pybind11.shape_predictor
criticPoints = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
#遍历预测框,进行人脸的关键点绘制
def drawCriticPoints(detected,frame):
for (step,locate) in enumerate(detected):
#对获取的人脸框再进行人脸关键点检测
#获取68个关键点的坐标值
dims=criticPoints(frame,locate)
#将得到的坐标值转换为二维
dims=predict2Np(dims)
#通过得到的关键点坐标进行关键点绘制
# 从i->j这个范围内的都是同一个区域:比如上面的鼻子就是从27->36
for (name,(i,j)) in shape_predictor_68_face_landmark.items():
#对每个部位进行绘点
for (x,y) in dims[i:j]:
cv2.circle(img=frame,center=(x,y),
radius=2,color=(0,255,0),thickness=-1)
return frame
#单张图片的人脸关键点检测
def signal_detect(img_path='images/face1.jpg'):
img=cv2.imread(img_path)
detected=detector(img)
frame=drawRectangle(detected,img)
frame = drawCriticPoints(detected, img)
cv2.imshow('frame',frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
#实时的人脸关键点检测
def detect_time():
cap=cv2.VideoCapture(0)
while cap.isOpened():
ret,frame=cap.read()
detected = detector(frame)
frame = drawRectangle(detected, frame)
frame=drawCriticPoints(detected,frame)
cv2.imshow('frame', frame)
key=cv2.waitKey(1)
if key==27:
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
print('Pycharm')
signal_detect()
# detect_time()
(9)单张图片的人脸关键点检测

注:实时检测部分读者可以自己测试。
边栏推荐
- Another CVPR 2022 paper was accused of plagiarism, and Ping An insurance researchers sued IBM Zurich team
- AI首席架构师10-AICA-蓝翔 《飞桨框架设计与核心技术》
- NFT挖矿游GameFi链游系统开发搭建
- What does software testing need to learn? Test learning outline sorting
- [PROJECT] Xiaomao school (IX)
- uni-app进阶之内嵌应用【day14】
- The company was jailed for nonstandard bug during the test ~ [cartoon version]
- What if icloud photos cannot be uploaded or synchronized?
- How to do a good job in software system demand research? Seven weapons make it easy for you to do it
- SaaS project management system solution for the financial service industry helps enterprises tap a broader growth service space
猜你喜欢
![The company was jailed for nonstandard bug during the test ~ [cartoon version]](/img/cd/42ab3fc0000fa7dfe2ac89de3486e4.jpg)
The company was jailed for nonstandard bug during the test ~ [cartoon version]

Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills

LRN local response normalization

助力极致体验,火山引擎边缘计算最佳实践

Hospital online consultation applet source code Internet hospital source code smart hospital source code

Apple Watch无法开机怎么办?苹果手表不能开机解决方法!

countdownlatch 和 completableFuture 和 CyclicBarrier

煤炭行业数智化供应商管理系统解决方案:数据驱动,供应商智慧平台助力企业降本增效

MRO工业品采购管理系统:赋能MRO企业采购各节点,构建数字化采购新体系

Sword finger offer 17 Print from 1 to maximum n digits
随机推荐
系统集成项目管理工程师认证高频考点:编制项目范围管理计划
Deep understanding of JVM (II) - memory structure (II)
How to do a good job in software system demand research? Seven weapons make it easy for you to do it
Hospital online consultation applet source code Internet hospital source code smart hospital source code
[cloud resident co creation] Huawei iconnect enables IOT terminals to connect at one touch
Grep output with multiple colors- Grep output with multiple Colors?
NFT挖矿游GameFi链游系统开发搭建
PHP uses queues to solve maze problems
分布式事务
ASP. Net authentication code login
One script of unity actual combat realizes radar chart
Sword finger offer 17 Print from 1 to maximum n digits
Solve the problem of unable to connect to command metric stream and related problems in the hystrix dashboard
挑选智能音箱时,首选“智能”还是“音质”?这篇文章给你答案
Vulnerability recurrence ----37. Apache unomi Remote Code Execution Vulnerability (cve-2020-13942)
In distributed scenarios, do you know how to generate unique IDs?
国内离线安装 Chrome 扩展程序的方法总结
「经验」我对用户增长的理解『新用户篇』
What if the apple watch fails to power on? Apple watch can not boot solution!
【云驻共创】Huawei iConnect使能物联终端一触即联
