Dlib实现人脸检测,并剪切人脸照
一、Dlib的安装:
如果你的Python版本也是3.6,那么安装dlib要简单很多,直接
pip install dlib==19.7.0
如果上面安装失败,就用博主附带的.whl文件进行安装吧。(如果你的Python版本不是3.6,又或者你想安装dlib其他的版本,博主就懒得写了,大家自己百度,但是你可以在这里找到合适的版本和方法。)
–-----------------------------------------------------------------------------—--------------------------------------------
–-----------------------------------------------------------------------------—--------------------------------------------
二、用Dlib检测人脸,并做标记点
提示:31、34行的第一个数字参数是调节圆圈、数字大小的
重要:第10行,是需要下载这个文件的,我源代码里面有,下载我的源代码就行啦。
# -*- coding:utf-8 -*-
# -*- author:zzZ_CMing CSDN address:https://blog.csdn.net/zzZ_CMing
# -*- 2019/01/13; 16:12
# -*- python3.6
import cv2
import dlib
import numpy as nppredictor_model = 'shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_model)# cv2读取图像
test_film_path = "iuput_pic/0.jpg"
img = cv2.imread(test_film_path)
# 取灰度
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()])#print(landmarks, type(landmarks))for idx, point in enumerate(landmarks):# 68点的坐标pos = (point[0, 0], point[0, 1])print(idx+1, pos)# 利用cv2.circle给每个特征点画一个圈,共68个cv2.circle(img, pos, 3, color=(0, 255, 0))# 利用cv2.putText输出1-68font = cv2.FONT_HERSHEY_SIMPLEXcv2.putText(img, str(idx+1), pos, font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)cv2.imwrite("result.png", img)
cv2.imshow("img", img)
cv2.waitKey(0)
效果展示图:

–-----------------------------------------------------------------------------—--------------------------------------------
–-----------------------------------------------------------------------------—--------------------------------------------
三、用Dlib剪切出人脸照
有了上面的基础,想切出大头照的方法就很简单了,因为68个标记点坐标是存储在一个字典dict中,我们只需要比较68个坐标点的大小,确定其上、下、左、右四个最值就可以确定人脸的位置了。
比较坐标点,确定四个最值的函数如下:
def get_face_points(dict_A):""":param dict_A: 传入一个字典A,内容是包含一张人脸的所有标记点坐标:return: 返回人脸上、下、左、右的索引值"""x_max = y_max = 0x_min = y_min = 2000for k_1, v_1 in dict_A.items():for k_2, v_2 in v_1.items():if k_2 == "x":if int(v_2) < x_min:x_min = int(v_2)if int(v_2) > x_max:x_max = int(v_2)else:if int(v_2) < y_min:y_min = int(v_2)if int(v_2) > y_max:y_max = int(v_2)return x_min, x_max, y_min, y_max
完整代码在这里下载,效果图如下:


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
