Python+OpenCV simply implements multiple face detection and face recognition 2 (with code)

If the third-party package installation of dilb and face_recognition fails, please move to Python to solve the failure of installing the third-party package of dilb and face_recognition - Programmer Sought

In the previous article, please move to Python+dilb to realize simple face detection (with code) - Programmer Sought

This paper is based on the previous work.

Table of contents

6 face detection multiple

7 Video detection

8 Take pictures and save

9 training data

Solve the error AttributeError: module 'cv2' has no attribute 'face'

10 face recognition


6 face detection multiple

The whole code is as follows: 

# 导入cv模块
import cv2 as cv


# 检测函数
def face_detect_demo():
    gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_detect = cv.CascadeClassifier(
        'D:/my/python-pycharm/python-envs/venv-deep/Lib/site-packages/cv2/data/haarcascade_frontalface_alt2.xml')
    face = face_detect.detectMultiScale(gary)
    for x, y, w, h in face:
        cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
    cv.imshow('result', img)


# 读取图像
img = cv.imread('face2.jpg')
# 检测函数
face_detect_demo()
# 等待
while True:
    if ord('q') == cv.waitKey(0):
        break
# 释放内存
cv.destroyAllWindows()

The effect is as follows: 

It can be seen that most of the faces have been detected. In the case of a large number of people, one of them was not detected, but the requirements can be basically completed in simple scenarios.

Of course, we can also change the called haarcascade_frontalface_alt2.xml file and replace it with other ones under this path, such as haarcascade_frontalface_default.xml, the effect will be slightly different.

7 Video detection

The whole code is as follows: 

# 导入cv模块
import cv2 as cv


# 检测函数
def face_detect_demo(img):
    gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_detect = cv.CascadeClassifier('D:/my/python-pycharm/python-envs/venv-deep/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    face = face_detect.detectMultiScale(gary)
    for x, y, w, h in face:
        cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
    cv.imshow('result', img)


# 读取摄像头
cap = cv.VideoCapture(0)
# 循环
while True:
    flag, frame = cap.read()
    if not flag:
        break
    face_detect_demo(frame)
    if ord('q') == cv.waitKey(1):
        break
# 释放内存
cv.destroyAllWindows()
# 释放摄像头
cap.release()

The effect is not shown here.

8 Take pictures and save

The whole code is as follows: 

# 导入模块
import cv2

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

falg = 1
num = 1

while (cap.isOpened()):  # 检测是否在开启状态
    ret_flag, Vshow = cap.read()  # 得到每帧图像
    cv2.imshow("Capture_Test", Vshow)  # 显示图像
    k = cv2.waitKey(1) & 0xFF  # 按键判断
    if k == ord('s'):  # 保存
        cv2.imwrite("D:/mycodetest/opencv/data/jm/" + str(num) + ".123" + ".jpg", Vshow)
        print("success to save" + str(num) + ".jpg")
        print("-------------------")
        num += 1
    elif k == ord(' '):  # 退出
        break
# 释放摄像头
cap.release()
# 释放内存
cv2.destroyAllWindows()

The effect is not shown here.

9 training data

The whole code is as follows: 

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


def getImageAndLabels(path):
    facesSamples = []
    ids = []
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    # 检测人脸
    face_detector = cv2.CascadeClassifier(
        'D:/my/python-pycharm/python-envs/venv-deep/Lib/site-packages/cv2/data/haarcascade_frontalface_alt2.xml')
    # 打印数组imagePaths
    print('数据排列:', imagePaths)
    # 遍历列表中的图片
    for imagePath in imagePaths:
        # 打开图片,黑白化
        PIL_img = Image.open(imagePath).convert('L')
        # 将图像转换为数组,以黑白深浅
        # PIL_img = cv2.resize(PIL_img, dsize=(400, 400))
        img_numpy = np.array(PIL_img, 'uint8')
        # 获取图片人脸特征
        faces = face_detector.detectMultiScale(img_numpy)
        # 获取每张图片的id和姓名
        id = int(os.path.split(imagePath)[1].split('.')[0])
        # 预防无面容照片
        for x, y, w, h in faces:
            ids.append(id)
            facesSamples.append(img_numpy[y:y + h, x:x + w])
        # 打印脸部特征和id
        # print('fs:', facesSamples)
        print('id:', id)
        # print('fs:', facesSamples[id])
    print('fs:', facesSamples)
    # print('脸部例子:',facesSamples[0])
    # print('身份信息:',ids[0])
    return facesSamples, ids


if __name__ == '__main__':
    # 图片路径
    path = './data/jm/'
    # 获取图像数组和id标签数组和姓名
    faces, ids = getImageAndLabels(path)
    # 获取训练对象
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    # recognizer.train(faces,names)#np.array(ids)
    recognizer.train(faces, np.array(ids))
    # 保存文件
    recognizer.write('trainer/trainer.yml')
    # save_to_file('names.txt',names)

The effect is as follows: A file will be generated with the path trainer/trainer.yml.

Solve the error AttributeError: module 'cv2' has no attribute 'face'

Scenario : When using cv2.face.LBPHFaceRecognizer_create() for face recognition operations, such a prompt will appear.

recognizer = cv2.face.LBPHFaceRecognizer_create()

Solution : This happens because a dependent package is missing .

From the official website, we can see that the face module is not actually part of the opencv library. More precisely, face is part of the opencv-contrib library. From the readme: This repository [opencv-contrib] is used to develop so-called "extra" modules, providing functionality. New modules often do not have stable APIs, and they are not well tested. Therefore, they should not be released as part of the official OpenCV distribution, as the library maintains binary compatibility and tries to provide good performance and stability.

(1) First switch to your environment (it is not recommended to download directly in the base environment), and then download the related packages we need, and use Tsinghua source to download quickly.

In the terminal of pycharm, execute the next command,

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-contrib-python

The installation is successful, and you can run the code again after seeing successfully.

ok, the problem is solved.

10 face recognition

The whole code is as follows: 

import cv2, os
import numpy as np
# coding=utf-8
import urllib
import urllib.request
import hashlib

# 加载训练数据集文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')
names = []
warningtime = 0


def md5(str):
    import hashlib
    m = hashlib.md5()
    m.update(str.encode("utf8"))
    return m.hexdigest()


statusStr = {
    '0': '短信发送成功',
    '-1': '参数不全',
    '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间',
    '30': '密码错误',
    '40': '账号不存在',
    '41': '余额不足',
    '42': '账户已过期',
    '43': 'IP地址限制',
    '50': '内容含有敏感词'
}


def warning():
    smsapi = "http://api.smsbao.com/"
    # 短信平台账号
    user = '13******10'
    # 短信平台密码
    password = md5('*******')
    # 要发送的短信内容
    content = '【报警】\n原因:检测到未知人员\n地点:xxx'
    # 要发送短信的手机号码
    phone = '*******'

    data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})
    send_url = smsapi + 'sms?' + data
    response = urllib.request.urlopen(send_url)
    the_page = response.read().decode('utf-8')
    print(statusStr[the_page])


