今天剛好有個需求需要偵測照片中的臉部,然後將臉部切割出來,後續可以做人臉比對(臉部偵測)應用,這方面技術可以採用opencv等作法,算是蠻成熟的一個應用,在這邊採用python作法.
其實最著名的做法是採用dlib C++這個套件來應用,可以在很機器學習或深度學習引用此套件,他透過LFW人臉數據進行機器學習與深度學習,所以若只是單抓人臉應該還蠻準確的.
而Python中有個face-recognition套件就將此應用集合起來.
話不多說來安裝吧!
Step1. 安裝
1 |
pip install face_recognition |
安裝過程中有出現錯誤,類似
1 |
CMake must be installed to build the following extensions: dlib |
基本上就是因為會引用到dlib套件,我是試圖直接安裝dlib,發現會有問題,後來發現他又引用了其它套件,所以要先安裝cmake(要根據訊息來安裝相關套件),我是安裝以下即可.
1 |
pip install cmake |
Step2. 準備一張有多人的圖片(節錄至攝圖網)
Step3. 寫一段程式,分割臉部(採用官方教學)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from PIL import Image 2 import face_recognition 3 4 # Load the jpg file into a numpy array 5 image = face_recognition.load_image_file("photoname.jpg") 6 7 # Find all the faces in the image using the default HOG-based model. 8 # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated. 9 # See also: find_faces_in_picture_cnn.py 10 face_locations = face_recognition.face_locations(image) 11 12 print("I found {} face(s) in this photograph.".format(len(face_locations))) 13 14 for face_location in face_locations: 15 16 # Print the location of each face in this image 17 top, right, bottom, left = face_location 18 print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) 19 20 # You can access the actual face itself like this: 21 face_image = image[top:bottom, left:right] 22 pil_image = Image.fromarray(face_image) 23 pil_image.show() |
Step4. 什麼!已經完成了,看結果吧!
未完待續…其實他也可以進行人臉比對,有機會再跟各位分享!