【免费】人脸识别 智能门禁系统(深度学习+OpenCV DNN+FastAPI+Vue3) 锋哥原创出品,必属精品

大家好,我是Java1234_小锋老师,分享一套锋哥原创的人脸识别 智能门禁系统(深度学习+OpenCV DNN+FastAPI+Vue3)

项目介绍

出入控制是安防体系中的基础环节。长期以来,IC 卡、密码键盘和门禁钥匙在企事业单位中广泛使用,但存在卡片易丢失、密码易泄露、冒用难追溯等问题。尤其在人员流动性较高的园区与写字楼场景中,卡片补办成本高,权限变更往往滞后,管理方难以及时掌握“谁在何时从何处进出”的完整信息。近年来,深度学习推动生物特征识别技术快速落地,人脸识别因采集成本低、通行体验好、可与视频监控联动,成为智能门禁的主流方案之一。

在智慧园区和数字化办公场景中,门禁系统不仅要完成“开门”,还要完成“管人、管设备、管权限、管记录、管告警”的闭环。将人脸识别与后台管理系统结合,能够把身份核验、权限策略和安全事件处理统一到同一平台,提升管理效率与安全水平。对组织管理者而言,系统可以支撑考勤辅助、访客管控与安全审计;对通行者而言,非接触式识别减少了掏卡刷卡的繁琐步骤,也降低了交叉接触风险。因此,研究并实现一套结构清晰、技术路线明确、可演示可扩展的带人脸识别智能门禁系统,具有明确的工程意义与教学价值。

本课题选择 OpenCV DNN、YuNet 与 SFace 作为识别技术路线,结合 Python、FastAPI 与 Vue3 完成系统开发。该方案无需依赖商业闭源 SDK,模型文件体积较小,部署门槛低,适合本科毕业设计在有限硬件条件下完成可运行原型,同时又能体现深度学习在实际工程中的应用方式。与单纯调用云端识别 API 相比,本地化推理更有利于保护人脸生物特征数据,也便于在论文中完整展示算法调用链路与系统设计细节。

从人才培养角度看,本课题横跨软件工程、数据库原理、Web 开发与计算机视觉等多个知识模块,要求学生把课堂理论转化为可运行系统,锻炼需求分析、模块划分、接口设计、测试验证和论文表达能力,符合本科毕业设计“综合训练”的定位。

源码下载

链接: https://pan.baidu.com/s/1XF5Bj0hyipdAXhTywhfmmg?pwd=1234
提取码: 1234

系统展示

核心代码

"""
OpenCV DNN 人脸识别引擎
使用 YuNet 人脸检测 + SFace 特征提取
"""
import os
from typing import Optional, Tuple

import cv2
import numpy as np

from app.core.config import settings


class FaceEngine:
    """人脸识别引擎单例类"""

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        if self._initialized:
            return
        self.detector = None
        self.recognizer = None
        self._initialized = True

    def load_models(self):
        """
        加载 YuNet 和 SFace 模型
        """
        models_dir = settings.MODELS_DIR
        os.makedirs(models_dir, exist_ok=True)
        yunet_path = os.path.join(models_dir, "face_detection_yunet_2023mar.onnx")
        sface_path = os.path.join(models_dir, "face_recognition_sface_2021dec.onnx")

        if not os.path.exists(yunet_path) or not os.path.exists(sface_path):
            raise FileNotFoundError(f"模型文件不存在,请先运行 scripts/download_models.py 下载模型")

        self.detector = cv2.FaceDetectorYN.create(yunet_path, "", (320, 320), 0.6, 0.3, 5000)
        self.recognizer = cv2.FaceRecognizerSF.create(sface_path, "")
        print("[FaceEngine] 模型加载成功")

    def detect_largest_face(self, image: np.ndarray) -> Optional[np.ndarray]:
        """
        检测图像中最大的人脸
        Args:
            image: BGR格式图像
        Returns:
            人脸检测结果行向量 [x,y,w,h,...] 或 None
        """
        if self.detector is None:
            self.load_models()
        h, w = image.shape[:2]
        self.detector.setInputSize((w, h))
        _, faces = self.detector.detect(image)
        if faces is None or len(faces) == 0:
            return None
        areas = faces[:, 2] * faces[:, 3]
        return faces[np.argmax(areas)]

    def extract_feature(self, image: np.ndarray, face: np.ndarray) -> Optional[np.ndarray]:
        """
        提取人脸128维特征向量
        Args:
            image: BGR格式图像
            face: 人脸检测结果
        Returns:
            128维特征向量
        """
        if self.recognizer is None:
            self.load_models()
        aligned = self.recognizer.alignCrop(image, face)
        feature = self.recognizer.feature(aligned)
        return feature.flatten()

    def process_image(self, image: np.ndarray) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
        """
        检测并提取特征(一步完成)
        Args:
            image: BGR格式图像
        Returns:
            (特征向量, 人脸框) 或 (None, None)
        """
        face = self.detect_largest_face(image)
        if face is None:
            return None, None
        feature = self.extract_feature(image, face)
        return feature, face

    @staticmethod
    def cosine_similarity(feat1: np.ndarray, feat2: np.ndarray) -> float:
        """
        计算两个特征向量的余弦相似度
        """
        norm1 = np.linalg.norm(feat1)
        norm2 = np.linalg.norm(feat2)
        if norm1 == 0 or norm2 == 0:
            return 0.0
        return float(np.dot(feat1, feat2) / (norm1 * norm2))

    @staticmethod
    def decode_image(image_bytes: bytes) -> np.ndarray:
        """将字节解码为OpenCV图像"""
        nparr = np.frombuffer(image_bytes, np.uint8)
        return cv2.imdecode(nparr, cv2.IMREAD_COLOR)


face_engine = FaceEngine()
<template>
  <div class="page-container">
    <div class="page-header"><h2>我的人脸</h2></div>
    <div class="face-grid">
      <div v-for="f in faceList" :key="f.id" class="face-card">
        <el-image :src="f.image_url" fit="cover" style="width:160px;height:160px;border-radius:12px" />
        <div class="face-info">
          <el-tag v-if="f.is_primary" type="success" size="small">主图</el-tag>
          <span v-if="f.quality_score">质量: {{ f.quality_score }}</span>
          <span>{{ f.create_time }}</span>
        </div>
      </div>
      <el-empty v-if="!faceList.length" description="暂无录入人脸,请联系管理员录入" />
    </div>
  </div>
</template>

<script setup>
/** 我的人脸页面(普通用户) */
import { ref, onMounted } from 'vue'
import { faceApi } from '@/api'

const faceList = ref([])
onMounted(async () => {
  const res = await faceApi.list()
  faceList.value = res.data
})
</script>

<style scoped>
.face-grid { display: flex; flex-wrap: wrap; gap: 20px; }
.face-card { background: #fff; padding: 16px; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); text-align: center; }
.face-info { margin-top: 8px; display: flex; flex-direction: column; gap: 4px; font-size: 13px; color: #909399; }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值