首页 > 编程语言 >JAVA 调佣百度ai识别身份证和车牌号

JAVA 调佣百度ai识别身份证和车牌号

时间:2022-11-14 20:46:04浏览次数:33  
标签:setBounds JAVA String 调佣 ai contentPane new import public

识别身份证和车牌号的方法:

package function;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;

import java.util.HashMap;


/**
 * 图像识别sdk
 */
public class Function {
    //设置APPID/AK/SK
    public static final String APP_ID = "28172969";
    public static final String API_KEY = "4eReYrQtAh9YN6QFuWGyuqlu";
    public static final String SECRET_KEY = "Y3tTclcDqxZP3ZLBLUISPEHDIzRUlBcx";
    public static String path = "D:\\6.jpg";   //初始化随便选一个路径
    // 初始化一个AipOcr
    public static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);


    public static void main(String[] args) {
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 可选:设置log4j日志输出格式,若不设置,则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        System.out.println("身份证***********************************");
        idCard("D://1.jpg");

        System.out.println("车牌***********************************");
        licensePlate("D://2.jpg");

    }



    public static String idCard(String path) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");

        String idCardSide = "back";

        // 参数为本地图片路径
//        String image = "";
        JSONObject res = client.idcard(path, idCardSide, options);
        System.out.println(res.toString(2));
        return res.toString(2);
    }



    public static String licensePlate( String path) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("multi_detect", "true");


        // 参数为本地图片路径
//        String image = "D://2.jpg";
        JSONObject res = client.plateLicense(path, options);

        System.out.println(res.toString(2));
        return res.toString(2);

    }



}

 

awt界面:

package swing;

import bean.LicensePlateBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import function.Function;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

public class LicensePlateSwing extends JFrame {

    private JPanel contentPane;
    private static JLabel lblNewLabel;  //图片展示区域
    private JButton btnNewButton ;//上传图片按钮
    private JButton upButton;  //上传网络验证
    private  JLabel jLabel ;                 //提示对话框
    private static String path = null;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LicensePlateSwing frame = new LicensePlateSwing();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LicensePlateSwing() {     //页面布局
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1000, 600);
//        setBounds(100, 100, 622, 421);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        //提示文本框
        jLabel = new JLabel("请选择要识别的车牌图片");
        jLabel.setFont(new Font("宋体", Font.BOLD, 15));
        jLabel.setBounds(450,200,800,100);
        contentPane.add(jLabel);


//      图片区域
        lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(225, 80, 200, 200);
        lblNewLabel.setBackground(Color.red);
        contentPane.add(lblNewLabel);

        //上传图片按钮
//        btnNewButton = new JButton("\u4E0A\u4F20\u56FE\u7247");
        btnNewButton = new JButton("上传图片");         //设置图片按钮
        btnNewButton.setFont(new Font("宋体", Font.BOLD, 18));
        btnNewButton.addMouseListener(new MouseAdapter() {          //按钮点击事件
            @Override
            public void mouseClicked(MouseEvent e) {
                addPicture(btnNewButton);

            }
        });

//        btnNewButton.setBounds(355, 264, 141, 46);
        btnNewButton.setBounds(250, 350, 141, 46);
        contentPane.add(btnNewButton);






        //验证
        upButton = new JButton("上传网络验证");
        upButton.setFont(new Font("宋体", Font.BOLD, 18));
        upButton.addMouseListener(new MouseAdapter() {          //按钮点击事件
            @Override
            public void mouseClicked(MouseEvent e) {
                if (path == null){
                    jLabel.setText("未选择图片");

                }
                else{
                    LicensePlateBean res = verify();

                    if (null==(res.getNumber())) {
                        jLabel.setText("选择的图片不是车牌照");
                    }
                    else {
                        jLabel.setText("经过识别这个车牌照:"+res.getNumber()+"  颜色是"+res.getColor());
                    }
                }
            }
        });
        upButton.setBounds(500,350,200,46);
        contentPane.add(upButton);


