日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

人脸识别Python教学

發布時間:2023/12/9 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 人脸识别Python教学 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.摘要

人臉識別在 Computer Vision 中一直是很火熱的話題,也是目前廣為人知的一項技術。本質上分為 Face Verification、Face Recognition:前者為驗證兩張人臉是否為同一個人,屬于一對一的過程;后者則是從數據庫里辨識出相同的人臉,屬于一對多的過程。詳細的人臉辨識解說可以參考: 使用深度學習進行人臉辨識: Triplet loss, Large margin loss(ArcFace)。

2.實現過程

本文將要使用 Python 來進行人臉識別的實現,過程分為幾個階段:

  • Face Detection
  • Face Align
  • Feature Extraction
  • Create Database
  • Face Recognition

2.0安裝相關庫

首先安裝相關庫

pip install scikit-learn pip install onnxruntime

2.1 Face Detection

這部分要進行人臉檢測,可以使用Python API MTCNN、Retina Face這邊示范使用RetinaFace來進行檢測。

  • 安裝RetinaFace
pip install retinaface
  • 檢測
    接著就可以來檢測人臉啦,輸出包含人臉預測框的左上角跟右下角點、兩個眼睛、鼻子、嘴巴兩邊的坐標值:
import cv2 from retinaface import RetinaFacedetector = RetinaFace(quality="normal") img_path = "001.jpg" img_bgr = cv2.imread(img_path, cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) detections = detector.predict(img_bgr) print(detections) # # output[{‘x1’: 243, ‘y1’: 142, ‘x2’: 557, ‘y2’: 586, ‘left_eye’: (303, 305), ‘right_eye’: (431, 346), ‘nose’: (305, 403), ‘left_lip’: (272, 468), ‘right_lip’: (364, 505)}] img_result = detector.draw(img_rgb, detections) img = cv2.cvt_color(img_result, cv2.COLOR_RGB2BGR) cv2.imshow("windows", img) key = cv2,waitKey() & 0xffff if key==ord("q"):print("exit") cv2.destoryWindow("windows")


若使用RetinaFace的時候,出現以下錯誤:

有可能是因為無法導入shapely.geometry模塊的關系,因此要先下去下載shapely包,下載地址https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely 下載完成以后再執行以下指令:

pip install <your Shapely package path>

測試安裝是否成功

$ python >>> from shapely.geometry import Polygon

2.2 Face Align

這部分要將人臉特征點進行對齊,需要先定義要對齊的坐標,在onnxarcface_inference.ipynb里的Preprocess images中可以看到。
接著就用skimage套件transform.SimilarityTransform()得到要變換的矩陣,然后進行對齊:

import cv2 from retinaface import RetinaFace from skimage import transform as transsrc = np.array([[30.2946, 51.6963],[65.5318, 51.5014],[48.0252, 71.7366],[33.5493, 92.3655],[62.7299, 92.2041]], dtype=np.float32)detector = RetinaFace(quality="normal") img_path = "001.jpg" img_bgr = cv2.imread(img_path, cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) detections = detector.predict(img_bgr)for i, face_info in enumerate(detections):face_position = [face_info["x1"], face_info["y1"], face_info["x2"], face_info["y2"]]face_landmarks = [face_info["left_eye"], face_info["right_eye"], face_info["nose"], face_info["left_lip"], face_info["right_lip"]]dst = np.array(face_landmarks, dtype=np.float32).shape(5, 2)tform = trans.SimilarityTransform()tform.estimate(dst, src)M = tform.params[0:2, :]aligned = cv2.warpAffine(imgRGB, M, (112, 112), borderValue=0)

對齊特征點后的人臉會呈現以下結果:

2.3 Feature extraction

這部分要提取剛剛對齊后的人臉特征,這邊使用onnx ArcFace model。

  • InsightFace-REST模型arcface_r100_v1下載
  • onnx 官方模型下載

如果是下載onnx官方模型需要先進行更新,因為該模型的BatchNorm節點中spatial為0,參考: https://github.com/onnx/models/issues/156。不過轉換過后的模型準確度比較差,因此數據集需要放兩張比較能夠檢測出來的圖片。

import onnx model = onnx.load("model/arcfaceresnet100-8.onnx") for node in model.graph.node:if(node.op_type == "BatchNormalization"):for attr in node.attribute:if(attr.name == "spatial"):attr.i = 1 onnx.save(model, "model/arcfaceresnet100.onnx")

接著使用模型進行特征提取:將對齊后的人臉做轉置,再轉換的type為float32,最后進行推理:

