当前位置:首页 » 《资源分享》 » 正文

Springboot 整合 Java DL4J 实现企业门禁人脸识别系统

9 人参与  2024年10月21日 13:20  分类 : 《资源分享》  评论

点击全文阅读


? 博主简介:历代文学网(PC端可以访问:https://literature.sinhy.com/#/literature?__c=1000,移动端可微信小程序搜索“历代文学”)总架构师,15年工作经验,精通Java编程高并发设计Springboot和微服务,熟悉LinuxESXI虚拟化以及云原生Docker和K8s,热衷于探索科技的边界,并将理论知识转化为实际应用。保持对新技术的好奇心,乐于分享所学,希望通过我的实践经历和见解,启发他人的创新思维。在这里,我希望能与志同道合的朋友交流探讨,共同进步,一起在技术的世界里不断学习成长。

在这里插入图片描述


在这里插入图片描述

Spring Boot 整合 Deeplearning4j 实现企业门禁人脸识别系统

一、引言

在当今数字化时代,企业对于安全性和效率的要求越来越高。传统的门禁系统如钥匙、密码等存在易丢失易被破解等问题。而人脸识别技术作为一种非接触式高效准确的身份验证方式,正逐渐成为企业门禁系统的首选。本文将详细介绍如何使用 Spring Boot 整合 Java Deeplearning4j 实现一个企业门禁人脸识别系统,通过识别员工面部特征实现快速身份验证,提高安全性通行效率

二、神经网络选择

本案例中我们选择使用卷积神经网络(Convolutional Neural NetworkCNN)来实现人脸识别。CNN 是一种专门用于处理图像数据的神经网络,具有以下优点:

能够自动提取图像的特征,减少了人工特征提取的工作量。对图像的平移、旋转、缩放等具有一定的不变性,提高了识别的准确性。可以处理大规模的图像数据,适用于企业门禁系统中可能出现的大量员工面部图像。

选择理由

人脸识别是一个复杂的任务,需要对图像中的面部特征进行准确的提取和识别。CNN 能够自动学习图像的特征,并且在图像识别领域取得了非常好的效果。企业门禁系统需要快速准确地识别员工的面部特征,以提高通行效率。CNN 可以在较短的时间内对图像进行处理,满足企业门禁系统的实时性要求。随着深度学习技术的不断发展,CNN 的性能不断提高,并且有很多成熟的开源框架和工具可以使用,如 Deeplearning4j,使得开发人脸识别系统变得更加容易。

三、数据集格式

数据集来源:我们可以使用公开的人脸识别数据集,如 Labeled Faces in the Wild(LFW)数据集,也可以自己收集企业员工的面部图像构建数据集。数据集格式:数据集通常以图像文件的形式存储,每个图像文件对应一个员工的面部图像。图像文件可以是 JPEG、PNG 等常见的图像格式。为了方便管理和使用数据集,我们可以将图像文件按照员工的编号或姓名进行命名,并将其存储在一个特定的目录中。例如,我们可以创建一个名为“dataset”的目录,然后在该目录下创建多个子目录,每个子目录对应一个员工,子目录中的图像文件即为该员工的面部图像。数据集表格示例
员工编号员工姓名图像文件路径
001张三dataset/001/face1.jpg
001张三dataset/001/face2.jpg
002李四dataset/002/face1.jpg
002李四dataset/002/face2.jpg

四、技术介绍

Spring BootSpring Boot 是一个基于 Spring 框架的快速开发框架,它简化了 Spring 应用的开发过程,使得开发者可以更加专注于业务逻辑的实现。在本案例中,我们使用 Spring Boot 来构建企业门禁系统的后端服务,实现人脸识别的业务逻辑。Deeplearning4jDeeplearning4j 是一个基于 Java 的深度学习框架,它支持多种神经网络模型,如 CNN、循环神经网络(Recurrent Neural NetworkRNN)等。在本案例中,我们使用 Deeplearning4j 来训练和部署人脸识别模型。图像预处理:在进行人脸识别之前,我们需要对图像进行预处理,包括图像的缩放、裁剪、归一化等操作,以提高模型的识别准确性。模型训练:使用 Deeplearning4j 提供的 API,我们可以构建和训练人脸识别模型。在训练过程中,我们需要将数据集分为训练集和测试集,使用训练集对模型进行训练,使用测试集对模型的性能进行评估。模型部署:训练好的模型可以部署到企业门禁系统中,实现人脸识别的功能。在部署过程中,我们需要将模型转换为适合在生产环境中运行的格式,并使用 Spring Boot 提供的 RESTful API 将模型暴露给前端应用。

五、相关Maven 依赖

在使用 Spring Boot 整合 Deeplearning4j 实现企业门禁人脸识别系统时,我们需要添加以下 Maven 依赖:

<dependency>    <groupId>org.deeplearning4j</groupId>    <artifactId>deeplearning4j-core</artifactId>    <version>1.0.0-beta7</version></dependency><dependency>    <groupId>org.deeplearning4j</groupId>    <artifactId>deeplearning4j-nn</artifactId>    <version>1.0.0-beta7</version></dependency><dependency>    <groupId>org.deeplearning4j</groupId>    <artifactId>deeplearning4j-ui</artifactId>    <version>1.0.0-beta7</version></dependency><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

六、代码示例

6.1 图像预处理

import org.deeplearning4j.nn.graph.ComputationGraph;import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;import org.deeplearning4j.nn.transferlearning.FineTuneConfiguration;import org.deeplearning4j.nn.transferlearning.TransferLearning;import org.deeplearning4j.zoo.ZooModel;import org.deeplearning4j.zoo.model.VGG16;import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;import org.nd4j.linalg.factory.Nd4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;public class ImagePreprocessor {    private static final Logger logger = LoggerFactory.getLogger(ImagePreprocessor.class);    public static double[] preprocessImage(String imagePath) {        try {            BufferedImage image = ImageIO.read(new File(imagePath));            int width = 224;            int height = 224;            BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);            resizedImage.getGraphics().drawImage(image, 0, 0, width, height, null);            double[] pixels = new double[width * height * 3];            for (int y = 0; y < height; y++) {                for (int x = 0; x < width; x++) {                    int argb = resizedImage.getRGB(x, y);                    int r = (argb >> 16) & 0xff;                    int g = (argb >> 8) & 0xff;                    int b = argb & 0xff;                    pixels[y * width * 3 + x * 3] = r / 255.0;                    pixels[y * width * 3 + x * 3 + 1] = g / 255.0;                    pixels[y * width * 3 + x * 3 + 2] = b / 255.0;                }            }            DataNormalization scaler = new ImagePreProcessingScaler(0, 1);            scaler.transform(Nd4j.create(pixels));            return pixels;        } catch (IOException e) {            logger.error("Error preprocessing image: {}", e.getMessage());            return null;        }    }}