        contentPane.addComponentListener(new ComponentAdapter() {//拖动窗口监听
            public void componentResized(ComponentEvent e) {
                int whidth=contentPane.getWidth();//获取窗口宽度
                int height=contentPane.getHeight();//获取窗口高度  你也可以设置高度居中
                //将lable放在 窗口左边的1/3处
//                btnNewButton.setBounds(whidth/3, 63, 61, 16);//(起始点x,起始点y,宽地w,高h)  标签设置宽高不明显
//                //将lable放在 窗口左边的1/2处
//                button.setBounds(whidth/2, 63, 61, 16);//(起始点x,起始点y,宽地w,高h)
//                //宽度始终是窗口的1/2
//                textField.setBounds(81, 110, whidth/2, 26);//(起始点x,起始点y,宽地w,高h)

                lblNewLabel.setBounds(whidth/5, height/4, 200, 200);
                jLabel.setBounds(whidth*3/5,height/4,800,100);
                btnNewButton.setBounds(whidth/5, height*4/5, 141, 46);//上传

                upButton.setBounds(whidth*3/5,height*4/5,200,46);//验证

            }

        });



    }


    //上传图片
    public static void addPicture(JButton button)  {
        JFileChooser chooser = new JFileChooser();//文件选择器
        chooser.setMultiSelectionEnabled(true);//是否可以多选文件

        /** 过滤文件类型 * */
        FileNameExtensionFilter filter = new FileNameExtensionFilter("图片","jpg","png"); //筛选结果为文件夹和图片文件
        chooser.setFileFilter(filter);//设置选择器的过滤器
        int returnVal = chooser.showOpenDialog(button);//在容器中选择文件选择器
        if (returnVal == JFileChooser.APPROVE_OPTION) { //如果在选择器中单击“打开”
            /** 得到选择的文件* */
            File[] arrfiles = chooser.getSelectedFiles();   //获取选择器中选中的文件
//            file.getAbsolutePath()
            if (arrfiles == null || arrfiles.length == 0) {
                return;
            }



            //判断是否有文件为jpg或者png
            File  ff = chooser.getSelectedFile();
            //创建一个fileName得到选择文件的名字
            String fileName =ff.getName();
            //lastIndexOf(".") 返回"."在文件名中最后一次出现的下标
            //substring(int index)从指定的index开始截取后面的字符串
            //比如: a.txt 最后一次出现的.下标是 1 substring(1)就是从下标1的位置开始截取 截取后的新字符串为 .txt
            //所以这里需要+1 才能只截取文件类型 txt
            String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
            //判断选择的文件是否是图片文件 必须排除不是的情况 不然后续操作会报错
            if(!(prefix.equals("jpg") || prefix.equals("png"))){
                JOptionPane.showMessageDialog(new JDialog(),":请选择.jpg 或 .png格式的图片");
                return;
            }
            String absolutePath = ff.getAbsolutePath();
            path=absolutePath;
            //创建一个ImageIcon对象 传入图片文件的绝对路径
            ImageIcon imageIcon = new ImageIcon(absolutePath);
            imageIcon.setImage(imageIcon.getImage().getScaledInstance(lblNewLabel.getWidth(), lblNewLabel.getHeight(), Image.SCALE_DEFAULT));//图片自适应窗口大小
            lblNewLabel.setIcon(imageIcon);

            lblNewLabel.getIcon();


            System.out.println("******************************"+absolutePath);//获取图片路径



        }
    }


    //验证
    public static LicensePlateBean verify() {
        LicensePlateBean licensePlate = new LicensePlateBean();
        String res = Function.licensePlate(path);
        JSONObject jsonObject = JSON.parseObject(res);//转为对象类型
        System.out.println(jsonObject);
        JSONArray words_result = (JSONArray)jsonObject.get("words_result");

        JSONObject results =  (JSONObject)words_result.get(0);
        System.out.println(results);
        String number =  results.getString("number");
        String color = results.getString("color");
        licensePlate.setColor(color);
        licensePlate.setNumber(number);

        return licensePlate;


    }



}

 

package swing;

import bean.IdCardBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import function.Function;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

public class IdCradSwing extends JFrame {

    private JPanel contentPane;
    private static JLabel lblNewLabel;  //图片展示区域
    private JButton btnNewButton ;//上传图片按钮
    private JButton upButton;  //上传网络验证
    private  JLabel jLabel ;
    private  JLabel jLabel2 ;
    private  JLabel jLabel3 ;

    private static String path = null;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    IdCradSwing frame = new IdCradSwing();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public IdCradSwing() {     //页面布局
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1000, 600);
//        setBounds(100, 100, 622, 421);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        //提示文本框
        jLabel = new JLabel("请选择要识别的身份证图片");
        jLabel.setFont(new Font("宋体", Font.BOLD, 15));
        jLabel.setBounds(450,200,800,100);
        contentPane.add(jLabel);

