python 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")

效果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值