python 人脸识别(通过摄像头)
1、人脸检测
# 打开摄像头,监测人脸 import cv2 as cv def face_detect(frame): # 图片转灰度 img_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # 加载人脸分类识别器 face_detector = cv.CascadeClassifier(r'../haarcascade/haarcascade_frontalface_default.xml') faces = face_detector.detectMultiScale(img_gray) for x, y, w, h in faces: cv.rectangle(frame, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1) cv.imshow("detecting", frame) if __name__ == '__main__': # 读取摄像头中的图像,获取图像grabbed为true cap = cv.VideoCapture(0) while True: grabbed, img = cap.read() if grabbed: print("frame:", img.shape) else: break face_detect(img) if ord('q') == cv.waitKey(10): break cv.destroyAllWindows() cap.release()
2、人脸采集
# 通过摄像头识别人脸,采集人脸图片保存到face_data目录 import cv2 as cv def face_collect(face_id, username): print('\n 正在初始化脸部识别,请保持在摄像头前面 ...') count = 0 filename = "" # 读取内置摄像头中的图像,获取图像grabbed为true cap = cv.VideoCapture(0) # 加载人脸分类识别器 face_detector = cv.CascadeClassifier(r'../haarcascade/haarcascade_frontalface_default.xml') while True: grabbed, img = cap.read() if grabbed: print("frame:", img.shape) else: break # 图片转灰度 img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) faces = face_detector.detectMultiScale(img_gray) for x, y, w, h in faces: cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1) count += 1 # 保存图像 filename = r"../face_data/" + username + "." + str(face_id) + '.' + str(count) + '.jpg' print(filename) cv.imwrite(filename, img_gray[y: y + h, x: x + w]) cv.imshow("detecting", img) if ord('q') == cv.waitKey(10): break elif count > 100: break cv.destroyAllWindows() cap.release() if __name__ == '__main__': user_id = input('\n 输入用户ID:') user_name = input('\n 输入用户英文名:') face_collect(user_id, user_name)
3、人脸训练
# 人脸训练 import numpy as np from PIL import Image import os import cv2 as cv def face_training(): print("人脸训练,请耐心等待 ...") # 人脸图片路径 face_path = '../face_data/' # opencv-contrib-python包中的函数 recognizer = cv.face.LBPHFaceRecognizer_create() # 载入人脸分类器 face_detector = cv.CascadeClassifier(r"../haarcascade/haarcascade_frontalface_default.xml") image_paths = [os.path.join(face_path, f) for f in os.listdir(face_path)] face_samples = [] ids = [] for imagePath in image_paths: img_gray = Image.open(imagePath).convert('L') img_numpy = np.array(img_gray, 'uint8') # 图片的命名方式 xx.id.num.ext(xx为任意英文标识,id是标签,同类人脸id相同,num一般为该类图片的计数,ext为图片后缀) # 文件名中关键就是id,作为有监督学习,id就是用于分类 user_id = int(os.path.split(imagePath)[-1].split(".")[1]) print(user_id, " ", imagePath) faces = face_detector.detectMultiScale(img_numpy) for x, y, w, h in faces: face_samples.append(img_numpy[y:y + h, x:x + w]) ids.append(user_id) recognizer.train(face_samples, np.array(ids)) # 保存训练信息 recognizer.write('../face_trainer/trainer.yml') print("{0} faces trained. Exiting Program".format(len(np.unique(ids)))) if __name__ == '__main__': face_training()
4、人脸识别
# 从视频中识别人脸 import cv2 as cv def face_recognition(): recognizer = cv.face.LBPHFaceRecognizer_create() # 读取训练数据 recognizer.read('../face_trainer/trainer.yml') face_detector = cv.CascadeClassifier(r"../haarcascade/haarcascade_frontalface_default.xml") font = cv.FONT_HERSHEY_SIMPLEX feature_id = None # 以训练的时候,按人脸id进行排序 names = ['xudemin', 'wanghaojin', 'heyinsong', 'linanan'] cap = cv.VideoCapture(0) # minW = 0.1*cap.get(3) # minH = 0.1*cap.get(4) while True: grabbed, img = cap.read() if grabbed: print("frame:", img.shape) else: break # 图片转灰度 img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) faces = face_detector.detectMultiScale(img_gray) for x, y, w, h in faces: cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1) # 预测 feature_id, confidence = recognizer.predict(img_gray[y:y + h, x:x + w]) print(feature_id, " ", confidence) if confidence < 100: feature_id = names[feature_id] confidence = "{0}%".format(round(100 - confidence)) else: feature_id = "unknown" confidence = "{0}%".format(round(100 - confidence)) cv.putText(img, str(feature_id), (x + 5, y - 5), font, 1, (0, 0, 255), 1) cv.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (0, 255, 0), 1) cv.imshow("recognizing", img) if ord('q') == cv.waitKey(10): break cv.destroyAllWindows() cap.release() if __name__ == '__main__': face_recognition()