阿里云高校计划视觉AI五天训练营教程 Day 2 - 身份证识别系统搭建

简介: 借助阿里云视觉开放平台OCR实现身份证识别系统

初始界面

image.png

项目结构

SpringBootApplication——SpringBoot启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class IdCardorcApplication {
    public static void main(String[] args) {
        SpringApplication.run(IdCardorcApplication.class, args);
    }
}

MainController——控制进程

异常情况下clear

if (faceImages.size() != backImages.size()) {
    faceImages.clear();
    backImages.clear();
    faceResults.clear();
    backResults.clear();
    }

刷新页面重新加载已识别结果

 if (!CollectionUtils.isEmpty(faceImages) && faceImages.size() == backImages.size()) {
        model.addAttribute("faceImage", faceImages.get(faceImages.size() - 1));
        model.addAttribute("faceResult", faceResults.get(faceResults.size() - 1));
        model.addAttribute("backImage", backImages.get(backImages.size() - 1));
        model.addAttribute("backResult", backResults.get(backResults.size() - 1));
    }

上传文件判定

public String upload(@RequestParam("face") MultipartFile face, @RequestParam("back") MultipartFile back,
                     RedirectAttributes redirectAttributes) {
    if (face.isEmpty() || back.isEmpty()) {
        redirectAttributes.addFlashAttribute("messages", "请选择一个文件进行上传。");
        return "redirect:/index";
    }
    String errorMessages = null;
    Path dir = Paths.get(uploadDir);
    if (!Files.exists(dir)) {
        try {
            Files.createDirectories(dir);
        } catch (IOException e) {
            e.printStackTrace();
            errorMessages += e.getMessage() + "\n";
        }
    }
    try {
        if (!face.isEmpty()) {
            String filename = saveFile(face);
            Map<String, String> faceResult = ocrService.RecognizeIdCard(uploadDir + filename, "face");
            faceImages.add("/images/" + filename);
            faceResults.add(faceResult);
        }
        if (!back.isEmpty()) {
            String filename = saveFile(back);
            Map<String, String> faceResult = ocrService.RecognizeIdCard(uploadDir + filename, "back");
            backImages.add("/images/" + filename);
            backResults.add(faceResult);
        }
    } catch (Exception e) {
        e.printStackTrace();
        errorMessages += e.getMessage() + "\n";
    }
    if (StringUtils.isNoneBlank(errorMessages)) {
        redirectAttributes.addFlashAttribute("messages", errorMessages);
    }
    return "redirect:/index";
}

存储逻辑

public String saveFile(MultipartFile file) {
    String filename = UUID.randomUUID().toString() + "."
            + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
    Path path = Paths.get(uploadDir + filename);
    System.out.println(faceResults);
    try {
        Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        return null;
    }
    return filename;
}

OcrService——通过SDK调用视觉开放平台的OCR

初始化config

private void init() throws Exception {
    Config config = new Config();
    config.endpointType = "access_key";
    config.regionId = "cn-shanghai";
    config.accessKeyId = accessKeyId;
    config.accessKeySecret = accessKeySecret;
    config.endpoint = "ocr.cn-shanghai.aliyuncs.com";

    orcClient = new Client(config);
    runtimeOptions = new RuntimeOptions();
}

调用逻辑

public Map<String, String> RecognizeIdCard(String fielpath, String side) throws Exception {
    RecognizeIdentityCardAdvanceRequest request = new RecognizeIdentityCardAdvanceRequest();
    request.imageURLObject = Files.newInputStream(Paths.get(fielpath));
    request.side = side;
    RecognizeIdentityCardResponse response = orcClient.recognizeIdentityCardAdvance(request, runtimeOptions);
    return "face".equals(side) ?
            JSON.parseObject(JSON.toJSONString(response.data.frontResult), new TypeReference<Map<String, String>>(){})
            : JSON.parseObject(JSON.toJSONString(response.data.backResult), new TypeReference<Map<String, String>>(){});
}

index.html——前端模板

上传界面

<form method="post" th:action="@{/upload}" enctype="multipart/form-data">
    <div class="row">
        <div class="col-sm-4">
            <div class="input-group">
                <input id="location" class="form-control" onclick="$('#i-face').click();">
                <label class="input-group-btn">
                    <input type="button" id="i-check" value="上传人像面" class="btn btn-primary" onclick="$('#i-face').click();">
                </label>
            </div>
        </div>
        <input type="file" name="face" id="i-face" accept=".jpg, .png, .jpeg" onchange="$('#location').val($('#i-face').val());" style="display: none">
        <div class="col-sm-4">
            <div class="input-group">
                <input id="locationf" class="form-control" onclick="$('#i-back').click();">
                <label class="input-group-btn">
                    <input type="button" id="i-checkb" value="上传国徽面" class="btn btn-primary" onclick="$('#i-back').click();">
                </label>
            </div>
        </div>
        <input type="file" name="back" id="i-back" accept=".jpg, .png, .jpeg" onchange="$('#locationf').val($('#i-back').val());" style="display: none">
        <div class="col-sm-4">
            <button type="submit" class="btn btn-primary form-control">开始识别</button>
        </div>
    </div>
</form>

识别后展示

<div class="row" style="margin-top: 38px;">
    <div class="col-md-12 mx-auto">
        <div class="row">
            <div class="col-sm-4">
                <img th:src="${faceImage}" th:if="faceImage != null" class="img-fluid">
            </div>
            <div class="col-sm-4">
                <img th:src="${backImage}" th:if="backImage != null" class="img-fluid">
            </div>
        </div>
    </div>
