1. 程式人生 > 程式設計 >Python3 利用face_recognition實現人臉識別的方法

Python3 利用face_recognition實現人臉識別的方法

前言

之前實踐了下face++線上人臉識別版本,這回做一下離線版本。github 上面有關於face_recognition的相關資料,本人只是做個搬運工,對其中的一些內容進行搬運,對其中一些例子進行實現。

官方描述:

face_recognition是一個強大、簡單、易上手的人臉識別開源專案,並且配備了完整的開發文件和應用案例,特別是相容樹莓派系統。本專案是世界上最簡潔的人臉識別庫,你可以使用Python和命令列工具提取、識別、操作人臉。本專案的人臉識別是基於業內領先的C++開源庫 dlib中的深度學習模型,用Labeled Faces in the Wild人臉資料集進行測試,有高達99.38%的準確率。但對小孩和亞洲人臉的識別準確率尚待提升。

(關於相容樹莓派,以後有板子了再做一下)

下面兩個連結劃重點

https://github.com/ageitgey/face_recognition/blob/master/README_Simplified_Chinese.md
https://face-recognition.readthedocs.io/en/latest/face_recognition.html

環境配置

  • ubuntu16.04(其他環境的安裝可以參考第一個連結,官方有說明)
  • pycharm(可忽略,怎麼舒服怎麼來)
  • python3
  • opencv(我的是4.1.2,三點幾的版本應該也一樣)

實際上只需要安裝face_recognition,當然,沒有opencv的也需要安裝一下opencv

pip3 install face_recognition

圖片準備

由於需要做一些圖片的比對,因此需要準備一些圖片,本文圖片取自以下連結

https://www.zhihu.com/question/314169580/answer/872770507

接下來開始操作

官方還有提供命令列的操作(這個沒去做),本文不做這個,我們只要是要在python中用face_recognition,因此定位到這一塊。

Python3 利用face_recognition實現人臉識別的方法

這個api文件地址就是上面的第二個連結。進去之後可以看到:

Python3 利用face_recognition實現人臉識別的方法

part1.識別圖片中的人是誰

程式碼

# part1
# 識別圖片中的人是誰
import face_recognition
known_image = face_recognition.load_image_file("lyf1.jpg")
unknown_image = face_recognition.load_image_file("lyf2.jpg")

