import pickle
with open('faces.dat', 'wb') as f:
pickle.dump(known_face_list, f)
下次需要使用時,直接透過 pickle.load() 就能還原!比 json 還方便啊!
with open('faces.dat', 'rb') as f:
known_face_list = pickle.load(f)
發現有時會誤判人臉?改用 CNN 模型
Face Recognition 預設辨識人臉位置的模型是 HOG (Histograms of Oriented Gradients),原理是透過梯度資訊反應影象目標的邊緣資訊,並透過區域性梯度的大小將影象區域性的外觀和形狀特徵化。相對於 CNN 模型,實測發現 HOG 不太能抓到較小的人臉,或是因光影關係而誤判。此時可以考慮使用 CNN 來做偵測。
CNN 的缺點是需要較大的運算量,純 CPU 計算會比 HOG 慢相當多,建議在有 CUDA 的平台上使用(Face Recognition 支援 CUDA 加速)。
# 辨識臉部位址時,給定 model = 'cnn' 即可
cur_face_locs = face_recognition.face_locations(img, model='cnn')
簡單用以下 code 測試一下在 CPU 跑的速度差異
import time
for fn in test_fn_list:
img = cv2.imread(fn)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
_t = time.time()
face_recognition.face_locations(img) # use HOG model to detect face locations
_t1 = time.time()
face_recognition.face_locations(img, model='cnn') # use CNN model to detect face locations
print(f'HOG: {round(_t1 - _t, 2)} secs, CNN: {round(time.time() - _t1, 2)} secs')
結果如下 (Macbook 2020 / i5 2Ghz)
測試檔案
HOG
CNN
孫藝珍-t1.jpeg
0.18s
3.47s
孫藝珍-t2.jpeg
0.16s
3.19s
孫藝珍-t3.jpeg
0.19s
3.93s
玄彬+孫藝珍.jpeg
0.41s
10.14s
準確度不夠?增加特徵點數量
如果發現誤判未知人臉的機率太高,可以增加 encoding 時使用的特徵點數量。
Face Recognition 預設使用 small(5 個特徵點),可以改用 large(68 個特徵點)測試看看。
for data in known_face_list:
img = cv2.imread(data['filename'])
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
data['encode'] = face_recognition.face_encodings(img)[0]
min_distance_index = np.argmin(face_distance_list)
if face_distance_list[min_distance_index] < tolerance:
result = known_face_list[min_distance_index]['name']
else:
result = 'unknown'
print(f'辨識檔案: {fn}, 辨識結果: {result}')
解釋完畢,我們立刻來看看辨識結果
辨識檔案: 孫藝珍-t1.jpeg, 辨識結果: Son Ye Jin
辨識檔案: 孫藝珍-t2.jpeg, 辨識結果: Son Ye Jin
辨識檔案: 孫藝珍-t3.jpeg, 辨識結果: Son Ye Jin
辨識檔案: 玄彬+孫藝珍.jpeg, 辨識結果: Hyun Bin
辨識檔案: 玄彬+孫藝珍.jpeg, 辨識結果: Son Ye Jin
看起來蠻理想的!接下來我們將辨識結果畫上圖片看看!
Step 5:開始比對並繪製紅色方框
先準備好一個繪製紅色方框的 utility function,他接收 img 和 match_results,依序拉出裡面的 location 和 name 來繪製。