视觉AI训练营 DAY2 身份证识别系统搭建

本文涉及的产品
OCR统一识别,每月200次
文档理解,免费额度 各100页
教育场景识别,教育场景识别 200次/月
简介: 该项目是通过阿里云自主研发的sdk,实现图片识别功能通过上传身份证照片可以显示出身份证的信息基于springboot实现

本项目使用了Spring boot的框架
阿里云视觉智能开放平台:https://vision.aliyun.com/
这里提供了两个SDK
https://help.aliyun.com/document_detail/144481.html
https://help.aliyun.com/document_detail/153132.html
整体是一个接口调用,前端上传数据,服务器端配置参数向阿里的开放接口发送请求,然后得到返回结果,再处理数据返回到前端页面

<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>身份证识别</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-xl-12 mx-auto">
                <h1>身份证识别</h1>
                <div class="col-sm-12">
                    <p th:text="${messages}" th:if="${messages != null}" class="alert alert-info"></p>
                </div>
                <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>
        </div>

        <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>
    </div>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</html>

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class MainController {

    @Value("${file.uplaod.path}")
    private String uploadDir;
    @Autowired
    private OcrService ocrService;

    private List<String> faceImages = new ArrayList<>();
    private List<String> backImages = new ArrayList<>();
    private List<Map<String, String>> faceResults = new ArrayList<>();
    private List<Map<String, String>> backResults = new ArrayList<>();

    @RequestMapping("/index")
    public String index(Model model) {
        if (faceImages.size() != backImages.size()) {
            clearAllList();
        }
        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));
        }
        return "index";
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "test";
    }

    @PostMapping("/upload")
    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";
    }

    private void clearAllList() {
        faceImages.clear();
        backImages.clear();
        faceResults.clear();
        backResults.clear();
    }

    public String saveFile(MultipartFile file) {
        String filename = UUID.randomUUID().toString() + "."
                + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        Path path = Paths.get(uploadDir + filename);
        try {
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            return null;
        }
        return filename;
    }
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.ocr.Client;
import com.aliyun.ocr.models.Config;
import com.aliyun.ocr.models.RecognizeIdentityCardAdvanceRequest;
import com.aliyun.ocr.models.RecognizeIdentityCardResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

@Service
public class OcrService {

    private Client orcClient;
    private RuntimeOptions runtimeOptions;

    @Value("${aliapi.accessKeyId}")
    private String accessKeyId;
    @Value("${aliapi.accessKeySecret}")
    private String accessKeySecret;

    @PostConstruct
    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>>(){});
    }
}
相关文章
|
6天前
|
机器学习/深度学习 人工智能 数据可视化
首个全自动科学发现AI系统,Transformer作者创业公司Sakana AI推出AI Scientist
【9月更文挑战第11天】Sakana AI公司近日推出全球首个全自动科学发现AI系统——AI Scientist,实现了人工智能在科学研究领域的重大突破。AI Scientist不仅能独立完成从假设提出到实验设计、数据分析及论文撰写的全过程,还能通过模拟评审提升研究成果的质量。该系统已成功应用于机器学习的多个子领域,并产出达到顶级会议标准的论文。尽管其高效性备受赞誉,但也引发了关于研究可信度和潜在风险的讨论。Sakana AI强调,系统具备可追溯的决策过程与严格的评审机制,确保了研究的可靠性和透明度。论文详情参见:[链接]。
24 6
|
26天前
|
存储 消息中间件 人工智能
AI大模型独角兽 MiniMax 基于阿里云数据库 SelectDB 版内核 Apache Doris 升级日志系统,PB 数据秒级查询响应
早期 MiniMax 基于 Grafana Loki 构建了日志系统,在资源消耗、写入性能及系统稳定性上都面临巨大的挑战。为此 MiniMax 开始寻找全新的日志系统方案,并基于阿里云数据库 SelectDB 版内核 Apache Doris 升级了日志系统,新系统已接入 MiniMax 内部所有业务线日志数据,数据规模为 PB 级, 整体可用性达到 99.9% 以上,10 亿级日志数据的检索速度可实现秒级响应。
AI大模型独角兽 MiniMax 基于阿里云数据库 SelectDB 版内核 Apache Doris 升级日志系统,PB 数据秒级查询响应
|
1月前
|
人工智能 自然语言处理 云计算
iOS迎来AI升级:揭秘Apple全新“智能”系统
iOS迎来AI升级:揭秘Apple全新“智能”系统
iOS迎来AI升级:揭秘Apple全新“智能”系统
|
21天前
|
存储 人工智能 自然语言处理
利用AI技术实现智能客服系统
【8月更文挑战第27天】本文将介绍如何利用人工智能(AI)技术构建一个智能客服系统,以提高客户服务效率和质量。我们将从需求分析、系统设计、功能实现等方面进行详细阐述,并通过实际代码示例展示如何实现一个简单的智能客服系统。
|
24天前
|
分布式计算 搜索推荐 物联网
大数据及AI典型场景实践问题之通过KafKa+OTS+MaxCompute完成物联网系统技术重构如何解决
大数据及AI典型场景实践问题之通过KafKa+OTS+MaxCompute完成物联网系统技术重构如何解决
|
24天前
|
人工智能 分布式计算 架构师
大数据及AI典型场景实践问题之基于MaxCompute构建Noxmobi全球化精准营销系统如何解决
大数据及AI典型场景实践问题之基于MaxCompute构建Noxmobi全球化精准营销系统如何解决
|
28天前
|
机器学习/深度学习 人工智能 监控
探索视觉AI:超越计算机视觉的边界
【8月更文挑战第20天】
40 2
|
16天前
|
人工智能 监控 安全
AI计算机视觉笔记十三:危险区域识别系统
本文介绍了如何在 IPC 监控视频中实现区域入侵检测,通过 YOLOv5 和 ByteTrack 实现人物检测与多目标跟踪。系统能在检测到人员进入预设的危险区域时发出警报,保障安全。主要步骤包括:1)使用 YOLOv5 识别人物;2)使用 ByteTrack 进行多目标跟踪;3)利用射线法判断物体是否进入禁区内。项目基于 Python 开发,使用海思、君正、RK 等摄像头模组,代码已在 RV1126 上验证,计划移植至 RK3568 平台。项目结构清晰,包含模型训练、跟踪算法及图形化界面展示等功能。
|
17天前
|
机器学习/深度学习 人工智能 自然语言处理
AI技术在智能客服系统中的应用
【8月更文挑战第31天】本文将介绍AI技术在智能客服系统中的应用,包括自然语言处理、机器学习和深度学习等方面的知识。我们将通过一个简单的代码示例,展示如何使用Python和TensorFlow库构建一个简单的智能客服系统。通过阅读本文,您将了解到AI技术如何改变传统客服行业,提高客户满意度和企业效率。
|
27天前
|
机器学习/深度学习 人工智能 PyTorch
"揭秘AI绘画魔法:一键生成梦幻图像,稳定扩散模型带你开启视觉奇迹之旅!"
【8月更文挑战第21天】稳定扩散(Stable Diffusion)是基于深度学习的模型,能根据文本生成高质量图像,在AI领域备受瞩目,革新了创意产业。本文介绍稳定扩散模型原理及使用步骤:环境搭建需Python与PyTorch;获取并加载预训练模型;定义文本描述后编码成向量输入模型生成图像。此外,还可调整参数定制图像风格,或使用特定数据集进行微调。掌握这项技术将极大提升创意表现力。
31 0