lyf_encoding = face_recognition.face_encodings(known_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

results = face_recognition.compare_faces([lyf_encoding],unknown_encoding)	
# A list of True/False values indicating which known_face_encodings match the face encoding to check

print(type(results))
print(results)

if results[0] == True:
  print("yes")
else:
  print("no")

結果

<class 'list'>
[True]
yes

part2.從圖片中找到人臉

程式碼

# part2
# 從圖片中找到人臉(定位人臉位置)

import face_recognition
import cv2

image = face_recognition.load_image_file("lyf1.jpg")

face_locations_useCNN = face_recognition.face_locations(image,model='cnn')
# model – Which face detection model to use. “hog” is less accurate but faster on CPUs.
# “cnn” is a more accurate deep-learning model which is GPU/CUDA accelerated (if available). The default is “hog”.

face_locations_noCNN=face_recognition.face_locations(image)
# A list of tuples of found face locations in css (top,right,bottom,left) order
# 因為返回值的順序是這樣子的,因此在後面的for迴圈裡面賦值要注意按這個順序來

print("face_location_useCNN:")
print(face_locations_useCNN)
face_num1=len(face_locations_useCNN)
print(face_num1)    # The number of faces


print("face_location_noCNN:")
print(face_locations_noCNN)
face_num2=len(face_locations_noCNN)
print(face_num2)    # The number of faces
# 到這裡為止,可以觀察兩種情況的座標和人臉數,一般來說,座標會不一樣,但是檢測出來的人臉數應該是一樣的
# 也就是說face_num1 = face_num2; face_locations_useCNN 和 face_locations_noCNN 不一樣


org = cv2.imread("lyf1.jpg")
img = cv2.imread("lyf1.jpg")
cv2.imshow("lyf1.jpg",img) # 原始圖片

# Go to get the data and draw the rectangle
# use CNN
for i in range(0,face_num1):
  top = face_locations_useCNN[i][0]
  right = face_locations_useCNN[i][1]
  bottom = face_locations_useCNN[i][2]
  left = face_locations_useCNN[i][3]

  start = (left,top)
  end = (right,bottom)

  color = (0,255,255)
  thickness = 2
  cv2.rectangle(img,start,end,color,thickness)  # opencv 裡面畫矩形的函式

# Show the result
cv2.imshow("useCNN",img)


# for face_location in face_locations_noCNN:
#
#   # Print the location of each face in this image
#   top,left = face_location
# # 等價於下面的這種寫法

for i in range(0,face_num2):
  top = face_locations_noCNN[i][0]
  right = face_locations_noCNN[i][1]
  bottom = face_locations_noCNN[i][2]
  left = face_locations_noCNN[i][3]

  start = (left,255)
  thickness = 2
  cv2.rectangle(org,thickness)

cv2.imshow("no cnn ",org)

cv2.waitKey(0)
cv2.destroyAllWindows()

結果

face_location_useCNN:
[(223,470,427,266)]
1
face_location_noCNN:
[(242,489,464,266)]
1

圖片效果大致是這樣

Python3 利用face_recognition實現人臉識別的方法

part3.找到人臉並將其裁剪打印出來(使用cnn定位人臉)

程式碼

# part3
# 找到人臉並將其裁剪打印出來(使用cnn定位人臉)

from PIL import Image
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("lyf1.jpg")

face_locations = face_recognition.face_locations(image,number_of_times_to_upsample=0,model="cnn")

print("I found {} face(s) in this photograph.".format(len(face_locations)))

for face_location in face_locations:
  top,left = face_location
  print("A face is located at pixel location Top: {},Left: {},Bottom: {},Right: {}".format(top,left,right))

  face_image = image[top:bottom,left:right]
  pil_image = Image.fromarray(face_image)
  pil_image.show()

結果

I found 1 face(s) in this photograph.
A face is located at pixel location Top: 205,Left: 276,Bottom: 440,Right: 512

圖片效果大致是這樣

Python3 利用face_recognition實現人臉識別的方法

part4.識別單張圖片中人臉的關鍵點

程式碼

# part4 識別單張圖片中人臉的關鍵點

from PIL import Image,ImageDraw
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("lyf1.jpg")

# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)
# print(face_landmarks_list)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))

# Create a PIL imagedraw object so we can draw on the picture
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)

for face_landmarks in face_landmarks_list:

  # Print the location of each facial feature in this image
  for facial_feature in face_landmarks.keys():
    print("The {} in this face has the following points: {}".format(facial_feature,face_landmarks[facial_feature]))

  # Let's trace out each facial feature in the image with a line!
  for facial_feature in face_landmarks.keys():
    d.line(face_landmarks[facial_feature],width=5)

# Show the picture
pil_image.show()

結果

I found 1 face(s) in this photograph.
The left_eyebrow in this face has the following points: [(305,285),(321,276),(340,277),(360,281),(377,288)]
The right_eye in this face has the following points: [(422,313),(432,303),(446,302),(459,305),(449,312),(435,314)]
The nose_bridge in this face has the following points: [(394,309),(394,331),(395,354),(396,375)]
The right_eyebrow in this face has the following points: [(407,287),(424,278),(442,273),(461,272),(478,279)]
The bottom_lip in this face has the following points: [(429,409),(419,421),(408,428),(398,430),(389,429),424),(364,412),(370,413),414),415),(407,(423,411)]
The chin in this face has the following points: [(289,295),(291,323),(296,351),(303,378),(315,403),(332,(353,448),(376,464),(400,467),(422,461),(441,444),425),(473,(484,377),(490,(493,296)]
The top_lip in this face has the following points: [(364,407),(397,406),(406,402),(417,405),(429,411),413)]
The left_eye in this face has the following points: [(327,308),(339,304),306),314),(352,317),(338,316)]
The nose_tip in this face has the following points: [(375,383),(386,387),390),385),(416,381)]

圖片效果

Python3 利用face_recognition實現人臉識別的方法

到此這篇關於Python3 利用face_recognition實現人臉識別的方法的文章就介紹到這了,更多相關Python3 人臉識別內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!