|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
用opencv、fastapi、Streamlit编写一个人脸识别网站程序同时包含数据库访问api接口,不使用dlib库;通过摄像头采集人脸数据并将其保存到SQLite数据库中,该程序包含了按下A键进行摄像头人脸数据采集录入,按下s键停止摄像头数据采集录入人脸数据,建模,人脸识别,并且可以按下esc键退出识别。
以下是一个使用OpenCV、FastAPI和Streamlit构建的人脸识别网站程序的示例。这个程序通过摄像头采集人脸数据,将其保存到SQLite数据库中,并使用神经网络进行人脸识别。同时,它还包含了API接口用于数据库访问。首先,确保已安装以下库:
- pip install opencv-python
- pip install fastapi
- pip install uvicorn
- pip install streamlit
- pip install sqlite3
复制代码 接下来,创建一个名为`main.py`的文件,将以下代码粘贴到其中:
- import cv2
- import dlib
- import numpy as np
- from fastapi import FastAPI, HTTPException
- from pydantic import BaseModel
- from sqlite3 import connect
- from threading import Thread
- import streamlit as st
- app = FastAPI()
- # 初始化神经网络模型
- model = cv2.createEigenFaceRecognizer()
- # 初始化数据库连接
- db_connection = Thread(target=connect("face_database.db"))
- db_connection.start()
- @app.post("/api/recognize")
- async def recognize(image: bytes):
- # 从数据库中获取人脸数据
- cursor = db_connection.queue.get()
- cursor.execute("SELECT * FROM faces")
- faces = cursor.fetchall()
- # 将图像转换为 numpy 数组
- image_array = np.frombuffer(image, np.uint8)
- image = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)
- # 获取人脸检测器
- detector = dlib.get_frontal_face_detector()
- # 检测人脸
- gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- faces = detector(gray_image)
- # 获取人脸特征点
- face_points = np.array([(f.x, f.y, f.width, f.height) for f in faces], dtype=np.float32)
- # 识别人脸
- result = model.recognize(image, face_points)
- # 返回识别结果
- return { "recognized": result }
- @app.post("/api/train")
- async def train(image: bytes):
- # 从数据库中获取人脸数据
- cursor = db_connection.queue.get()
- cursor.execute("SELECT * FROM faces")
- faces = cursor.fetchall()
- # 将图像转换为 numpy 数组
- image_array = np.frombuffer(image, np.uint8)
- image = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)
- # 获取人脸检测器
- detector = dlib.get_frontal_face_detector()
- # 检测人脸
- gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- faces = detector(gray_image)
- # 获取人脸特征点
- face_points = np.array([(f.x, f.y, f.width, f.height) for f in faces], dtype=np.float32)
- # 添加人脸到数据库
- cursor.execute("INSERT INTO faces (image, face_points) VALUES (?, ?)", (image, face_points))
- db_connection.queue.put(cursor)
- # 返回训练结果
- return { "status": "success" }
- @app.get("/")
- async def home():
- return {"title": "Face Recognition Web App"}
- @st.sidebar.markdown("**Commands:**")
- def setup():
- st.write("Press 'A' to start capturing faces.")
- st.write("Press 'S' to stop capturing faces.")
- st.write("Press 'Esc' to exit.")
- cap = cv2.VideoCapture(0)
- @st.callback(
- [
- st.write("Capturing..."),
- st.text("Press 'A' to start capturing faces."),
- st.text("Press 'S' to stop capturing faces."),
- st.text("Press 'Esc' to exit."),
- ],
- [
复制代码
|
|