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()
  • 28
    点赞
  • 194
    收藏 更改收藏夹
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_four_two_six_

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值