首页 > 其他分享 >调用百度API实现身份证车牌号识别

调用百度API实现身份证车牌号识别

时间:2022-11-04 08:45:56浏览次数:53  
标签:jFrame String 车牌号 token API new import public 百度

 

 首先要按照百度文档中下载三个类并且导入进去,并且获取token

safe_token(获取token)

package jar;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class safe_token {
    public static void main(String[] args) {
        getAuth();
    }

    /**
     * 获取权限token
     * @return 返回示例:
     * {
     * "access_token": "**********",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "Qk4dy6aMSYbBG8FGqmPYRM1p";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "**********";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }
}

 

interface:

package Jframe;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import jar.FileUtil;
import jar.HttpUtil;

import java.net.URLEncoder;



public class Interface {



    public static void main(String[] args) {
//        identify();
//        car();
        }
        public static String identify(String path){
            String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
            String name="姓名:";
            String minzu="民族";
            String sex="性别:";
            String card="身份证号:";
            try {
                // 本地文件路径
//                String filePath = "C:/Users/LLL/Desktop/2.jpg";
                byte[] imgData = FileUtil.readFileByBytes(path);
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");
                String param = "id_card_side=" + "front" + "&image=" + imgParam;
                // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
                String accessToken = "******";
                String result = HttpUtil.post(url, accessToken, param);
                JSONObject jsonObject=JSONObject.parseObject(result);
                JSONObject result1=jsonObject.getJSONObject("words_result");
                name+=(String)result1.getJSONObject("姓名").get("words");
                minzu+=(String)result1.getJSONObject("民族").get("words");
                sex+=(String)result1.getJSONObject("性别").get("words");
                card+=(String)result1.getJSONObject("公民身份号码").get("words");
//                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
//            return null;
//            System.out.println("出错了");
            return name+","+minzu+","+sex+","+card;
    }

    public static String car(String path){
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";
        String color="";
        String card="";
        try {
            // 本地文件路径
//            String filePath = "C:/Users/LLL/Desktop/3.png";
            byte[] imgData = FileUtil.readFileByBytes(path);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = "********";
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject jsonObject=JSONObject.parseObject(result);
            JSONObject result1=jsonObject.getJSONObject("words_result");
            color=(String)result1.getString("color");
            card=(String)result1.getString("number");
            System.out.println(color+"      "+card);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "颜色:"+color+"车牌号:"+card;
    }


}

 

 

jframe:

package Jframe;

import com.baidu.aip.imageclassify.AipImageClassify;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class jframe {

 /*   public static final String APP_ID = "***********";

    public static final String API_KEY = "*************";

    public static final String SECRET_KEY = "*******";*/
    public static String file1;
    public static void main(String[] args) {

        JFrame jFrame=new JFrame("图片识别系统");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setLayout(null);
        //初始化界面
        jFrame.setSize(2560,2500);

        JRadioButton jRadioButton=new JRadioButton("身份证识别",true);
        JRadioButton jRadioButton1=new JRadioButton("车牌识别");
        ButtonGroup buttonGroup=new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton);


//        jFrame.setLocation(320,240);
        JFileChooser jFileChooser=new JFileChooser();
        jFileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return true;
            }

            @Override
            public String getDescription() {
                return null;
            }
        });
        // 创建登录按钮
        JButton SCButton = new JButton("上传图片");
        JLabel label3 =new JLabel("");
        label3.setBounds(300,100,200,50);
        SCButton.setBounds(50, 225, 100, 50);
        JLabel jLabel = new JLabel();
        ImageIcon i = new ImageIcon("");
        //设置ImageIcon
        jLabel.setIcon(i);
        //label的大小设置为ImageIcon,否则显示不完整
        JButton WLButton=new JButton("上传网络验证");
        WLButton.setBounds(SCButton.getX()+200,SCButton.getY(),150,50);
        SCButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
