python opencv3 人脸识别的例子


一个人脸识别的例子

程序中用到了公共数据集, 欢迎去我的git上下载源码,源码里带有数据集

git:https://github.com/linyi0604/Computer-Vision

 

脚本中一个三个函数

第一个: 调用本机摄像头采集一些自己的照片 作为数据集的一部分

第二个:把自己的照片 和公共数据集照片一并读取 作为输入数据

第三个: 预测函数  调用第二个函数拿到x 和y 进行训练后 开启摄像头 进行预测

 

 1 # coding:utf-8
 2 
 3 import cv2  4 import os  5 import numpy as np  6 
 7 
 8 # 1 生成人脸识别数据
 9 # 图像是灰度格式,后缀名.pgm
 10 # 图像是正方形 图像大小要一样 在这里使用200*200
 11 def generate():  12     # 加载检测图像中人脸位置的对象, xml文件需要去opencv文件夹里面找, 放到项目里面来引入
 13     face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml")  14     # 调用本机摄像头
 15     camera = cv2.VideoCapture(0)  16     count = 0  17     # 读取摄像头
 18     while True:  19         # 读入 帧
 20         ret, frame = camera.read()  21         # 变为灰度图像
 22         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  23         # 检测人脸位置
 24         faces = face_cascade.detectMultiScale(gray, 1.3, 5)  25         # 将图片中人脸位置单独拿出来改变成200*200大小的图片 存入本地 作为数据集
 26         for (x, y, w, h) in faces:  27             img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)  28             f = cv2.resize(gray[y:y+h, x:x+w], (200, 200))  29             cv2.imwrite("./data/%s.pgm" % str(count), f)  30             count += 1
 31 
 32         cv2.imshow("camera", frame)  33         # 如果按键q就退出 否则等50毫秒
 34         if cv2.waitKey(50) & 0xff == ord("q"):  35             break
 36 
 37  camera.release()  38  cv2.destroyAllWindows()  39 
 40 
 41 # 读取生成好的数据 在我项目目录下整理好的
 42 def readImages():  43     x, y = [], []  44     path = "./data/faces/"
 45     image_file = os.listdir(path)  46     image_files = [path + i for i in image_file]  47     for file in image_files:  48         images = os.listdir(file)  49         label = file.split("/")[-1][1:]  50         for i in images:  51             img = cv2.imread(file + "/" + i, cv2.IMREAD_GRAYSCALE)  52             img = cv2.resize(img, (200, 200))  53             x.append(np.asarray(img, dtype=np.uint8))  54  y.append(int(label))  55 
 56     y = np.asarray(y, dtype=np.int32)  57     return x, y  58 
 59 
 60 # 检测人脸
 61 def face_rec():  62     # 获取数据
 63     x, y = readImages()  64 
 65     # 人脸识别的模型
 66     model = cv2.face.EigenFaceRecognizer_create()  67     # fisherfaces算法的模型
 68     # model = cv2.face.FisherFaceRecognizer_create()
 69     # LBPH算法的模型
 70     # model = cv2.face.LBPHFaceRecognizer_create()
 71     """
 72  Eigenfaces和Fisherfaces 预测时候产生0到20000的评分  73  低于4000 5000 的评分都是相当可靠的  74  LBPH 产生评分不同,低于50是可靠的 高于80是不可靠的  75     """
 76 
 77     # 训练模型
 78  model.train(np.asarray(x), np.asarray(y))  79 
 80     # 开摄像头
 81     camera = cv2.VideoCapture(0)  82     # 加载检测人脸对象
 83     face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml")  84     while True:  85         # 读取当前帧
 86         read, img = camera.read()  87         # 当前帧下检测人脸
 88         faces = face_cascade.detectMultiScale(img, 1.3, 5)  89         for (x, y, w, h) in faces:  90             # 画出人脸
 91             img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)  92             # 转成灰度图
 93             gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  94             # 拿出人脸部分
 95             roi = gray[x: x+w, y: y+h]  96             try:  97                 # 更改大小
 98                 roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)  99                 # 进行预测
100                 params = model.predict(roi) 101                 # 在图像上写预测结果
102                 # 1.2是字体大小 2是粗细
103                 img = cv2.putText(img, str(params[0]), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2) 104                 # prams是一个二元素列表, 第一个元素是预测结果,第二个元素是得分情况
105                 print(params) 106 
107             except Exception as e: 108                 print(e) 109         cv2.imshow("detect face", img) 110         if cv2.waitKey(5) & 0xff == ord("q"): 111             break
112 
113  cv2.destroyAllWindows() 114 
115 
116 if __name__ == '__main__': 117     # 调用摄像头 采集人脸照片数据
118     # generate()
119 
120     # 检测人脸
121     face_rec()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM