OpenCV python 人脸识别(分类)

OpenCV python 人脸识别(分类)

人脸图片
在这里插入图片描述
在这里插入图片描述
资源图片:face.zip

import cv2
import numpy as np


def resize_img(path):
    """导入图片、调整图片尺寸至相同大小"""

    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (250, 350))

    return img


def main():

    # 1.导入人脸训练图片
    img_list = [resize_img("./face/a0.jpg"),
                resize_img("./face/a1.jpg"),
                resize_img("./face/a2.jpg"),
                resize_img("./face/a3.jpg"),
                resize_img("./face/b0.jpg"),
                resize_img("./face/b1.jpg"),
                resize_img("./face/b2.jpg"),
                resize_img("./face/b3.jpg")]

    # 2.设置图片标签类型
    labels = [0, 0, 0, 0, 1, 1, 1, 1]

    # 3.创建识别对象
    # recognizer = cv2.face.EigenFaceRecognizer_create()
    # recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer = cv2.face.FisherFaceRecognizer_create()

    # 4.训练图片
    recognizer.train(img_list, np.array(labels))

    # 5.导入预测图片并预测
    predict_image = resize_img("./face/b4.jpg")
    label, confidence = recognizer.predict(predict_image)

    # 6.显示预测结果
    print("预测类型:", label)
    print("置信度:", confidence)


if __name__ == '__main__':
    main()

结果:
在这里插入图片描述

人脸识别 方法二

文件下载地址
链接: https://pan.baidu.com/s/1zgBEWllFIxrgazOIcl0csQ 提取码: 4cuc

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import numpy as np
import cv2 as cv
import sklearn.preprocessing as sp

# 哈尔级联分类器 人脸
fd = cv.CascadeClassifier('./haar/face.xml')


# 文件夹搜索图片
def search_faces(directory):
    directory = os.path.normpath(directory)

    faces = {}
    for curdir, subdirs, files in os.walk(directory):
        for jpeg in (file for file in files if file.endswith('.jpg')):
            path = os.path.join(curdir, jpeg)
            label = path.split(os.path.sep)[-2]
            if label not in faces:
                faces[label] = []
            faces[label].append(path)
    return faces


# 读取 训练集人脸 路径
train_faces = search_faces('./faces/training')

# 人名标签编码
codec = sp.LabelEncoder()
codec.fit(list(train_faces.keys()))

# 训练集 人脸检测并截取人脸
train_x, train_y = [], []
for label, filenames in train_faces.items():
    for filename in filenames:
        image = cv.imread(filename)
        gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        faces = fd.detectMultiScale(gray, 1.1, 2, minSize=(100, 100))
        for l, t, w, h in faces:
            train_x.append(gray[t:t + h, l:l + w])
            train_y.append(codec.transform([label])[0])
train_y = np.array(train_y)

# 创建模型 局部二值模式直方图人脸识别分类器
model = cv.face.LBPHFaceRecognizer_create()
model.train(train_x, train_y)

# 测试集 读取整理
test_faces = search_faces('./faces/testing')
test_x, test_y, test_z = [], [], []
for label, filenames in test_faces.items():
    for filename in filenames:
        image = cv.imread(filename)
        gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        faces = fd.detectMultiScale(gray, 1.1, 2, minSize=(100, 100))
        for l, t, w, h in faces:
            test_x.append(gray[t:t + h, l:l + w])
            test_y.append(codec.transform([label])[0])

            a, b = int(w / 2), int(h / 2)
            cv.ellipse(image, (l + a, t + b), (a, b), 0, 0, 360, (255, 0, 255), 2)
            test_z.append(image)

test_y = np.array(test_y)

# 测试集预测
pred_test_y = []
for face in test_x:
    pred_code = model.predict(face)[0]
    pred_test_y.append(pred_code)

# 循环显示 预测结果对比
escape = False
while not escape:
    for code, pred_code, image in zip(
            test_y, pred_test_y, test_z):
        label, pred_label = \
            codec.inverse_transform([code, pred_code])
        text = 'Label:{} {} {}(Predict)'.format(label,
                                 '==' if code == pred_code else '!=',
                                 pred_label)
        cv.putText(image, text, (10, 60), cv.FONT_HERSHEY_SIMPLEX, 2,
                   (255, 255, 255), 6)
        cv.imshow('Recognizing...', image)
        if cv.waitKey(1000) == 27:
            escape = True
            cv.imwrite("faces.jpg", image)
            break

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

廷益--飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值