这段代码实现了对图像的预处理功能,包括图像的缩放、归一化等操作。首先,我们使用ImageIO读取图像文件,并将其缩放到指定的大小。然后,我们将图像的像素值转换为double类型,并进行归一化处理,使得像素值在 0 到 1 之间。

6.2 模型训练

import org.deeplearning4j.nn.graph.ComputationGraph;import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;import org.deeplearning4j.nn.transferlearning.FineTuneConfiguration;import org.deeplearning4j.nn.transferlearning.TransferLearning;import org.deeplearning4j.zoo.ZooModel;import org.deeplearning4j.zoo.model.VGG16;import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;import org.nd4j.linalg.factory.Nd4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.File;import java.util.ArrayList;import java.util.List;public class FaceRecognitionTrainer {    private static final Logger logger = LoggerFactory.getLogger(FaceRecognitionTrainer.class);    public static ComputationGraph trainModel(String datasetPath, int numClasses) {        try {            // 加载预训练的 VGG16 模型            ZooModel zooModel = VGG16.builder().build();            ComputationGraph vgg16 = (ComputationGraph) zooModel.initPretrained();            // 设置微调配置            FineTuneConfiguration fineTuneConf = new FineTuneConfiguration.Builder()                   .updater("sgd")                   .learningRate(0.001)                   .seed(123)                   .build();            // 进行迁移学习            ComputationGraph model = new TransferLearning.GraphBuilder(vgg16)                   .fineTuneConfiguration(fineTuneConf)                   .setFeatureExtractor("fc2")                   .removeVertexKeepConnections("predictions")                   .addLayer("predictions",                            org.deeplearning4j.nn.conf.layers.OutputLayer.builder()                                   .nIn(4096)                                   .nOut(numClasses)                                   .activation("softmax")                                   .build())                   .build();            // 加载数据集            List<double[]> images = new ArrayList<>();            List<Integer> labels = new ArrayList<>();            File datasetDir = new File(datasetPath);            for (File employeeDir : datasetDir.listFiles()) {                int label = Integer.parseInt(employeeDir.getName());                for (File imageFile : employeeDir.listFiles()) {                    double[] pixels = ImagePreprocessor.preprocessImage(imageFile.getAbsolutePath());                    if (pixels!= null) {                        images.add(pixels);                        labels.add(label);                    }                }            }            // 创建数据集迭代器            DataSetIterator iterator = new FaceRecognitionDataSetIterator(images, labels);            // 训练模型            model.fit(iterator);            return model;        } catch (Exception e) {            logger.error("Error training model: {}", e.getMessage());            return null;        }    }}

这段代码实现了对人脸识别模型的训练功能。首先,我们加载预训练的 VGG16 模型,并设置微调配置。然后,我们使用迁移学习的方法,将预训练的模型进行微调,以适应人脸识别的任务。接着,我们加载数据集,并创建数据集迭代器。最后,我们使用迭代器对模型进行训练。

6.3 模型部署

import org.deeplearning4j.nn.graph.ComputationGraph;import org.deeplearning4j.zoo.ZooModel;import org.deeplearning4j.zoo.model.VGG16;import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;import org.nd4j.linalg.factory.Nd4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;@SpringBootApplication@RestControllerpublic class FaceRecognitionApplication {    private static final Logger logger = LoggerFactory.getLogger(FaceRecognitionApplication.class);    private ComputationGraph model;    public static void main(String[] args) {        SpringApplication.run(FaceRecognitionApplication.class, args);    }    @PostMapping("/recognize")    public ResponseEntity<String> recognizeFace(@RequestParam("image") MultipartFile imageFile) {        try {            // 加载模型(如果尚未加载)            if (model == null) {                model = FaceRecognitionTrainer.trainModel("dataset", 10);            }            // 保存上传的图像文件            File tempFile = File.createTempFile("temp", ".jpg");            imageFile.transferTo(tempFile);            // 预处理图像            double[] pixels = ImagePreprocessor.preprocessImage(tempFile.getAbsolutePath());            // 进行人脸识别            int prediction = predictFace(pixels);            // 返回识别结果            return new ResponseEntity<>("Recognized face as employee " + prediction, HttpStatus.OK);        } catch (IOException e) {            logger.error("Error recognizing face: {}", e.getMessage());            return new ResponseEntity<>("Error recognizing face", HttpStatus.INTERNAL_SERVER_ERROR);        }    }    private int predictFace(double[] pixels) {        double[] output = model.outputSingle(pixels);        int prediction = Nd4j.argMax(output).getInt(0);        return prediction;    }}

这段代码实现了将训练好的人脸识别模型部署为一个 RESTful API 的功能。我们使用 Spring Boot 构建了一个后端服务,并在服务中加载训练好的模型。当接收到前端应用上传的图像文件时,我们对图像进行预处理,并使用模型进行人脸识别。最后,我们将识别结果返回给前端应用。

七、单元测试

7.1 图像预处理测试

import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertNotNull;public class ImagePreprocessorTest {    @Test    public void testPreprocessImage() {        double[] pixels = ImagePreprocessor.preprocessImage("test.jpg");        assertNotNull(pixels);    }}

这段代码对图像预处理功能进行了单元测试。我们使用一个测试图像文件,并调用ImagePreprocessor.preprocessImage方法对图像进行预处理。然后,我们检查返回的像素数组是否不为空。

7.2 模型训练测试

import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertNotNull;public class FaceRecognitionTrainerTest {    @Test    public void testTrainModel() {        ComputationGraph model = FaceRecognitionTrainer.trainModel("dataset", 10);        assertNotNull(model);    }}

这段代码对模型训练功能进行了单元测试。我们使用一个测试数据集,并调用FaceRecognitionTrainer.trainModel方法对模型进行训练。然后,我们检查返回的模型是否不为空。

7.3 模型部署测试

import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.mock.web.MockMultipartFile;import java.io.FileInputStream;import java.io.IOException;import static org.junit.jupiter.api.Assertions.assertEquals;@SpringBootTestpublic class FaceRecognitionApplicationTest {    @Test    public void testRecognizeFace() throws IOException {        FaceRecognitionApplication application = new FaceRecognitionApplication();        FileInputStream fis = new FileInputStream("test.jpg");        MockMultipartFile imageFile = new MockMultipartFile("image", "test.jpg", "image/jpeg", fis);        ResponseEntity<String> response = application.recognizeFace(imageFile);        assertEquals(HttpStatus.OK, response.getStatusCode());    }}

这段代码对模型部署功能进行了单元测试。我们使用一个测试图像文件,并模拟前端应用上传图像文件的请求。然后,我们检查返回的响应状态码是否为 200(OK)

八、预期输出

图像预处理:经过图像预处理后,图像的像素值应该在 0 到 1 之间,并且图像的大小应该符合模型的输入要求。模型训练:在模型训练过程中,我们可以观察到模型的损失函数和准确率的变化情况。随着训练的进行,损失函数应该逐渐减小,准确率应该逐渐提高。模型部署:当我们上传一张员工的面部图像时,后端服务应该能够快速准确地识别出该员工的身份,并返回相应的识别结果。

九、参考资料文献

Deeplearning4j 官方文档Spring Boot 官方文档卷积神经网络介绍人脸识别技术介绍

点击全文阅读


本文链接:http://zhangshiyu.com/post/174923.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1