//                JOptionPane.showConfirmDialog(null, "上传图片");
                int returnVal = jFileChooser.showOpenDialog(jFrame);
                File file=jFileChooser.getSelectedFile();
                if (returnVal==JFileChooser.APPROVE_OPTION){
                    JOptionPane.showMessageDialog(jFrame, "计划打开文件:" + file.getAbsolutePath());
                    file1=file.getAbsolutePath();
                    file1.replaceAll("\\\\", "/");
                    ImageIcon imageIcon=new ImageIcon(file1);
                    Image image=imageIcon.getImage();
                    image=image.getScaledInstance(450,300,Image.SCALE_AREA_AVERAGING);
                    imageIcon.setImage(image);
                    jLabel.setIcon(imageIcon);
                    jLabel.setBounds(25,25,imageIcon.getIconWidth(),imageIcon.getIconHeight());
                    SCButton.setBounds(50, 50+imageIcon.getIconHeight(), 100, 50);
                    WLButton.setBounds(175, 50+imageIcon.getIconHeight(), 100, 50);
                    jRadioButton.setBounds(325,50+imageIcon.getIconHeight(),150,50);
                    jRadioButton1.setBounds(500,50+imageIcon.getIconHeight(),150,50);
                    label3.setBounds(50+imageIcon.getIconWidth(),100,1500,100);
                }
            }
        });
        WLButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
//               JOptionPane.showConfirmDialog(null, "上传网络验证");

//                System.out.println(name);
//                System.out.println(jRadioButton.getText());
                if (jRadioButton.isSelected()){
                    String name=Interface.identify(file1);
                    label3.setText("身份证信息为:"+name);
                    label3.setFont(new Font(Font.DIALOG,1,25));
                }else {
                    String name=Interface.car(file1);
                    label3.setText("车牌号信息为:"+name);
                    label3.setFont(new Font(Font.DIALOG,1,25));
                }

            }
        });
        jFrame.add(WLButton);
        jFrame.add(jRadioButton);
        jFrame.add(jRadioButton1);
        jFrame.add(SCButton);
        jFrame.add(jLabel);
        jFrame.add(label3);
        jFrame.setVisible(true);
    }
}

 

标签:jFrame,String,车牌号,token,API,new,import,public,百度
From: https://www.cnblogs.com/1774323810com/p/16856495.html

相关文章

  • 百度前端react面试题总结
    componentWillReceiveProps调用时机已经被废弃掉当props改变的时候才调用,子组件第二次接收到props的时候在调用setState之后发生了什么状态合并,触发调和:setState......
  • sdk、库和API了解
    转自:https://blog.csdn.net/weixin_45697314/article/details/104554941,讲的很详细1.框架 框架是针对开发人员的规范或软件产品,一般为开发更上层应用提供基础功能,可开发......
  • 2.Java API操作elasticsearch
    新建Maven工程添加依赖:<dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><ver......
  • 如何利用API FOX编写业务测试用例?
     假设管理员进行一个场景:为网站新增品牌,内容为品牌名:冬青及服务商名:胡歌,并验证是否新增成功所以:通过页面的F12查询,我们可以知道新增品牌接口,及列表品牌接口,以及品牌详情......
  • 实验七:基于REST API的SDN北向应用实践
    一、实验目的1.能够编写程序调用OpenDaylightRESTAPI实现特定网络功能;2.能够编写程序调用RyuRESTAPI实现特定网络功能。二、实验环境1.下载虚拟机软件OracleVisua......
  • 实验7:基于REST API的SDN北向应用实践
    实验目的能够编写程序调用OpenDaylightRESTAPI实现特定网络功能;能够编写程序调用RyuRESTAPI实现特定网络功能。实验要求(一)基本要求编写Python程序,调用OpenDayligh......
  • ES的java端API操作
    首先简单介绍下写这篇博文的背景,最近负责的一个聚合型的新项目要大量使用ES的检索功能,之前对es的了解还只是纯理论最多加个基于postman的索引创建操作,所以这次我得了解在ja......
  • .net 6 api引入EF (DB first)
    项目添加:Microsoft.EntityFrameworkCore.ToolsPomelo.EntityFrameworkCore.MySql(这个是第三方的efmysql中间件)​Scaffold-DbContext-Force"Server=localhost;U......
  • Django_获取api接口的传参
    当参数为form-data或者x-www-form-urlencoded类型时,使用request.POST获取到参数获取参数方式request.POST.get('username')当参数为raw类型时,使用request.body获取......
  • ckeditor增加自定义工具栏暨百度编辑器上传WORD文档并保留源格式自动填充到编辑框
    ​ 在之前在工作中遇到在富文本编辑器中粘贴图片不能展示的问题,于是各种网上扒拉,终于找到解决方案,在这里感谢一下知乎中众大神以及TheViper。通过知乎提供的思路找到粘......