Python實作人臉辨識(2)–繪出人臉位置

Share This Post

這邊使用MTCNN進行人臉範圍繪製的工作。

什麼事MTCNN

MTCNN全稱為Multi-task Cascaded Convolutional Networks,是一種用於人臉檢測和識別的深度學習模型。MTCNN由三個卷積神經網絡組成,分別為人臉檢測網絡、候選框修正網絡和人臉識別網絡。它可以快速且準確地檢測圖像中的人臉,並生成相應的識別框和人臉特徵,是現代人臉識別和圖像處理技術中的重要工具之一。

開始實作

  1. 建立資料夾及檔案

資料夾中要包含:
Superstar(資料夾, 內含多張有人臉之照片)
headshot(空資料夾,用來存放偵測到的人臉影像)
FaceDetection.py

  1. 安裝MTCNN模型及相關套件
  1. 執行主程式
# FaceDetection2.py

from os import listdir
import matplotlib.pyplot as plt
import numpy as np
from mtcnn.mtcnn import MTCNN
import cv2

dir_superstar = '/content/drive/MyDrive/range/Superstar/'
dir_headshot = '/content/drive/MyDrive/range/headshot/'

detector  =  MTCNN()
for filename in listdir(dir_superstar):
    print(filename)
    path  =  dir_superstar  +  filename
    print('load from: ',path)
    save_path  =  dir_headshot  +  filename
    print('save to: ',save_path)
    filename = filename[:-4]
    try:
        imageBGR = cv2.imread( path, 1 )
        imageRGB=cv2.cvtColor(imageBGR,cv2.COLOR_BGR2RGB)
        results  =  detector.detect_faces(imageRGB)
        x1,  y1,  width,  height  = results[0]['box']
        x1,  y1  =  abs(x1),  abs(y1)
        x2,  y2  =  x1  +  width,  y1  +  height
        faceRGB  =  imageRGB[y1:y2,  x1:x2]
        plt.figure()
        plt.subplot(121)
        plt.imshow(imageRGB)
        plt.title(filename)
        plt.subplot(122)
        plt.imshow(faceRGB)
        plt.show()
        faceBGR=cv2.cvtColor(faceRGB,cv2.COLOR_RGB2BGR)
        cv2.imwrite(save_path,faceBGR)
    except(IndexError,IsADirectoryError,OSError):
        except_file.append(filename)
        print('except file...'+str(filename))
        pass

將程式碼貼上並執行

  1. 結果

左邊是superstar資料夾中的照片,右邊是擷取下來的人臉,擷取下來後會存放至headshot中。

訂閱研究文章

Get updates and learn from the best