人脸识别python+opencv实现

#获取人脸
import time
import cv2
import os
import  random
# 保存人脸数据集的目录
dataset_dir = 'image'
# 创建目录(如果不存在)
if not os.path.exists(dataset_dir):
    os.makedirs(dataset_dir)

# 初始化人脸识别器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml')
face_recognizer = cv2.face.LBPHFaceRecognizer_create()

# 打开摄像头
video_capture = cv2.VideoCapture(0)

# 计数器
face_count = 0

while face_count<=0:
    # 读取摄像头的视频帧
    ret, frame = video_capture.read()
    # 将帧转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    # 对每个检测到的人脸进行操作
    for (x, y, w, h) in faces:
        face_roi = gray[y:y + h, x:x + w]

        # 绘制边框
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # time.sleep(600)

        # 保存人脸数据集
        face_file_name = f'face{random.randint(1, 10)}.jpg'
        face_file_path = os.path.join(dataset_dir, face_file_name)
        cv2.imwrite(face_file_path, face_roi)
        print(f'Saved {face_file_name}')

        # face_count += 1

    # 显示视频帧
    cv2.imshow('Face Capture', frame)

    # 按下 'q' 键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# 释放资源
video_capture.release()
cv2.destroyAllWindows()


 训练文件夹里的图片数据集:

import os
import numpy as np
import cv2
files=[]
def face_detect_demo(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    face_detector = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
    faces = face_detector.detectMultiScale(gray, 1.2, 6)
    if len(faces) == 0:
        return None, None
    (x, y, w, h) = faces[0]
    return gray[y:y + w, x:x + h], faces[0]
def ReFileName(dirPath):
    faces = []
    for file in os.listdir(dirPath):
        if os.path.isfile(os.path.join(dirPath, file)):
            c = os.path.basename(file)
            print(file)
            files.append(file)
            name = os.path.join(dirPath, file)
            img = cv2.imread(name)
            face, rect = face_detect_demo(img)
            if face is not None:
                faces.append(face)
    cv2.waitKey(1)
    cv2.destroyAllWindows()
    return faces
def retur():
    dirPath = r"image/"  # 文件路径
    label_dict = {}  # 标签字典
    for i, file in enumerate(os.listdir(dirPath)):
        if os.path.isfile(os.path.join(dirPath, file)):
            c = os.path.splitext(file)[0]
            print(file)
            name = os.path.join(dirPath, file)
            img = cv2.imread(name)
            face, rect = face_detect_demo(img)
            if face is not None:
                train_data = np.array([face])
                if c not in label_dict:
                    label_dict[c] = i
                train_label = np.array([label_dict[c]], dtype=np.int32)  # 使用标签字典将标签映射为整数编码
                recognizer = cv2.face.LBPHFaceRecognizer_create()  # 分类器
                recognizer.train(train_data, train_label)  # 训练数据
                recognizer.write(f'traineddata/{c}.yml')  # 保存训练数据集
retur()

根据训练数据识别人脸信息:

import cv2
# -*- coding: utf-8 -*-
# 加载训练好的人脸模型
import numpy as np
from PIL import ImageFont, ImageDraw

face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.read(r'traineddata\\Q.yml')
# 打开摄像头
video_capture = cv2.VideoCapture(0)
# 人脸检测器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml')
while True:
    ret, frame = video_capture.read()  # 读取视频帧
    # 转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 人脸检测8
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    # 对每个检测到的人脸进行识别
    for (x, y, w, h) in faces:
        face_roi = gray[y:y + h, x:x + w]
        # 使用训练好的模型进行人脸识别
        label, confidence = face_recognizer.predict(face_roi)
        # 如果识别结果置信度足够高,认为识别成功
        if confidence < 50:
            print("登录成功")
            cv2.putText(frame, "Login Successful", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2,
                        cv2.LINE_AA, False)
            # exit()
        else:

            # 设置字体

            # 在图像上绘制中文字符
            # cv2.putText(frame, '不认识', (x, y - 10), font_chinese, 0.9, (0, 0, 255), 2)

            cv2.putText(frame, u"Unknown", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
            # cv2.putText(frame, "不认识", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
    # 显示画面
    cv2.imshow('Face Recognition', frame)
    # 按下 'q' 键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break  # 释放资源
video_capture.release()
cv2.destroyAllWindows()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ALIM-MASTIK

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值