</div>
<div class="row" style="margin-top: 38px;">
    <div class="col-md-12 mx-auto" th:if="${faceResult != null}">
        <div class="row">
            <div class="col-sm-4">
                <p><span>姓名: </span><span th:text="${faceResult.name}"></span></p>
                <p><span>性别: </span><span th:text="${faceResult.gender}"></span></p>
                <p><span>民族: </span><span th:text="${faceResult.nationality}"></span></p>
                <p><span>出生日期: </span><span th:text="${faceResult.birthDate}"></span></p>
                <p><span>住址: </span><span th:text="${faceResult.address}"></span></p>
                <p><span>身份证号: </span><span th:text="${faceResult.IDNumber}"></span></p>
            </div>
             <div class="col-sm-4">
                <p><span>签发机关: </span><span th:text="${backResult.issue}"></span></p>
                <p><span>有效日期: </span><span th:text="${backResult.startDate}">-<span th:text="${faceResult.endDate}"></span></span></p>
             </div>
        </div>
    </div>
</div>

application.properties——若干配置文件

server.port=
file.uplaod.path=
aliapi.accessKeyId=
aliapi.accessKeySecret=

pom.xml——若干相关依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.10</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.4.8</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.52</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>ocr</artifactId>
        <version>1.0.3</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>
相关文章
|
3天前
|
人工智能 自然语言处理 Serverless
阿里云函数计算 x NVIDIA 加速企业 AI 应用落地
阿里云函数计算与 NVIDIA TensorRT/TensorRT-LLM 展开合作,通过结合阿里云的无缝计算体验和 NVIDIA 的高性能推理库,开发者能够以更低的成本、更高的效率完成复杂的 AI 任务,加速技术落地和应用创新。
|
6天前
|
机器学习/深度学习 人工智能 数据可视化
首个全自动科学发现AI系统,Transformer作者创业公司Sakana AI推出AI Scientist
【9月更文挑战第11天】Sakana AI公司近日推出全球首个全自动科学发现AI系统——AI Scientist,实现了人工智能在科学研究领域的重大突破。AI Scientist不仅能独立完成从假设提出到实验设计、数据分析及论文撰写的全过程,还能通过模拟评审提升研究成果的质量。该系统已成功应用于机器学习的多个子领域,并产出达到顶级会议标准的论文。尽管其高效性备受赞誉,但也引发了关于研究可信度和潜在风险的讨论。Sakana AI强调,系统具备可追溯的决策过程与严格的评审机制,确保了研究的可靠性和透明度。论文详情参见:[链接]。
24 6
|
12天前
|
人工智能 小程序 Java
【评测】玩转阿里云《10 分钟构建 AI 客服并应用到网站、钉钉或微信中》
本文介绍了使用阿里云百炼大模型在10分钟内构建AI客服,并应用于网站、钉钉或微信中的体验。作者“JavaDog程序狗”详细描述了从搭建到完成的全过程,包括快速上手、遇到的问题及解决方法、定制化需求以及云产品的整体体验。文档清晰易懂,集成过程顺畅,客服支持响应迅速,定制功能满足特定业务需求,总体体验极佳,适合开发者尝试。
87 5
【评测】玩转阿里云《10 分钟构建 AI 客服并应用到网站、钉钉或微信中》
|
12天前
|
人工智能 自然语言处理 算法
|
8天前
|
人工智能 Linux iOS开发
AI超强语音转文本SenseVoice,本地化部署教程!
【9月更文挑战第7天】以下是AI超强语音转文本工具SenseVoice的本地化部署教程:首先确保服务器或计算机满足硬件和软件要求,包括处理器性能、内存及操作系统等。接着从官网下载适合的安装包,并按操作系统进行安装。配置音频输入设备和语言模型后,启动SenseVoice并测试其语音转文本功能。最后根据实际使用情况进行优化调整,并定期更新以获取最新功能。详细步骤需参照官方文档。
|
9天前
|
机器学习/深度学习 人工智能 测试技术
AI计算机视觉笔记二十五:ResNet50训练部署教程
该项目旨在训练ResNet50模型并将其部署到RK3568开发板上。首先介绍了ResNet50网络,该网络由何恺明等人于2015年提出,解决了传统卷积神经网络中的退化问题。项目使用车辆分类数据集进行训练,并提供了数据集下载链接。环境搭建部分详细描述了虚拟环境的创建和所需库的安装。训练过程中,通过`train.py`脚本进行了15轮训练,并可视化了训练和测试结果。最后,项目提供了将模型转换为ONNX和PT格式的方法,以便在RK3568上部署。
|
12天前
|
SQL 人工智能 运维
在阿里云日志服务轻松落地您的AI模型服务——让您的数据更容易产生洞见和实现价值
您有大量的数据,数据的存储和管理消耗您大量的成本,您知道这些数据隐藏着巨大的价值,但是您总觉得还没有把数据的价值变现出来,对吗?来吧,我们用一系列的案例帮您轻松落地AI模型服务,实现数据价值的变现......
68 3
|
11月前
|
人工智能 弹性计算 云栖大会
2023云栖大会 | 阿里云高校计划,助力高校科研与教育加速,让每位中国在校大学生真实受益于普惠算力
10月31日,阿里云在2023杭州云栖大会上宣布一项面向全国高校的重磅计划——阿里云高校计划,助力高校科研与教育加速,让每位中国在校大学生真实受益于普惠算力
853 6
2023云栖大会 | 阿里云高校计划,助力高校科研与教育加速,让每位中国在校大学生真实受益于普惠算力
|
10月前
|
弹性计算 人工智能
什么是阿里云高校计划“云工开物”?
什么是阿里云高校计划“云工开物”?
1968 0
阿里云高校计划服务器用后感
一款让我用完感觉非常顺手的服务器