使用 MTCNN进行人脸识别教程 配置+代码实例 远离踩坑

1. github地址

https://github.com/ipazc/mtcnn

2. 安装

Currently it is only supported Python3.4 onwards. It can be installed through pip:

$ pip install mtcnn

This implementation requires OpenCV>=4.1 and Keras>=2.0.0 (any Tensorflow supported by Keras will be supported by this MTCNN package). If this is the first time you use tensorflow, you will probably need to install it in your system:

$ pip install tensorflow==1.9.0
$ pip install keras==2.2.0

3. 环境配置

我的版本:

python 3.6.5
tensorflow 1.9.0
Keras 2.2.0

其他可参考 https://www.cnblogs.com/carle-09/p/11661261.html

但是keras 版本必须大于 2.2

4. 实例代码 人脸识别

4.1 库

from mtcnn import MTCNN
detector = MTCNN()

import numpy as np
import cv2


4.2 检测函数

  • 输入是一个 height * weight * 3的图片 (三维数组), 可以用cv2.imread() 读取
  • 输出是 一个数组, 每个元素是 height * weight * 3 , 表示的是 面部的 三维数组, 可以用cv2.imwrite()保存
def detect_face (img):
    # img =  height * weight * 3  (RGB)
    shapes = np.array(img).shape

    # face_arr

    face_arr = []

    # 得到高度和宽度 做异常处理
    height = shapes[0]
    weight = shapes[1]

    #检测人脸
    detect_result = detector.detect_faces(img)

    #如果检测不到人脸、 返回空

    if len(detect_result )== 0:
        return []
    else :
        for item in detect_result:


            box = item['box']

            #因为预测是 给出左上角的点座标【0,1】  以及 长宽【2,3】  所以需要转换
            top = box[1]
            buttom = box[1] + box[3]
            left = box[0]
            right = box[0] + box[2]
            #因为左上角的点可能会在图片范围外 所以要异常处理
            if top < 0:
                top = 0
            if left < 0:
                left = 0
            if buttom > height:
                buttom = height
            if right > weight:
                right = weight

            face_arr.append(img[top: buttom, left: right])

    return face_arr



4.3 实例

import cv2

img = cv2.imread('test1.png')
# jpg保存

face_arr = detect_face(img)

if not len(face_arr) == 0:
    count = 0
    # 把脸部图片全部进行 写出
    for item in face_arr:
        count = count + 1
        cv2.imwrite( "face_" + str(count) + '.png', item )  # 写入图片   jpg有损压缩,png无损压缩
        else:
            print("No face is detected")

效果

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章