        jLabel2 = new JLabel("");
        jLabel2.setFont(new Font("宋体", Font.BOLD, 15));
        contentPane.add(jLabel2);

        jLabel3 = new JLabel("");
        jLabel3.setFont(new Font("宋体", Font.BOLD, 15));
        contentPane.add(jLabel3);


//      图片区域
        lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(225, 80, 200, 200);
        lblNewLabel.setBackground(Color.red);
        contentPane.add(lblNewLabel);

        //上传图片按钮
//        btnNewButton = new JButton("\u4E0A\u4F20\u56FE\u7247");
        btnNewButton = new JButton("上传图片");         //设置图片按钮
        btnNewButton.setFont(new Font("宋体", Font.BOLD, 18));
        btnNewButton.addMouseListener(new MouseAdapter() {          //按钮点击事件
            @Override
            public void mouseClicked(MouseEvent e) {
                addPicture(btnNewButton);

            }
        });

//        btnNewButton.setBounds(355, 264, 141, 46);
        btnNewButton.setBounds(250, 350, 141, 46);
        contentPane.add(btnNewButton);






        //验证
        upButton = new JButton("上传网络验证");
        upButton.setFont(new Font("宋体", Font.BOLD, 18));
        upButton.addMouseListener(new MouseAdapter() {          //按钮点击事件
            @Override
            public void mouseClicked(MouseEvent e) {
                if (path == null){
                    jLabel.setText("未选择图片");

                }
                else{
                    IdCardBean res = verify();

                    if (null==(res.getId())) {
                        jLabel.setText("选择的图片不是身份证或身份证有损坏");
                    }
                    else {
                        jLabel.setText("姓名:"+ res.getName()+"  性别:"+res.getSex()+"  民族:"+res.getNationality()+"");
                        jLabel2.setText("家庭住址:"+res.getAddress());
                        jLabel3.setText("身份证号码:"+res.getId());




                    }
                }
            }
        });
        upButton.setBounds(500,350,200,46);
        contentPane.add(upButton);


        contentPane.addComponentListener(new ComponentAdapter() {//拖动窗口监听
            public void componentResized(ComponentEvent e) {
                int whidth=contentPane.getWidth();//获取窗口宽度
                int height=contentPane.getHeight();//获取窗口高度  你也可以设置高度居中

                lblNewLabel.setBounds(whidth/5, height/4, 200, 200);
                jLabel.setBounds(whidth*3/5,height/8,800,100);
                btnNewButton.setBounds(whidth/5, height*4/5, 141, 46);//上传
                jLabel2.setBounds(whidth*3/5,height/2,800,100);
                jLabel3.setBounds(whidth*3/5,height/4,800,100);
                upButton.setBounds(whidth*3/5,height*4/5,200,46);//验证

            }

        });



    }


    //上传图片
    public static void addPicture(JButton button)  {
        JFileChooser chooser = new JFileChooser();//文件选择器
        chooser.setMultiSelectionEnabled(true);//是否可以多选文件

        /** 过滤文件类型 * */
        FileNameExtensionFilter filter = new FileNameExtensionFilter("图片","jpg","png"); //筛选结果为文件夹和图片文件
        chooser.setFileFilter(filter);//设置选择器的过滤器
        int returnVal = chooser.showOpenDialog(button);//在容器中选择文件选择器
        if (returnVal == JFileChooser.APPROVE_OPTION) { //如果在选择器中单击“打开”
            /** 得到选择的文件* */
            File[] arrfiles = chooser.getSelectedFiles();   //获取选择器中选中的文件
//            file.getAbsolutePath()
            if (arrfiles == null || arrfiles.length == 0) {
                return;
            }



            //判断是否有文件为jpg或者png
            File  ff = chooser.getSelectedFile();
            //创建一个fileName得到选择文件的名字
            String fileName =ff.getName();

            String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
            //判断选择的文件是否是图片文件 必须排除不是的情况 不然后续操作会报错
            if(!(prefix.equals("jpg") || prefix.equals("png"))){
                JOptionPane.showMessageDialog(new JDialog(),":请选择.jpg 或 .png格式的图片");
                return;
            }
            String absolutePath = ff.getAbsolutePath();
            path=absolutePath;
            //创建一个ImageIcon对象 传入图片文件的绝对路径
            ImageIcon imageIcon = new ImageIcon(absolutePath);
            imageIcon.setImage(imageIcon.getImage().getScaledInstance(lblNewLabel.getWidth(), lblNewLabel.getHeight(), Image.SCALE_DEFAULT));//图片自适应窗口大小
            lblNewLabel.setIcon(imageIcon);

            lblNewLabel.getIcon();


            System.out.println("******************************"+absolutePath);//获取图片路径



        }
    }


    //验证
    public static IdCardBean verify() {
        IdCardBean idCardBean = new IdCardBean();
        String res = Function.idCard(path);
        JSONObject jsonObject = JSON.parseObject(res);//转为对象类型

        JSONObject words_result = (JSONObject)jsonObject.get("words_result");
        JSONObject name = (JSONObject)words_result.get("姓名");
        String nameRes = name.getString("words");
        JSONObject nationality = (JSONObject)words_result.get("民族");
        String nationalityRes = nationality.getString("words");
        JSONObject address = (JSONObject)words_result.get("住址");
        String addressRes = address.getString("words");
        JSONObject id = (JSONObject)words_result.get("公民身份号码");
        String idRes = id.getString("words");
        JSONObject birthday = (JSONObject)words_result.get("出生");
        String birthdayRes = birthday.getString("words");
        JSONObject sex = (JSONObject)words_result.get("性别");
        String sexRes = sex.getString("words");

        idCardBean.setName(nameRes);
        idCardBean.setAddress(addressRes);
        idCardBean.setId(idRes);
        idCardBean.setBirthday(birthdayRes);
        idCardBean.setNationality(nationalityRes);
        idCardBean.setSex(sexRes);

        return idCardBean;


    }



}

 

