java实现调用百度ai开放平台图像识别接口

1.直接上完整代码,可直接运行,代码注释详细。 

package com.example.demo.demo2;
// 导入相关的类
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;

import org.json.JSONObject;
public class ImageRecognitionDemo {
    // 设置API Key和Secret Key
    private static final String API_KEY = "";
    private static final String SECRET_KEY = "";

    // 设置获取access token的地址和参数
    private static final String AUTH_HOST = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String AUTH_PARAMS;

    static {
        try {
            AUTH_PARAMS = "grant_type=client_credentials" +
                    "&client_id=" + URLEncoder.encode(API_KEY, "UTF-8") +
                    "&client_secret=" + URLEncoder.encode(SECRET_KEY, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    // 设置图像识别的接口地址和参数
    private static final String IMAGE_HOST = "https://aip.baidubce.com/api/v1/solution/direct/imagerecognition/combination";
    private static final String SCENES = "[\"animal\"]"; // 指定要调用的模型服务,"plant","ingredient","dishs", "red_wine","currency","landmark"
    private static final String IMAGE = new String(getImageBase64("D:\\1.jpg")) ; // 图像数据,base64编码

    // 定义一个获取access token的方法
    public static String getAccessToken() {
        try {
            // 创建一个URL对象,并传入获取access token的地址和参数
            URL url = new URL(AUTH_HOST + "?" + AUTH_PARAMS);

            // 打开一个连接对象,并设置相关的属性
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET"); // 请求方法
            conn.setConnectTimeout(5000); // 连接超时时间
            conn.setReadTimeout(5000); // 读取超时时间

            // 获取连接对象的输入流,并使用一个缓冲读取器来读取返回值
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 将返回值转换为一个JSON对象,并解析其中的数据项,获取access token
            JSONObject json = new JSONObject(sb.toString());
            String accessToken = json.getString("access_token");

            // 关闭连接
            conn.disconnect();

            // 返回access token
            return accessToken;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 定义一个调用图像识别接口的方法
    public static void imageRecognition(String accessToken) {
        try {
            // 创建另一个URL对象,并传入图像识别的接口地址和参数
            URL imageUrl = new URL(IMAGE_HOST + "?access_token=" + accessToken);

            // 打开另一个连接对象,并设置相关的属性
            HttpURLConnection imageConn = (HttpURLConnection) imageUrl.openConnection();
            imageConn.setRequestMethod("POST"); // 请求方法
            imageConn.setConnectTimeout(5000); // 连接超时时间
            imageConn.setReadTimeout(5000); //
            imageConn.setDoOutput(true);
            imageConn.setDoInput(true);
            imageConn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 请求头

            // 获取另一个连接对象的输出流,并使用一个数据输出流来写入请求体,包含要识别的图片数据
            OutputStream out = imageConn.getOutputStream();
            DataOutputStream writer = new DataOutputStream(out);
            writer.writeBytes("{\"scenes\":" + SCENES + ",\"image\":\"" + IMAGE + "\"}"); // 请求体
            writer.flush();
            writer.close();

            // 获取另一个连接对象的输入流,并使用另一个缓冲读取器来读取返回值
            InputStream imageIn = imageConn.getInputStream();
            BufferedReader imageReader = new BufferedReader(new InputStreamReader(imageIn));
            StringBuilder imageSb = new StringBuilder();
            String imageLine = null;
            while ((imageLine = imageReader.readLine()) != null) {
                imageSb.append(imageLine);
            }

            // 将返回值转换为另一个JSON对象,并解析其中的数据项,获取图片识别的结果
            JSONObject imageJson = new JSONObject(imageSb.toString());
            JSONObject result = imageJson.getJSONObject("result"); // 返回结果json串

            // 打印或显示图片识别的结果
            System.out.println(result.toString());

            // 关闭连接
            imageConn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 定义一个获取图片并转为base64编码的方法
    public static String getImageBase64(String imagePath) {
        try {
            // 创建一个文件对象,并传入图片的地址
            File file = new File(imagePath);

            // 创建一个文件输入流对象,并传入文件对象
            FileInputStream fis = new FileInputStream(file);

            // 创建一个字节数组,用来存储图片数据
            byte[] data = new byte[(int) file.length()];

            // 从文件输入流中读取图片数据到字节数组中
            fis.read(data);

            // 关闭文件输入流
            fis.close();

            // 使用Base64类的方法,将字节数组转为base64编码的字符串
            String imageBase64 = Base64.getEncoder().encodeToString(data);

            // 返回base64编码的字符串
            return imageBase64;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 定义一个主方法,用来运行程序
    public static void main(String[] args) {
        // 获取access token
        String accessToken = getAccessToken();
        // 调用图像识别接口
        imageRecognition(accessToken);
    }


}

2.测试

选择一张带大象的图片,识别结果如下:

{
	"animal": {
		"result": [{
			"score": "0.843056",
			"name": "非洲象"
		}, {
			"score": "0.152664",
			"name": "亚洲象"
		}, {
			"score": "0.00209082",
			"name": "野象"
		}, {
			"score": "0.000134751",
			"name": "水牛"
		}, {
			"score": "4.43494e-05",
			"name": "猛犸象"
		}, {
			"score": "4.41153e-05",
			"name": "海象"
		}],
		"log_id": 164536619102552888
	}
}

3.结果显示还是很不错的。

猜你喜欢

转载自blog.csdn.net/qq_35207086/article/details/130066317