如何使用 java 将图像发送到 Azure AutoML 端点?

问题描述 投票:0回答:1

我有一个对象检测模型部署到天蓝色的端点。在 python 中,代码运行完美,如下所示:

    headers = {'Content-Type': 'application/json',
               'Authorization': ('Bearer ' + api_key)}
    sample_image = os.path.join(directory, filename)
    # Load image data
    body = open(sample_image, "rb").read()

    req = urllib.request.Request(url, body, headers)

    response = urllib.request.urlopen(req)

我正在尝试在 PDI Kettle 的 UDJC 中做同样的事情。该代码如下所示:

    String urlString = get(Fields.In, "ENDPOINT_URL").getString(r);
    HttpPost post = new HttpPost(urlString);
    post.addHeader("Content-Type",get(Fields.In, "CONTENTTYPE").getString(r));
    post.addHeader("Authorization",get(Fields.In, "API_KEY").getString(r));
    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.STRICT);
    entity.addBinaryBody("file", get(Fields.In, "IMAGEDATA").getBinary(r));
    post.setEntity(entity.build());

    HttpClient httpClient = HttpClients.createDefault();
    HttpResponse response = httpClient.execute(post);

我收到此错误:

http_status    result -1  java.net.SocketException: Broken pipe (Write failed)

我认为图像的书写方式存在问题。如何让java以与python相同的方式编写它? 有什么建议么?谢谢

java azure kettle automl azure-auto-ml
1个回答
0
投票

您可以在java中使用以下包来 获得一个终点。

import  java.net.HttpURLConnection;
import  java.net.URL;

下面是代码。

import  java.io.IOException;
import  java.io.InputStream;
import  java.net.HttpURLConnection;
import  java.net.URL;
import  java.nio.file.Files;
import  java.nio.file.Paths;
import  java.util.Base64;
import  org.json.JSONArray;
import  org.json.JSONObject;
import  java.io.InputStreamReader;
import  java.io.BufferedReader;

class  HelloWorld {
    public  static  void  main(String  args[])
    {
        String  url  =  "https://jml-hgrrb.westeurope.inference.ml.azure.com/score";
        String  api_key  =  "Your_api_key";
        String  directory  =  "C:\\Users\\v-jgs\\Downloads";
        String  filename  =  "download.jpg";
        
      try {
          String  authorizationHeader  =  "Bearer "  +  api_key;
          byte[] imageBytes  =  Files.readAllBytes(Paths.get(directory,filename));
          String  base64ImageData  =  Base64.getEncoder().encodeToString(imageBytes);
          JSONObject  inputData  =  new  JSONObject();
          inputData.put("columns", new  JSONArray().put("image"));
          inputData.put("index", new  JSONArray().put(0));
          inputData.put("data", new  JSONArray().put(base64ImageData));
          JSONObject  requestBody  =  new  JSONObject();
          requestBody.put("input_data", inputData);
          
          URL  apiUrl  =  new  URL(url);
          HttpURLConnection  connection  = (HttpURLConnection) apiUrl.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/json");
          connection.setRequestProperty("Authorization", authorizationHeader);
          connection.setDoOutput(true);
          connection.getOutputStream().write(requestBody.toString().getBytes());
          
          int  responseCode  =  connection.getResponseCode();
          System.out.println("Response Code: "  +  responseCode);
          
          if (responseCode  ==  HttpURLConnection.HTTP_OK) 
          {
            InputStream  responseStream  =  connection.getInputStream();
            String  responseData  =  readInputStream(responseStream);
            System.out.println("Response Data: "  +  responseData);
            } else {
            InputStream  errorStream  =  connection.getErrorStream();
            String  errorData  =  readInputStream(errorStream);
            System.out.println("Error Data: "  +  errorData);
            }
            
            connection.disconnect();
            
        } catch (IOException  e) 
        {
        e.printStackTrace();
        }
    }
    private  static  String  readInputStream(InputStream  inputStream) throws  IOException {
        BufferedReader  reader  =  new  BufferedReader(new  InputStreamReader(inputStream));
        StringBuilder  response  =  new  StringBuilder();
        String  line;
        while ((line  =  reader.readLine()) !=  null) {
        response.append(line);
        }
        reader.close();
        return  response.toString();
    }
}

这是响应对象检测边界的端点。

https://jml-hgrrb.westeurope.inference.ml.azure.com/score

这接受如下所示的 json 主体。

{
    "input_data": {
            "columns": ["image"],
            "index": [0],
            "data":["base64_string"]
            }
}

这里,您需要在数据选项中提供base64字符串。 如果您有多个图像,您也可以将它们相应地添加到索引和数据中,如下所示。

"index":[0,1],
"data":["image1","image2"]

因此,在代码中,您需要创建一个端点接受的 json 对象。 检查 auto-ml 部署详细信息以了解输入结构。 在此代码中,下面的部分创建 json 对象。

          JSONObject  inputData  =  new  JSONObject();
          inputData.put("columns", new  JSONArray().put("image"));
          inputData.put("index", new  JSONArray().put(0));
          inputData.put("data", new  JSONArray().put(base64ImageData));
          JSONObject  requestBody  =  new  JSONObject();
          requestBody.put("input_data", inputData);

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.