首页 > 其他分享 >基于百度图像识别SDK开发植物识别系统

基于百度图像识别SDK开发植物识别系统

时间:2022-10-27 10:48:04浏览次数:75  
标签:图像识别 String 识别系统 setLookAndFeel swing new com public SDK

完成了一个小作业,基于百度的图像识别SDK完成动植物的识别。

可能需要的知识:

百度图像识别参考文档:图像识别 - 简介 | 百度AI开放平台 (baidu.com)

fastjson解析类库Github地址:https://github.com/alibaba/fastjson

swing学习以及一些简单皮肤地址:图形界面系列教材 (十四)- Swing 皮肤 Look And Feel (how2j.cn)

 

1.去百度智能云创建自己的应用。

 

2.首先去百度图像识别文档中获取它需要的jar包,导入自己项目中

 

 

3.根据你的API Key 和Secret Key获取access_token,这个就相当于接口调用的凭证,这个代码也是在提供的文档中找到的。

public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "eAg5GyfCgoZDkfOAGXviRd7w";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "KsMf7wrGptzMlNznzQoa0OOnRjwPK3Ec";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Secret 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;
    }
    public static void main(String[] args) {
        getAuth();
    }

运行结果:

expires_in就是凭证的有效时间,所以最后设置成单例模式。

 

4.获取到access_token后,直接就可以调用接口了。

因为获取的数据格式是JSONObject格式,我只想要匹配到的名字,所以需要用到Json解析,因为我也是自己刚刚弄得,所以就一直在Json和字符串之间转换,最后获取到自己想要的数据。json解析需要调用写好的类库,我用的是fastjson。

  public static String name;
    public static final String APP_ID = "28062893";
    public static final String API_KEY = "eAg5GyfCgoZDkfOAGXviRd7w";
    public static final String SECRET_KEY = "KsMf7wrGptzMlNznzQoa0OOnRjwPK3Ec";
    
    
    
    
    public static void animalSample(AipImageClassify client,String image) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("top_num", "1");
        options.put("baike_num", "0");
        
        
        // 参数为本地路径
        JSONObject res = client.animalDetect(image, options);
        String result1 = res.get("result").toString();
        JSONArray arr = JSON.parseArray(result1);
        String jsonObject1 = arr.get(0).toString();
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(jsonObject1);
        String name = obj.getString("name");
        
        AuthService.name = name;
    }
    
    public static void plantSample(AipImageClassify client,String image) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("baike_num", "0");
        
        
        // 参数为本地路径
        JSONObject res = client.plantDetect(image, options);
        String result1 = res.get("result").toString();
        JSONArray arr = JSON.parseArray(result1);
        String jsonObject1 = arr.get(0).toString();
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(jsonObject1);
        String name = obj.getString("name");
        AuthService.name = name;

    }

 

5.最后就是完成图形界面,这个就是swing基础的一些知识就够用了

主要就是设置组件大小,位置,按钮的点击事件,选择文件夹,调用函数接口,操作执行相关顺序之类的知识。

在主函数中生成图形界面,最后那个setLookAndFeel();函数,是java提供的swing皮肤,他有很多,我选的其中的一个,文章开头提供了皮肤jar包获取的地址。

public static String myFile;
    public static String[] type = new String[] {"动物","植物"};
    public static String temp;
    
    public static void main(String[] args) {
        setLookAndFeel();
        AuthService authService = new AuthService();
        
        //主窗体基本信息
        JFrame j = new JFrame("动植物识别系统");
        j.setSize(800, 500);
        j.setLocation(300, 100);
        j.setLayout(null);
        
        //下拉框选择查询类别
        JLabel tishi = new JLabel("要识别图片的类型");
        tishi.setBounds(280,20,200, 30);
        JComboBox<String> cb = new JComboBox<>(type);
        cb.setBounds(400, 20, 70, 30);
        
        //打开文件信息
        JFileChooser jfc = new JFileChooser();
        jfc.setFileFilter(new FileFilter() {
            
            @Override
            public String getDescription() {
                // TODO Auto-generated method stub
                return null;
            }
            
            @Override
            public boolean accept(File f) {
                // TODO Auto-generated method stub
                return true;
            }
        });
        
        //图片容器
        JLabel l = new JLabel();
        
        //显示文字组件
        JLabel jieguo = new JLabel("等待选择图片");
        jieguo.setBounds(600, 150, 200, 50);
        
        //获取图片按钮
        JButton jb1 = new JButton("上传图片");
        jb1.setBounds(200, 350, 100, 50);
        jb1.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int returnVal =  jfc.showOpenDialog(j);
                File file = jfc.getSelectedFile();
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    myFile = file.getAbsolutePath();
                    myFile.replaceAll("\\\\", "/");
                    ImageIcon i = new ImageIcon(myFile);
                    l.setIcon(i);
                    l.setBounds(50,50,i.getIconWidth(),i.getIconHeight());
                    jb1.setBounds(i.getIconWidth()/2, i.getIconHeight()+100, 100, 50);
                }
                jieguo.setText("等待提交验证");
            }
        });
        
        //上传百度接口验证按钮
        JButton jb2 = new JButton("上传网络验证");
        jb2.setBounds(600, 350, 100, 50);
        jb2.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                AipImageClassify client = new AipImageClassify(AuthService.APP_ID, AuthService.API_KEY, AuthService.SECRET_KEY);
                temp = cb.getSelectedItem().toString();
                if(temp.equals("动物")) {
                    AuthService.animalSample(client, myFile);
                } else {
                    AuthService.plantSample(client, myFile);
                }
                jieguo.setText("经过网络查询这个"+temp+"是:"+AuthService.name);
            }
        });
        
        j.add(tishi);
        j.add(cb);
        j.add(jieguo);
        j.add(l);
        j.add(jb1);
        j.add(jb2);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.setVisible(true);
    }
    
    private static void setLookAndFeel() {
        try {
          //javax.swing.UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
         //javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
//       javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");
//        javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.mint.MintLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel");
          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
//          javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
            // handle exception
        }
}

 

6.图形界面效果展示:

 

这个小系统还有点BUG,因为这个图片容器的长宽是通过导入图片获取的,这就导致在网上下载的图片大小差不多,屏幕可以放下,自己拍的照片,几MB很大,屏幕就放不下,因为上传网络验证是固定定位,所以还能识别出来,但是界面就非常不友好,就像下面这样:(这是我拍的我们校园的一条狗)

期待大家的完善,希望这篇文章对你们有所帮助。

 

标签:图像识别,String,识别系统,setLookAndFeel,swing,new,com,public,SDK
From: https://www.cnblogs.com/IT2002/p/16831345.html

相关文章