# 准备识别的图片
def face_detect_demo(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转换为灰度
    face_detector = cv2.CascadeClassifier('D:/my/python-pycharm/python-envs/venv-deep/Lib/site-packages/cv2/data/haarcascade_frontalface_alt2.xml')
    face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300))
    # face=face_detector.detectMultiScale(gray)
    for x, y, w, h in face:
        cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)
        cv2.circle(img, center=(x + w // 2, y + h // 2), radius=w // 2, color=(0, 255, 0), thickness=1)
        # 人脸识别
        ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
        # print('标签id:',ids,'置信评分:', confidence)
        if confidence > 80:
            global warningtime
            warningtime += 1
            if warningtime > 100:
                warning()
                warningtime = 0
            cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
        else:
            cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
    cv2.imshow('result', img)
    # print('bug:',ids)


def name():
    path = './data/jm/'
    # names = []
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    for imagePath in imagePaths:
        name = str(os.path.split(imagePath)[1].split('.', 2)[1])
        names.append(name)


cap = cv2.VideoCapture('1.mp4')
name()
while True:
    flag, frame = cap.read()
    if not flag:
        break
    face_detect_demo(frame)
    if ord(' ') == cv2.waitKey(10):
        break
cv2.destroyAllWindows()
cap.release()
# print(names)

If you want to use the alarm function mentioned in the code, you first need to go to the better short message service-SMS Bao official website to register and log in to have an account.

Here, because the account information written in my code is incorrect, the output of the pycharm terminal is "password error", and under normal circumstances, it will display that the SMS message has been successfully generated.

The effect is as follows: 

 

Since our data training only added a picture with the path ./data/jm/1.lena.jpg, when the code is executed to build face recognition, it can only recognize the girl named lena, and other faces are recognized All will be marked as "unknown".

Guess you like

Origin blog.csdn.net/qq_45956730/article/details/128996243