import cv2 as cv import numpy as np # 读取图片,并转换为灰度图片 face_image = cv.imread('211.jpg') face_gray = cv.cvtColor(face_image, cv.COLOR_RGB2GRAY) cv.imshow('gray face', face_gray) # 检测人脸 XML_PATH = 'haarcascade_frontalface_default.xml' # 人脸检测分类模型 注:模型较老,侧脸几乎识别不出来,建议正脸尝试 face_detector = cv.CascadeClassifier(XML_PATH) # 实例化分类器 face_list = face_detector.detectMultiScale(face_gray) cv.imshow('2',face_image) print(face_list) # 在人脸上标框 for face in face_list: rect_image = cv.rectangle(face_image, face, (0, 30, 100), 2) cv.imshow('current image', rect_image) # 截取人脸 x, y, w, h = face_list[0] print(x,y,w,h) face_rect = face_image[y:y + h, x:x + w] # 获取人脸对应位置的数值 cv.imshow('current faces', face_rect) # 进行旋转 center_point = [np.float32(w>>1),np.float32(h>>1)] # 寻找中心点 mat = cv.getRotationMatrix2D(center_point, 30, 1) #30 强制旋转30°角,此处不太好 face_rotation = cv.warpAffine(face_rect, mat, (h, w)) cv.imshow('rotation face', face_rotation) if cv.waitKey(0) & 0xFF == 27: cv.destroyAllWindows()
'haarcascade_frontalface_default.xml' # 人脸检测分类模型