百度ai—细粒度图像识别

代码如下:

这里调用的图像识别接口是百度ai-细粒度图像识别;

识别后对植物详细介绍的接口为欧拉蜜-百科。

图像识别支持植物、动物、车型等识别,这里以植物识别为例。

需要识别的图片的限制:图像数据,base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式。

识别图为:
百度ai—细粒度图像识别_第1张图片

运行结果为:

名称:绿萝
产地:原产中美、南美的热带雨林地区。现国内各地上海、江苏、福建、台湾、广东、广西等地均有人工园林居室养植。
门:被子植物门
生活型:藤本植物
界:植物界
种:绿萝
目:泽泻目
习性:绿萝属阴性植物,忌阳光直射,喜散射光,较耐阴。室内栽培可置窗旁,但要避免阳光直射。阳光过强会灼伤绿萝的叶片,过阴会使叶面上美丽的斑纹消失,通常以接受四小时的散射光,绿萝的生长发育最好。
土壤:在一般环境下均能生长,性喜温暖、潮湿环境,要求土壤疏松、肥沃、排水良好
科:天南星科
纲:单子叶植物纲
分布:原产中美、南美的热带雨林地区。现国内各地上海、江苏、福建、台湾、广东、广西等地均有人工园林居室养植。
属:绿萝属
域:真核域
大型常绿藤本植物。生长于热带地区常攀援生长在雨林的岩石和树干上,可长成巨大的藤本植物。绿色的叶片上有黄色的斑块。其缠绕性强,气根发达,既可让其攀附于用棕扎成的圆柱上,摆于门厅、宾馆,也可培养成悬垂状置于书房、窗台,是一种较适合室内摆放的花卉。

1、ImageRec.java

package imageRecognition;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ImageRec {

    public static byte[] getImageByte(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String plant() {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
        try {
            // 本地文件路径
            String filePath = "D:\\test.jpg";
            byte[] imgData = getImageByte(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = AuthService.getAuth();
            String resultStr = sendPost(url+"?access_token="+accessToken, param);           

            JSONObject jsobj = JSONObject.parseObject(resultStr);
            JSONArray jsary = jsobj.getJSONArray("result");
            String name = jsary.getJSONObject(0).getString("name");                      
            return getIntroduce(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    public static String getIntroduce(String keyword){      
        return new NLIProcess().parse("介绍"+keyword);
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(plant());
    }

}

2、NLIProcess.java (调用欧拉蜜接口介绍植物)

package imageRecognition;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class NLIProcess {
    private static final String url = "https://cn.olami.ai/cloudservice/api";
    private static final String Appkey = "7aa0153fd3cc422abbccfe4d3f9efdb5";
    private static final String Appsecret = "bc2f7fd436464b089be1548083765851";
    private static final String api = "nli";    

    public JSONObject process (String input) {
        JSONObject NLIresult = new JSONObject();
        List params = new ArrayList();
        params.add(new BasicNameValuePair("appkey", Appkey));
        params.add(new BasicNameValuePair("api", api));

        long timestamp = Calendar.getInstance().getTimeInMillis();
        params.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
        params.add(new BasicNameValuePair("sign", generateSign(timestamp)));

        JSONObject request = new JSONObject();
        JSONObject data = new JSONObject();
        try {
            data.put("input_type", 0);
            data.put("text", input);

            request.put("data_type", "stt");
            request.put("data", data);
        } catch (JSONException e1) {
            e1.printStackTrace();
            return NLIresult;
        }
        params.add(new BasicNameValuePair("rq", request.toString()));
        params.add(new BasicNameValuePair("cusid", "asdfghj"));

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String contnt = EntityUtils.toString(entity);
                    NLIresult = JSONObject.parseObject(contnt);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return NLIresult;
        } finally {
            try {
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return NLIresult;
    }

    private String generateSign(long timestamp) {
        String sign = Appsecret + "api=" + api + "appkey=" + Appkey + "timestamp=" + timestamp + Appsecret;
        return MD5String(sign);
    }

    public String MD5String(String str) {
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("MD5");
            msgDigest.reset();
            msgDigest.update(str.getBytes("UTF-8"));
            byte[] byteArrary = msgDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArrary.length; i++) {
                String tmp = Integer.toHexString(0xFF & byteArrary[i]);
                if (tmp.length() == 1) {
                    md5StrBuff.append(0).append(tmp);
                } else {
                    md5StrBuff.append(tmp);
                }
            }
            return md5StrBuff.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }   

    public String parse(String input) {
        JSONObject semantic = process(input);
        if (semantic == null || !"ok".equalsIgnoreCase(semantic.getString("status"))) 
            return "";

        JSONObject data = semantic.getJSONObject("data");
        JSONArray s_list = data.getJSONArray("nli");
        JSONObject s_first = s_list.getJSONObject(0);
        JSONObject data_obj = s_first.getJSONArray("data_obj").getJSONObject(0);
        String description = data_obj.getString("description");
        List field_name = data_obj.getJSONArray("field_name");
        List field_value = data_obj.getJSONArray("field_value");
        StringBuffer  str = new StringBuffer();
        for(int i = 0; i 
  

3、Base64Util.java (base64编码)

package imageRecognition;

public class Base64Util {

    private static final char last2byte = (char) Integer
            .parseInt("00000011", 2);
    private static final char last4byte = (char) Integer
            .parseInt("00001111", 2);
    private static final char last6byte = (char) Integer
            .parseInt("00111111", 2);
    private static final char lead6byte = (char) Integer
            .parseInt("11111100", 2);
    private static final char lead4byte = (char) Integer
            .parseInt("11110000", 2);
    private static final char lead2byte = (char) Integer
            .parseInt("11000000", 2);
    private static final char[] encodeTable = new char[] { 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/' };

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int) (from.length * 1.34) + 3);
        int num = 0;
        char currentByte = 0;
        for (int i = 0; i < from.length; i++) {
            num = num % 8;
            while (num < 8) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if ((i + 1) < from.length) {
                            currentByte |= (from[i + 1] & lead2byte) >>> 6;
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if ((i + 1) < from.length) {
                            currentByte |= (from[i + 1] & lead4byte) >>> 4;
                        }
                        break;
                    default:
                        break;
                }
                to.append(encodeTable[currentByte]);
                num += 6;
            }
        }
        if (to.length() % 4 != 0) {
            for (int i = 4 - to.length() % 4; i > 0; i--) {
                to.append("=");
            }
        }
        return to.toString();
    }
}

4、AuthService.java (获取token)

package imageRecognition;

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;

/**
 * 获取token类
 */
public class AuthService {

    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "G3MCKHWKpDhVANcTSyhqqbHa";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "OgoWRHPtfcGdoHBGLWV5TcsQzh5DWS4C";
        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> 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;
    }

}

你可能感兴趣的:(java)