首先安装opencv库 windows R 输入cmd 输入:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
利用opencv库进行人脸识别-存储
注意把分类器模型 haarcascade_frontalface_alt2.xml 和代码文件放在同一目录之下
从opencv库的文件目录之下找到,同时在相同目录之下创建文件夹命名training_data_me
之后运行代码
import cv2
def getTrainingData(window_name, camera_id, path_name, max_num): # path_name是图片存储目录,max_num是需要捕捉的图片数量
cv2.namedWindow(window_name) # 创建窗口
cap = cv2.VideoCapture(camera_id) # 打开摄像头
classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # 加载分类器
color = (0, 255, 0) # 人脸矩形框的颜色
num = 0
while cap.isOpened():
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 灰度化
faceRects = classifier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
if len(faceRects) > 0:
for faceRect in faceRects:
x, y, w, h = faceRect
# 捕捉到的图片的名字,这里用到了格式化字符串的输出
image_name = '%s%d.jpg' % (path_name,num) # 注意这里图片名一定要加上扩展名,否则后面imwrite的时候会报错:could not find a writer for the specified extension in function cv::imwrite_ 参考:https://stackoverflow.com/questions/9868963/cvimwrite-could-not-find-a-writer-for-the-specified-extension
image = frame[y:y + h, x:x + w] # 将当前帧含人脸部分保存为图片,注意这里存的还是彩色图片,前面检测时灰度化是为了降低计算量;这里访问的是从y位开始到y+h-1位
cv2.imwrite(image_name, image)
num += 1
# 超过指定最大保存数量则退出循环
if num > max_num:
break
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) # 画出矩形框
font = cv2.FONT_HERSHEY_SIMPLEX # 获取内置字体
cv2.putText(frame, ('%d' % num), (x + 30, y + 30), font, 1, (255, 0, 255),
4) # 调用函数,对人脸坐标位置,添加一个(x+30,y+30)的矩形框用于显示当前捕捉到了多少人脸图片
if num > max_num:
break
cv2.imshow(window_name, frame)
c = cv2.waitKey(10)
if c & 0xFF == ord('q'):
break
cap.release() # 释放摄像头并销毁所有窗口
cv2.destroyAllWindows()
print('Finished.')
# 主函数
if __name__ == '__main__':
print('catching your face and writting into disk...')
getTrainingData('getTrainData', 0, 'training_data_me/', 100) # 注意这里的training_data_xx 文件夹就在程序工作目录下
from deepface import DeepFace
verification = DeepFace.verify(img1_path = "/training_data_me/0.jpg", img2_path = "/training_data_me/2.jpg")
print(verification)
过程图:
保存结果:
之后通过下载deepface库
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple deepface
模型都挺大的,识别一个人脸属性(年龄,标签,性别,种族)
from deepface import DeepFace
analysis = DeepFace.analyze(img_path="C:/Users/Tinkpad/Desktop/training_data_me/1.jpg", actions=["age", "gender", "emotion", "race"])
print(analysis)
直接识别刚刚文件夹中的图片
识别结束
识别结果:{'age': 32, 'region': {'x': 12, 'y': 13, 'w': 212, 'h': 212}, 'gender': 'Man', 'emotion': {'angry': 2.699081413447857, 'disgust': 3.29873905968725e-06, 'fear': 3.79166342318058, 'happy': 0.0011297983292024583, 'sad': 49.782344698905945, 'surprise': 0.01582831027917564, 'neutral': 43.7099426984787}, 'dominant_emotion': 'sad', 'race': {'asian': 81.11991173743675, 'indian': 1.5053462203053367, 'black': 0.35795348036011937, 'white': 1.921237374617897, 'middle eastern': 0.12854522394658469, 'latino hispanic': 14.967007337034186}, 'dominant_race': 'asian'}