最近在做人像识别的工作,需要根据人像照片的清晰度、人脸正拍还是侧拍、正立还是倒立(以及顺逆时针旋转90度)进行分类。
问题相关代码
import cv2
import numpy as np
读取文件
image = 'E:\leidian\353.jpg'
#net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000_fp16.caffemodel') # Caffe模型
net = cv2.dnn.readNetFromTensorflow('E:\leidian\opencv_face_detector_uint8.pb', 'E:\leidian\opencv_face_detector.pbtxt') # TensorFlow模型
image = cv2.imread(image) # 读取图片
height, width, channel = image.shape # 高、宽、通道数
人脸检测
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # 调整大小并降低光照的影响
net.setInput(blob) # 设置输入
detections = net.forward() # 检测结果
faces = detections[0, 0] # 人脸结果
for face in faces:
confidence = face[2] # 置信度
if confidence > 0.5: # 置信度阈值设为0.5
box = face[3:7] * np.array([width, height, width, height]) # 人脸矩形框坐标
pt1 = int(box[0]), int(box[1]) # 左上角坐标
pt2 = int(box[2]), int(box[3]) # 右下角坐标
cv2.rectangle(image, pt1, pt2, (0, 255, 0), thickness=2) # 画出人脸矩形框
text = '{:.2f}%'.format(confidence * 100) # 置信度文本
startX, startY = pt1
y = startY - 10 if startY - 10 > 10 else startY + 10
org = (startX, y) # 文本的左下角坐标
cv2.putText(image, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), thickness=2) # 画出置信度
显示和保存图片
cv2.imshow('result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
识别人脸倒正。如果可以从更多维度对人像照片进行分类,欢迎大家提意见。