标签:setBounds,JAVA,String,调佣,ai,contentPane,new,import,public
From: https://www.cnblogs.com/zhaolei0419/p/16890315.html

相关文章

  • Java 继承的重点(一定要掌握)
    在看集合源码的时候,因为对一些知识点有些混淆,导致看源码比较吃力。所以重新回顾一下面向对象的继承和多态,顺便记录一下重点。继承子类会继承父类的所有属性和方法,但私......
  • java 转发重定向
    首先我们要知道:(1)request.getRequestDispatcher()是请求转发,前后页面共享一个request;这个是在服务端运行的,对浏览器来说是透明的。(2)response.sendRedirect()是重新......
  • JAVA 调佣百度ai识别动植物
    项目结构:    调用sdk分别实现动物识别和植物识别类:packagefounction;importutil.AuthService;importutil.Base64Util;importutil.FileUtil;importut......
  • java三级菜单遍历
     java三级菜单遍历@OverridepublicList<YjztCity>getYjzt(){List<YjztCity>yjztCities=yjztCityMapper.selectByExample(null);//先获取你想要......
  • 力扣278(java&python)-第一个错误的版本(简单)
    题目:你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本......
  • 小新Java8-【final、权限、内部类、引用类型】
    一、final关键字1.概述final:不可改变。可以用于修饰类、方法和变量。类:被修饰的类,不能被继承。方法:被修饰的方法,不能被重写。变量:被修饰的变量,不能被重新赋值。2.......
  • 第一天复习Java基础
    java基础语法1注释,标识符,关键字注释书写注释是一个很好的习惯,他是写给人看的。平时写代码一定要规范Java的三种注释单行注释//多行注释/*注释*/(可以注释多......
  • 【JAVA面试】java面试题整理(4)
                          java面试题整理(4)JAVA常考点4目录​​1、Set集合如何保证不重复1​​​​2、Java中Integer型和int型......
  • 【Spark】java.lang.NoSuchMethodException: org.apache.hadoop.hive.ql.metadata.Hiv
    2/11/1419:02:23ERROR[main]SparkUncaughtExceptionHandler:UncaughtexceptioninthreadThread[main,5,main]java.lang.NoSuchMethodException:org.apache.hado......
  • 百度AIG知识图谱部面经
    自我介绍平时用什么语言比较多?Pythonc语言指针占多少内存?根据机器不同,16位占2位,32位占4位,64位占8位python里的map函数,讲一下它的作用和返回值传入一个函数和......