【机器学习】OpenCV人脸识别

OpenCv 基础函数

# 读取图片
image = cv2.imread("test01.jpg")

# 转灰度
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 修改尺寸
resize_image = cv2.resize(image,(300,400))

# 绘制矩形
cv2.rectangle(image, (x , y),(x + width, y + height),(0,255,0),2)

# 显示图片
cv2.imshow("title",image)

# 关闭窗口
cv2.waitKey(0)
cv2.destroyAllWindows()

识别流程

依赖库

import cv2
import os
from PIL import Image
import numpy as np

录入脸部特征信息

# 选择分类器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# 使用默认摄像头,参数为0
video_capture = cv2.VideoCapture(0) 

# 输入人脸录入者的姓名
person_name = input("请输入人脸录入者的姓名: ")  

# 初始化样本计数器
sample_count = 0  

while True:
    # 读取帧数
    ret, frame = video_capture.read()
    # 转灰度
    gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 提取特征
    faces = face_cascade.detectMultiScale(gray_image, 1.1, 5)

    for (x, y, w, h) in faces:
        # 绘制矩形
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        # 将人脸样本保存到本地文件
        sample_count += 1
        # 提取人脸ROI
        face_roi = gray_image[y:y + h, x:x + w]  
        # 创建储存样本的文件夹
        person_fodler = f'./face_roi/{person_name}/'
        if not os.path.exists(person_fodler):
            os.mkdir(person_fodler)
            
        # 样本图片命名
        sample_path = person_fodler + f'{person_name}_{sample_count}.jpg'
        # 储存到文件夹
        cv2.imwrite(sample_path, face_roi)
        print(f"保存样本: {sample_path}")

    cv2.imshow("Video", frame)

    # 记录数据特征样本数量  10张测试
    if cv2.waitKey(1) & 0xFF == ord('q') or sample_count >= 10:
        break

video_capture.release()
cv2.destroyAllWindows()

分类器训练数据

# 提取样本的 人脸数据集和标签
def get_ImgaesLabels(path):
    facesSamplies = []       # 储存人脸数据
    ids = []                 # 储存标签数据
    imagesPath = [os.path.join(path,f) for f in os.listdir(path)] # 储存每个图片的相对路径
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')     # 加载人脸分类器
    
    # 遍历列表中的图片
    for Path in imagesPath:
        pil_image = Image.open(Path).convert('L')  # 转成灰度
        gray_np_image = np.array(pil_image)        # 灰度特征数组
        # 获取人脸特征
        faces = face_cascade.detectMultiScale(gray_np_image,1.1,5)
        id = int(Path.split('_')[-1].split('.')[0])  # 获取到每张图片的ID
        for x,y,w,h in faces:
            ids.append(id)  # 添加ID
            facesSamplies.append(gray_np_image[y:y+h,x:x+w]) # 添加ROI特征
    return facesSamplies,ids


person_fodler = './face_roi/Wh/'
# 加载人脸数据集和标签
faces, ids = get_ImgaesLabels(person_fodler)
# 创建LBPH人脸识别器
recognizer = cv2.face.LBPHFaceRecognizer_create()
# 训练人脸识别器
recognizer.train(faces, np.array(ids))
# 保存训练好的模型
recognizer.save("face_recognizer_model.yml")

识别人脸

# 加载已经训练好的LBPH人脸识别器模型
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("face_recognizer_model.yml")

# 加载人脸级联分类器(用于检测人脸)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

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

while True:
    # 读取每帧
    bool,frame = cap.read()

    # 灰度
    gray_image = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    # 通过分类器加载人脸的特征
    faces = face_cascade.detectMultiScale(gray_image,1.1,5)

    for (x,y,w,h) in faces:
        # 绘制人脸矩形框
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        
         # 根据识别器识别人脸 confidence为预测值(0~100)
        label, confidence = recognizer.predict(gray_image[y:y+h, x:x+w])

        # 获取识别结果并显示
        if confidence < 100:
            text = "WH"
        else:
            text = "Unknown"
            
		# 加入文本
        cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    # 显示结果帧
    cv2.imshow("Face Recognition", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()

完整流程

录入人脸特征(储存训练后的数据)

import cv2
import numpy as np


# 输入人脸信息
person_name = input("请输入姓名:")

# 加载人脸级联分类器(用于检测人脸)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

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

# 创建LBPH人脸识别器
recognizer = cv2.face.LBPHFaceRecognizer_create()

# 判断是否存在特征信息,有的话就加载特征
yml_name = f"face_{ person_name }_model.yml"
try:
    recognizer.read(yml_name)
except:
    pass

# 初始化人脸数据和标签
faces = []
lable_ids = []
count = 0

while True:
    count = count + 1
    # 读取摄像头帧
    ret, frame = cap.read()
    # 将彩色帧转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 检测人脸
    faces_rect = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,)

    for (x, y, w, h) in faces_rect:
        # 绘制人脸矩形框
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        # 将人脸数据和标签添加到列表中
        faces.append(gray[y:y+h, x:x+w])
        lable_ids.append(count)

    # 显示结果帧
    cv2.imshow("Face Capture", frame)

    # 按下'q'键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 训练人脸识别器
recognizer.train(faces, np.array(lable_ids))
print("yml_name",yml_name)
# 保存训练好的模型
recognizer.save(yml_name)

# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()

识别人脸

# 加载已经训练好的LBPH人脸识别器模型
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("face_xxxxx_model.yml")

# 加载人脸级联分类器(用于检测人脸)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

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

while True:
    
    bool,frame = cap.read()

    # 灰度
    gray_image = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    # 通过分类器加载人脸的特征
    faces = face_cascade.detectMultiScale(gray_image,1.1,5)

    for (x,y,w,h) in faces:
        # 绘制人脸矩形框
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        
         # 根据识别器识别人脸    confidence:预测结果的可信度(0~100)
        label, confidence = recognizer.predict(gray_image[y:y+h, x:x+w])
        print("预测值=> ",confidence)
        
        # 获取识别结果并显示
        if confidence < 100:
            text = "WH"
        else:
            text = "Unknown"
            
        # 写入文本
        cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    # 显示结果帧
    cv2.imshow("Face Recognition", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break



# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
posted @ 2023-12-18 10:34  PythonNew_Mr.Wang  Views(92)  Comments(0Edit  收藏  举报