使用 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")

效果

在這裏插入圖片描述

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