阿里云高校计划视觉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>
相关文章
|
4月前
|
人工智能 新制造
TsingtaoAI受邀参加宁波AI海曙科创训练营并分享技术落地实践
10月12日至15日,由宁波市海曙区组织部主办的AI海曙科创训练营在宁波成功举办。作为受邀企业代表,TsingtaoAI团队深入参与了多项活动,与政府领导、行业专家及科创企业代表围绕AI技术在制造业、成果转化等领域的实际应用展开交流,用真实案例诠释了“技术扎根产业”的价值逻辑。
138 2
|
11月前
|
人工智能 计算机视觉
HarmonyOS NEXT AI基础视觉服务-背景替换
这是一个基于AI基础视觉服务的背景替换案例,通过调用设备相册选择图片并智能分割主体,支持动态更换背景颜色。主要步骤包括:1) 导入模块与定义组件;2) 实现图片选择与格式转换;3) 使用`subjectSegmentation.doSegmentation`接口完成主体分割;4) 通过随机RGB值实现背景色动态更换。代码结构清晰,功能完整,适合学习AI图像处理技术。
HarmonyOS NEXT AI基础视觉服务-背景替换
|
11月前
|
存储 人工智能 数据安全/隐私保护
HarmonyOS NEXT AI基础视觉服务-人脸对比
这是一套基于AI基础视觉服务实现的人脸对比系统,用户可通过调用设备相册选择两张图片,系统将提取人脸特征并计算相似度,最终以结构化数据形式展示对比结果(如相似度值和是否为同一人)。代码涵盖模块导入、双图选择、图像处理、人脸对比核心逻辑及UI界面构建,支持异常处理与权限管理,确保功能稳定性和兼容性。适配场景包括身份验证、人脸匹配等,具有较高的实用价值。
HarmonyOS NEXT AI基础视觉服务-人脸对比
|
5月前
|
机器学习/深度学习 人工智能 自然语言处理
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
418 10
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
|
10月前
|
人工智能 搜索推荐 API
AI赋能大学计划·大模型技术与应用实战学生训练营——华东师范大学站圆满结营
4月24日,由中国软件行业校园招聘与实习公共服务平台携手阿里魔搭社区共同举办的AI赋能大学计划·大模型技术与产业趋势高校行大模型应用实战学生训练营——华东师范大学站圆满结营。
441 2
|
11月前
|
人工智能 计算机视觉
HarmonyOS NEXT AI基础视觉服务-人脸识别
这是一个基于AI基础视觉服务的人脸识别案例,通过调用设备相册选择图片,利用MediaLibraryKit、ImageKit和CoreVisionKit等模块完成图像处理与人脸检测,并展示结构化结果。核心功能包括:相册访问授权、图像数据转换、人脸位置及特征点检测,最终以弹窗形式输出检测信息。代码涵盖模块导入、功能实现与UI构建,适合学习AI视觉应用开发流程。
|
5月前
|
人工智能 自然语言处理 架构师
AI 自动化智能体训练营
本课程专为想提升效率、探索副业的职场人、创业者及内容创作者设计,零基础可学。4周系统掌握AI生成文案、PPT、图表,自动化运营与多平台分发,打造24小时赚钱智能体,实现降本增效与个人变现双赢。
|
机器学习/深度学习 新零售 人工智能
阿里云高校计划视觉AI五天训练营 Day 1——视觉应用探索
在这个人工智能已经普及的时代,各行各业都充斥着AI的身影。大部分人认为人工智能起点高,入门难,想要使用AI服务又无法独立完成编写,开发者可以通过阿里云视觉平台提供的通用且标准化的接入方式,快速接入及使用阿里云视觉平台提供的包括人脸人体、文字识别、商品理解、内容安全、图像识别、图像生产、分割抠图、视觉搜索、目标检测、图像分析处理、视频理解、视频生产、视频分割13个类目多个API能力,为其提供高易用、普惠的视觉API服务,帮助企业快速建立视觉智能技术的应用能力的综合性视觉AI能力平台。
1468 0
阿里云高校计划视觉AI五天训练营 Day 1——视觉应用探索
|
JSON 人工智能 API
阿里云高校计划视觉AI五天训练营 Day5
关爱环境卫生,人人有责,怎么快速识别垃圾的种类扔进相应的垃圾桶中,那接下来看如何快速识别垃圾分类。
阿里云高校计划视觉AI五天训练营 Day5
|
人工智能 达摩院 文字识别
阿里云视觉智能开放平台2021首秀——趣味视觉AI训练营限时免费报名中!
趣味视觉AI训练营限时报名中!!!新功能,新算法,阿里云视觉智能开发平台产品专家带你体验视觉AI平台新能力,0代码体验AI能力,一键生成可视化AI结果。本次训练营带来更多的视觉AI应用场景,达摩院算法专家分享图像分割的算法基础知识,演示人物背景替换实现过程,体验热门算法-人物动漫化。调用视觉AI能力体验AI带来的趣味性。
阿里云视觉智能开放平台2021首秀——趣味视觉AI训练营限时免费报名中!