介绍
如何创建面部识别应用程序的记录,具体来说,所做如下:
- 尝试使用Raspberry Pi 4 + CameraModule3 进行拍摄
- 尝试使用 OpenCV 对相机拍摄的图像进行面部识别处理
- 尝试使用 Streamlit 将以上内容转换为 Web 应用程序
开发环境
- Raspberry Pi 4
- Bullseye 64bit
- Python 3.9.2
- CameraModule3
使用 Raspberry Pi 和相机拍摄
在这个步骤中遇到了很多麻烦,过几天再出篇文章,单独进行总结
使用 OpenCV 对拍摄图像进行人脸识别处理
安装包
安装 picamera2 和 OpenCV。
pip install picamera2
pip install opencv-python
下载训练好的模型
yunet_n_640_640.onnx
face_recognizer_fast.onnx
保存面部图像
从图像中检测人脸,将其剪切出来并保存为人脸图像。
源代码
import os
import argparse
import cv2
def main():
parser = argparse.ArgumentParser("generate aligned face images from an image")
parser.add_argument("image", help="input image file path (./image.jpg)")
args = parser.parse_args()
path = args.image
directory = os.path.dirname(args.image)
if not directory:
directory = os.path.dirname(__file__)
path = os.path.join(directory, args.image)
image = cv2.imread(path)
if image is None:
exit()
channels = 1 if len(image.shape) == 2 else image.shape[2]
if channels == 1:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
if channels == 4:
image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
weights = "onnx/yunet_n_640_640.onnx"
face_detector = cv2.FaceDetectorYN_create(weights, "", (0, 0))
weights = "onnx/face_recognizer_fast.onnx"
face_recognizer = cv2.FaceRecognizerSF_create(weights, "")
height, width, _ = image.shape
face_detector.setInputSize((width, height))
_, faces = face_detector.detect(image)
aligned_faces = []
if faces is not None:
for face in faces:
aligned_face = face_recognizer.alignCrop(image, face)
aligned_faces.append(aligned_face)
for i, aligned_face in enumerate(aligned_faces):
cv2.imshow("aligned_face {:03}".format(i + 1), aligned_face)
cv2.imwrite(os.path.join(directory, "face{:03}.jpg".format(i + 1)), aligned_face)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
执行命令
python generate_aligned_faces.py input.jpg
输入图像(input.jpg)
执行结果
face001.jpg | face002.jpg |
---|---|
提取特征并保存为字典
从面部图像中提取特征并将其保存为特征字典。
源代码
import os
import sys
import argparse
import numpy as np
import cv2
def main():
parser = argparse.ArgumentParser("generate face feature dictionary from an face image")
parser.add_argument("image", help="input face image file path (./<face名>.jpg)")
args = parser.parse_args()
print(args.image)
path = args.image
directory = os.path.dirname(args.image)
if not directory:
directory = os.path.dirname(__file__)
path = os