前言
最近碰到了照片識別的場景,正好使用了face_recognition項目,給大家分享分享。face_recognition項目能做的很多,人臉檢測功能也是有的,是一個比較成熟的項目。該項目的github地址:github倉庫
本文主要是對該項目的安裝使用,后面會更新一篇我自己寫的實現人臉檢測的代碼,可以直接使用。
環境安裝
首先我們看看官方給出的人臉識別效果圖
我們看一下README關於安裝環境的信息
官方給出的可安裝操作系統是Mac和Linux,但是我想在windows安裝,繼續往下看。
windows雖然不是官方支持,但是也能裝,不就是個dlib嗎?好的,那就開始裝。
我們直接安裝requirements_dev.txt,這里要注意,把pip去掉。
注意一點安裝dlib的時候會報錯,需要先安裝cmake,安裝命令如下:
pip install cmake -i https://pypi.douban.com/simple
除此之外,項目還需要安裝opencv-python,安裝命令如下:
pip install opencv-python -i https://pypi.douban.com/simple
代碼使用
先做一下說明,在使用face_recognition運行的時候,可以選擇安裝face_recognition命令進行運行的模式,也可以使用face_recognition模塊構建代碼運行。為了二次開發,我還是先試試代碼的方式,主要試試人臉識別模塊。
官方代碼如下:
import face_recognition
# Load the jpg files into numpy arrays
biden_image = face_recognition.load_image_file("biden.jpg")
obama_image = face_recognition.load_image_file("obama.jpg")
unknown_image = face_recognition.load_image_file("obama2.jpg")
# Get the face encodings for each face in each image file
# Since there could be more than one face in each image, it returns a list of encodings.
# But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
try:
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
except IndexError:
print("I wasn't able to locate any faces in at least one of the images. Check the image files. Aborting...")
quit()
known_faces = [
biden_face_encoding,
obama_face_encoding
]
# results is an array of True/False telling if the unknown face matched anyone in the known_faces array
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)
print("Is the unknown face a picture of Biden? {}".format(results[0]))
print("Is the unknown face a picture of Obama? {}".format(results[1]))
print("Is the unknown face a new person that we've never seen before? {}".format(not True in results))
代碼說明:
1、首先可以看到將兩個人臉的數據加到了known_faces列表內。
2、然后用未知圖數據進行識別判斷。
看一下加入到known_faces的照片
看一下需要識別的照片
看一下執行結果
我們可以看到在拜登的識別中提示false,在奧巴馬識別中提示true。這里要注意一點,我們看一下compare_faces方法參數。
參數tolerance最佳為0.6,越低越嚴格,所以可以按照自己的需求調整。
總結
經過我多次測試,在臉型比較接近的情況下,還是會有誤差,需要按照自己的情況進行調整。
分享:生活最沉重的負擔不是工作,而是無聊。——《羅曼·羅蘭》
如果本文對你有幫助的話,點個贊吧,謝謝!
本人CSDN主頁地址:劍客阿良_ALiang的主頁
一起學習,一起進步。