废话不多说,直接上代码
# coding:utf-8
#安装cv2 的全名为:opencv-python
import cv2 as cv
import numpy as np
#安装dlib 需要先安装cmake包,否则可能造成报错
import dlib
from imutils import face_utils
#datapath:人脸数据文件位置路径
#inpath:人脸图片输入路径
#outpath:纠正后输出路径
#示例:BeautifulFunction(r'D:\dk\shape_predictor_68_face_landmarks.dat',r'D:\dk\1.jpg' , r'D:\dk\1.jpg')
def BeautifulFunction(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 = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
#如果存在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)
#记录旋转了几次
result += 1
return False
except Exception as e:
return False
记录一下,方便以后查找,如果觉得OK,麻烦点个赞呗!谢谢啦。
也可以直接使用我完成的软件来进行转换
软件连接:https://download.csdn.net/download/DK18397606232/12947183
如何使用请看软件的简介