实现效果:
本程序可以将下图第二张照片进行人脸识别,发现相片是否是正向,如果不是就进行相片转正形成下图第一张图。
代码
安装配置
模型下载
首先在我的这篇文件下载相应的人脸识别模型,一般 64标记点就够用,当然你也可以换成68位
人脸识别模型 shape_predictor_68_face_landmarks.dat 和81位下载_shape_predictor_68_face_landmarks.dat下载-CSDN博客
依赖下载
需要pip install 安装下面依赖
opencv-python
opencv-contrib-python
numpy
cmake
boost
imutils
dlib
问题解决
安装dlib这个可能遇到问题
python安装dlib报ERROR: Failed building wheel for dlib-CSDN博客
源码
# 安装cv2 安装的全名为:opencv-python同时还要按个指示包:opencv-contrib-python
import cv2 as cv
# 安装numpy,numPy 是 Python 科学计算的基础包。NumPy 包的核心是 ndarray 对象,他封装了同构数据类型的 n 维数组。
import numpy as np
# 安装dlib 需要先安装cmake包,否则可能造成报错
import dlib
# 安装imutils from和import意思是导入imutils包,但是在这个同级py文件中没有无需要的函数,我需要到对应下级py文件中的face_utils这个功能块或函数
from imutils import face_utils
class PhotoCorrect:
# datapath:人脸数据文件位置路径,人脸识别的68个特征点检测库dat文件
# inpath:人脸图片输入路径
# outpath:纠正后输出路径
def photoCorrect(datapath, inpath, outpath):
try:
# opencv读取图片
image = cv.imread(inpath)
# 读取的图片先存一张原图,用于原图旋转
FirstImage = image
result = 0
for i in range(4):
# 加载人脸数据
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(datapath)
# 图片转灰(用于提高人脸识别度)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# 获取特征集合
rects = detector(gray, 1)
for (i, rect) in enumerate(rects):
# 如果存在shape说明人脸已经识别出来了
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
# 然后根据result就知道需要旋转几次
# 然后再使用opencv旋转保存之前的备份图片即可,这样就不会更改原有的图片
for (x, y) in shape:
if result == 0:
cv.imwrite(outpath, FirstImage, [int(cv.IMWRITE_JPEG_QUALITY), 70])
elif result == 1:
cv.imwrite(outpath, np.rot90(FirstImage), [int(cv.IMWRITE_JPEG_QUALITY), 70])
elif result == 2:
cv.imwrite(outpath, np.rot90(np.rot90(FirstImage)), [int(cv.IMWRITE_JPEG_QUALITY), 70])
elif result == 3:
cv.imwrite(outpath, np.rot90(np.rot90(np.rot90(FirstImage))),
[int(cv.IMWRITE_JPEG_QUALITY), 70])
return True
# 如果不具备相应特征,旋转图片90°
image = np.rot90(image)
# 记录旋转次数加1
result += 1
# 进程结束,退出代码
return False
except Exception as e:
print(e)
return False
if __name__ == '__main__':
PhotoCorrect.photoCorrect(r'F:\exercise\py\AI\dat\shape_predictor_68_face_landmarks.dat', r'F:\testResource\Test\photo\testPhoto1.jpg',
r'F:\testResource\Test\photo\right1.jpg')
调用主方法,这个有点慢 莫要着急
------------------------------------------与正文内容无关------------------------------------
如果觉的文章写对各位读者老爷们有帮助的话,麻烦点赞加关注呗!小弟在这拜谢了!
如果您觉得我的文章在某些地方写的不尽人意或者写的不对,从而让你对你人生观产生颠覆(概不负责),需要斧正,麻烦在评论区不吝赐教,作者看到后会根据您的提示查阅文章进行修改,还这世间一个公理一片蓝天