电脑基础 · 2023年3月20日

Python人脸识别

Python人脸识别

#头文件:

import cv2 as cv

import numpy as np

import os

from PIL import Image

import xlsxwriter

import psutil

import time

#人脸录入

def get_image_name(name):

name_map = {f.split('.')[1]:int(f.split('.')[0]) for f in os.listdir("./picture")}

if not name_map:

name_number = 1

elif name in name_map:

name_number = name_map[name]

else:

name_number = max(name_map.values()) + 1

return './picture/' + str(name_number) + "." + name + '.jpg'

def save_face(faces,img,name):

if len(faces) == 0:

print("没有检测到人脸,请调整")

return

if len(faces) >1:

print("检测到多个人脸")

return

x,y,w,h = faces[0]

cv.imwrite(get_image_name(name),img[y:y+h,x:x+w])

print("录上了")

def img_extract_faces(img):

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

face_classifier = cv.CascadeClassifier('./haarcascade_frontalface_alt2.xml')

return face_classifier.detectMultiScale(gray, 1.1, 5), gray

def main():

cap = cv.VideoCapture(0)

if not cap.isOpened():

print('连接失败')

name = input("what is your name? ")

while True:

ret, frame = cap.read()

if not ret:

print("读帧失败")

break

#检测并提取人脸信息

faces, gray = img_extract_faces(frame)

for x, y, w, h in faces:

cv.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), thickness=2)

cv.imshow("还好我拼命护住了脸,英俊的相貌才得以保存", frame)

k = cv.waitKey(1)

if k == ord('s'):

save_face(faces, gray, name)

elif k == ord('q'):

break

cap.release()

cv.destroyAllWindows()

main()

#训练数据

faces_list = []

labels = []

def main():

for f in os.listdir('./picture'):

img = cv.imread(os.path.join('./picture',f), 0)

face_classifier = cv.CascadeClassifier(r'E:\Users\liufugui\PycharmProjects\pythonProject4\venv\Lib\site-packages\cv2\data\haarcascade_frontalface_alt2.xml')

faces = face_classifier.detectMultiScale(img)

if len(faces) == 0:

continue

x, y, w, h = faces[0]

faces_list.append(img[y:y+h, x:x+w])

labels.append(int(f.split('.')[0]))

recognizer = cv.face.LBPHFaceRecognizer_create()

recognizer.train(faces_list, np.array(labels))

recognizer.write('train.yml')

main()

#人脸识别

def main():

cap = cv.VideoCapture(0)

if not cap.isOpened():

print('连接失败')

name_map = {int(f.split('.')[0]) : f.split('.')[1] for f in os.listdir("./picture")}

while True:

ret, frame = cap.read()

if not ret:

print("读帧失败")

break

gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

recognizer = cv.face.LBPHFaceRecognizer_create()

recognizer.read('train.yml')

face_classifier = cv.CascadeClassifier('./haarcascade_frontalface_alt2.xml')

faces = face_classifier.detectMultiScale(gray)

for (x, y, w, h) in faces:

img_id, confidence = recognizer.predict(gray[y:y + h, x:x + w])

if confidence > 75:

name = '未识别'

else:

name = name_map[img_id]

cv.putText(

img=frame, org=(x, y), text=name,

fontFace=cv.FONT_HERSHEY_SIMPLEX, fontScale=0.75, color=(0, 255, 0), thickness=1

)

cv.circle(

img=frame, center=(x + w // 2, y + h // 2), radius=w//2,

color=(255, 0, 0), thickness=1

)

cv.imshow("还好我拼命护住了脸,英俊的相貌才得以保存", frame)

if cv.waitKey(1) == ord('q'):

break

cap.release()

cv.destroyAllWindows()

main()