人脸识别算法之Fisherface_python实现

有关Fisherface的人脸识别代码网上实现较少,因此,分享一下自己的代码实现

1.从摄像头获取照片

# -*- coding: utf-8 -*-
"""
Created on Wed May  6 11:00:25 2020

@author: Leonardragon
"""

import cv2
# 调用笔记本内置摄像头,所以参数为0,如果有其他的摄像头可以调整参数为1,2
cap = cv2.VideoCapture(0)

face_detector = cv2.CascadeClassifier('F:\\Useful App\opencv-2.4.9\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
face_id = input('\n enter user id:')

print('\n Initializing face capture. Look at the camera and wait ...')
count = 0
while True:

    # 从摄像头读取图片
    sucess, img = cap.read()

    # 转为灰度图片
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_detector.detectMultiScale( gray, 1.3 , 5 )
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0))
        count += 1     
        h = cv2.resize(img[y:y+h,x:x+w],(150,150))        
        # 保存图像
        cv2.imwrite("C:\\Users\\Administrator\\Desktop\\Facedata\\User." + str(face_id) + '.' + str(count) + '.jpg', h)
        
        cv2.imshow('image', img)
    # 保持画面的持续。
    k = cv2.waitKey(1)

    if k == 27:   # 通过esc键退出摄像
        break
    elif count >= 50:  # 得到30个样本后退出摄像
        break
# 关闭摄像头
cap.release()
cv2.destroyAllWindows()

 

2.图像训练

# -*- coding: utf-8 -*-
"""
Created on Mon May  4 17:22:46 2020

@author: Leonardragon
"""
import numpy as np
from PIL import Image
import os
import cv2

# 人脸数据路径
#path = 'C:\\Users\\Administrator\\.spyder-py3\Spyder_Python\OpenCV\FaceRecognition\Facedata_6'

path = 'C:\\Users\\Administrator\\Desktop\\u'
recognizer = cv2.face.FisherFaceRecognizer_create()       # 图像归一化

# detector = cv2.CascadeClassifier("F:\\Useful App\opencv-2.4.9\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml")

def getImagesAndLabels(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]  # join函数的作用?
    faceSamples = []
    ids = []   
    for imagePath in imagePaths:  
        
        PIL_img = Image.open(imagePath).convert('L')    # convert it to grayscale
        img_numpy = np.array(PIL_img, 'uint8')
        
        x = os.path.split(imagePath)[-1]
        y = os.path.split(imagePath)[-1].split(".")[1] 
        
        id = int(  os.path.split(imagePath)[-1].split(".")[1]  )
        ids.append(id)
        
        """
        faces = detector.detectMultiScale(img_numpy)
        for (x, y, w, h) in faces:
            faceSamples.append(img_numpy[y:y + h, x: x + w])
            ids.append(id)
        """        
    # return faceSamples, ids
    return ids
images=[]

for i in range(1,51):
    images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.0"+'.'+ str(i) +'.jpg' ,cv2.IMREAD_GRAYSCALE))

images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.1.1.bmp",cv2.IMREAD_GRAYSCALE))

images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.2.1.bmp",cv2.IMREAD_GRAYSCALE))
images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.2.2.bmp",cv2.IMREAD_GRAYSCALE))
images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.2.3.bmp",cv2.IMREAD_GRAYSCALE))
images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.2.4.bmp",cv2.IMREAD_GRAYSCALE))
images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.2.5.bmp",cv2.IMREAD_GRAYSCALE))

images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.3.1.bmp",cv2.IMREAD_GRAYSCALE))
#images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.4.1.jpg",cv2.IMREAD_GRAYSCALE))

for i in range(1,11):
    images.append(cv2.imread("C:\\Users\\Administrator\\Desktop\\u\\User.4"+'.'+ str(i) +'.jpg' ,cv2.IMREAD_GRAYSCALE))
print('Training faces. It will take a few seconds. Wait ...')

# faces, ids = getImagesAndLabels(path)
ids = getImagesAndLabels(path)

#recognizer.train(faces, np.array(ids))
recognizer.train(images, np.array(ids))
recognizer.write(r'face_trainer\trainer.yml')

#recognizer.write("C:\\Users\\Administrator\\.spyder-py3\\Spyder_Python\\OpenCV\\FaceRecognition\\face_trainer")
print("{0} faces trained. Exiting Program".format(len(np.unique(ids))))

3.人脸识别

# -*- coding: utf-8 -*-
"""
Created on Mon May  4 18:03:00 2020

@author: Leonardragon
"""
import cv2
recognizer  = cv2.face.FisherFaceRecognizer_create() 
recognizer.read("C:\\Users\\Administrator\\Desktop\\face_trainer\\trainer.yml")
cascadePath = "F:\\Useful App\\opencv-2.4.9\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)

font = cv2.FONT_HERSHEY_SIMPLEX
idnum = 0
names = [ 'LiMike','Mike','Cindy','Lucy','yaohuiqin']  
cam = cv2.VideoCapture(0)

cam.set(3,500)    #宽
cam.set(4,500)   #高

minW = cam.get(3)
minH = cam.get(4)

minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)

while True:
    
    ret, img = cam.read()     # 从摄像头读取图片    
    
    # 转为灰度图片
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(int(minW), int(minH)),      
        #minSize = (int(100),int(100)),
    )   
    # predict_image=cv2.imread("C:\\Users\\Administrator\\Desktop\\U\\User.0.10.jpg",cv2.IMREAD_GRAYSCALE)    
    for (x, y, w, h) in faces:              
        #if w >= 150 & h >= 150 :      
            u = cv2.rectangle( img,  (x, y), (x+w, y+h), (0, 255, 0), 2 )   #酸橙色                
            g=gray [y:y+ h, x:x+ w]                              
            out = cv2.resize(g, (150,150))                              
            idnum, confidence = recognizer.predict(out)
            
            # idnum, confidence = recognizer.predict(gray[y:y+h,x:x+w])
            # idnum, confidence = recognizer.predict(predict_image)
            
            if confidence < 3000 :         
                print(confidence,names[idnum])                
                confidence = ((100-0)/(4000-100))*(confidence - 0) + 0   # 投影至【0,100】区间
               
                print(confidence)
                
                #if confidence < 100:
                idnum = names[idnum]
                confidence = "{0}%".format(round(100 - confidence))
            else:
                print(confidence,"unknow")
                idnum = "unknown"
                confidence = "{0}%".format(round(100 - confidence))
    
            cv2.putText(img, str(idnum), (x+5, y-5), font, 1, (0, 0, 255), 1)
            cv2.putText(img, str(confidence), (x+5, y+h-5), font, 1, (0, 0, 0), 1)                    
    cv2.imshow('camera', img)
    k = cv2.waitKey(10)
    if k == 27:
        break
cam.release()
cv2.destroyAllWindows()

4.识别效果

                                             人脸识别算法之Fisherface_python实现_第1张图片

你可能感兴趣的:(人脸识别算法之Fisherface_python实现)