import numpy as np import onnxruntime as rt from sklearn.preprocessing import normalizeonnx_path = "model/arcfaceresnet100.onnx" extractor = rt.InferenceSession(onnx_path)t_aligned = np.transpose(aligned, (2, 0, 1)) inputs = t_aligned.astype(np.float32) input_blob = np.expand_dims(inputs, axis=0)first_input_name = extractor.get_inputs()[0].name first_output_name = extractor.get_outputs()[0].namepredict = extractor.run([first_output_name], {first_input_name:input_blob})[0] final_embedding = normalize(predict).flatten()

2.4 Create Database

這部分要將識別的人臉資料寫進數據庫里,這邊數據庫是使用sqlite。
首先,準備要識別的人臉資料:

接著把上面的Face Detection、Face Align、Feature extraction寫成函數,調用比較方便。然后將資料夾的圖片分別進行檢測、對齊、提取特征后,再寫入數據庫中。

import sqlite3 import io import osdef adapt_array(arr):out = io.BytesIO()np.save(out, arr)out.seek(0)return sqlite3.Binary(out.read())def convert_array(text):out = io.ByteIO(text)out.seek(0)return np.load(out)def load_file(file_path):file_data = {}for person_name in os.listdir(file_path):person_file = os.path.join(file_path, person_name)total_picture = []for picture in os.listdir(person_file):picture_path = os.path.join(person_file, picture)total_pictures.append(picture_path)file_data[person_name] = total_picturesreturn file_datasqlite3.register_adapter(np.ndarray, adapt_array) sqlite3.register_converter("ARRAY", convert_array) conn_db = sqlite3.connect("database.db") conn_db.execute("CREATE TABLE face_info (id INT PRIMARY KEY NOT NULL,name TEXT NOT NULL,embedding ARRAY NOT NULL)")file_path = "database" if os.path.exists(file_path):file_data = load_file(file_path)for i, person_name in enumerate(file_data.keys()):picture_path = file_data[person_name]sum_embeddings = np.zeros([1, 512])for j, picture in enumerate(picture_path):img_rgb, detections = face_detect(picture)position, landmarks, embeddings = get_embeddings(img_rgb, detections)sum_embeddings += embeddingsfinal_embedding = sum_embeddings / len(picture_path)adapt_embedding = adapt_array(final_embedding)conn_db.execute("INSERT INTO face_info (id, name, embedding) VALUES (?, ?, ?)", (i, person_name, adapt_embedding))conn_db.commit()conn_db.close()

確認是否寫入數據庫里面:

import sqlite3 import numpy as np import iodef adapt_array(arr):out = io.ByteIO()np.save(out, arr)out.seek(0)return sqlite3.Binary(out.read())def convert_array(text):out = io.ByteIO(text)out.seek(0)return np.load(out)sqlite3.register_adapter(np.ndarray, adapt_array) sqlite3.register_converter("array", convert_array) conn_db = sqlite3.connect("database.db")cursor = conn_db.execute("SELECT * FROM face_info") db_data = cursor.fetchall() for data in db_data:print(data) conn_db.close()

2.5 Face Recognition

這部分是要將數據庫里的人臉特征跟輸入照片進行比對,這里使用L2-Norm來計算之間的距離。最后再設定thresold,若L2-Norm距離大于threshold表示輸入照片不為數據庫中的任何一人,反之,L2-Norm距離最小的人臉與輸入照片為同一人。

import numpy as np import sqlite3 import io import osconn_db = sqlite3.connect(db_path) cursor = conn_db.execute("SELECT * FROM face_info") db_data = cursor.fetchall()total_distances = [] total_names = [] for data in dn_data:total_names.append(data[1])db_embeddings = convert_array(data[2])distance = round(np.linalg.norm(db_embeddings-embeddings), 2)total_distances.append(distance) total_result = dict(zip(total_names, total_distances)) idx_min = np.argmin(total_distances)distance, name = total_distances[idx_min], total_names[idx_min] conn_db.close()if distance < threshold:return name, distance, total_result else:name = "Unknown Person"return name, distance, total_result

接下來看看測試結果吧!由以下測試結果可以看出,在數據庫中的人臉都有正確的識別到,而不在的則會顯示Unkonwn Perrson。

詳細代碼詳見https://github.com/chingi071/Face_recognition

參考目錄

https://medium.com/ching-i/face-recognition-%E4%BA%BA%E8%87%89%E8%BE%A8%E8%AD%98-python-%E6%95%99%E5%AD%B8-75a5e2ef534f

總結

以上是生活随笔為你收集整理的人脸识别Python教学的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。