您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用计算机视觉 REST API 和 Java 分析远程图像Quickstart: Analyze a remote image using the Computer Vision REST API and Java

在本快速入门中,你将使用计算机视觉的 REST API 分析远程存储的图像以提取视觉特征。In this quickstart, you analyze a remotely stored image to extract visual features by using Computer Vision's REST API. 使用分析图像方法,可以根据图像内容提取视觉特征。With the Analyze Image method, you can extract visual features based on image content.

如果没有 Azure 订阅,请在开始之前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

先决条件Prerequisites

创建和运行示例应用程序Create and run the sample application

要创建和运行示例,请执行以下步骤:To create and run the sample, do the following steps:

  1. 在最喜爱的 IDE 或编辑器中新建一个 Java 项目。Create a new Java project in your favorite IDE or editor. 如果此选项可用,请从命令行应用程序模板创建 Java 项目。If the option is available, create the Java project from a command line application template.

  2. 将以下库导入到你的 Java 项目中。Import the following libraries into your Java project. 如果使用 Maven,则为每个库提供 Maven 坐标。If you're using Maven, the Maven coordinates are provided for each library.

  3. 将以下 import 语句添加到包含你的项目的 Main 公共类的文件。Add the following import statements to the file that contains the Main public class for your project.

    import java.net.URI;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONObject;
    
  4. Main 公共类替换为以下代码,然后根据需要在代码中进行以下更改:Replace the Main public class with the following code, then make the following changes in code where needed:

    1. subscriptionKey 的值替换为你的订阅密钥。Replace the value of subscriptionKey with your subscription key.
    2. 如有必要,请将 uriBase 的值替换为获取的订阅密钥所在的 Azure 区域中的分析图像方法的终结点 URL。Replace the value of uriBase with the endpoint URL for the Analyze Image method from the Azure region where you obtained your subscription keys, if necessary.
    3. (可选)将 imageToAnalyze 的值替换为要分析的其他图像的 URL。Optionally, replace the value of imageToAnalyze with the URL of a different image that you want to analyze.
public class Main {
    // **********************************************
    // *** Update or verify the following values. ***
    // **********************************************

    // Replace <Subscription Key> with your valid subscription key.
    private static final String subscriptionKey = "<Subscription Key>";

    // You must use the same Azure region in your REST API method as you used to
    // get your subscription keys. For example, if you got your subscription keys
    // from the West US region, replace "westcentralus" in the URL
    // below with "westus".
    //
    // Free trial subscription keys are generated in the "westus" region.
    // If you use a free trial subscription key, you shouldn't need to change
    // this region.
    private static final String uriBase =
            "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze";

    private static final String imageToAnalyze =
            "https://upload.wikimedia.org/wikipedia/commons/" +
                    "1/12/Broadway_and_Times_Square_by_night.jpg";

    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        try {
            URIBuilder builder = new URIBuilder(uriBase);

            // Request parameters. All of them are optional.
            builder.setParameter("visualFeatures", "Categories,Description,Color");
            builder.setParameter("language", "en");

            // Prepare the URI for the REST API method.
            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);

            // Request headers.
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request body.
            StringEntity requestEntity =
                    new StringEntity("{\"url\":\"" + imageToAnalyze + "\"}");
            request.setEntity(requestEntity);

            // Call the REST API method and get the response entity.
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // Format and display the JSON response.
                String jsonString = EntityUtils.toString(entity);
                JSONObject json = new JSONObject(jsonString);
                System.out.println("REST Response:\n");
                System.out.println(json.toString(2));
            }
        } catch (Exception e) {
            // Display error message.
            System.out.println(e.getMessage());
        }
    }
}

编译并运行程序Compile and run the program

  1. 保存,然后生成 Java 项目。Save, then build the Java project.
  2. 如果使用的是 IDE,请运行 MainIf you're using an IDE, run Main.

另外,如果从命令行窗口运行此程序,请运行以下命令。Alternately, if you're running the program from a command line window, run the following commands. 这些命令假设你的库在名为 libs 的文件夹中,该文件夹与 Main.java 位于同一文件夹中;否则,你需要将 libs 替换为库路径。These commands presume your libraries are in a folder named libs that is in the same folder as Main.java; if not, you will need to replace libs with the path to your libraries.

  1. 编译 Main.java 文件。Compile the file Main.java.

    javac -cp ".;libs/*" Main.java
    
  2. 运行该程序。Run the program. 它向 QnA Maker API 发送创建知识库的请求,然后每隔 30 秒轮询一次结果。It will send the request to the QnA Maker API to create the KB, then it will poll for the results every 30 seconds. 每个响应都将输出到命令行窗口中。Each response is printed to the command line window.

    java -cp ".;libs/*" Main
    

检查响应Examine the response

成功的响应以 JSON 格式返回。A successful response is returned in JSON. 示例应用程序会在控制台窗口中分析和显示成功响应,如下例所示:The sample application parses and displays a successful response in the console window, similar to the following example:

REST Response:

{
  "metadata": {
    "width": 1826,
    "format": "Jpeg",
    "height": 2436
  },
  "color": {
    "dominantColorForeground": "Brown",
    "isBWImg": false,
    "accentColor": "B74314",
    "dominantColorBackground": "Brown",
    "dominantColors": ["Brown"]
  },
  "requestId": "bbffe1a1-4fa3-4a6b-a4d5-a4964c58a811",
  "description": {
    "captions": [{
      "confidence": 0.8241405091548035,
      "text": "a group of people on a city street filled with traffic at night"
    }],
    "tags": [
      "outdoor",
      "building",
      "street",
      "city",
      "busy",
      "people",
      "filled",
      "traffic",
      "many",
      "table",
      "car",
      "group",
      "walking",
      "bunch",
      "crowded",
      "large",
      "night",
      "light",
      "standing",
      "man",
      "tall",
      "umbrella",
      "riding",
      "sign",
      "crowd"
    ]
  },
  "categories": [{
    "score": 0.625,
    "name": "outdoor_street"
  }]
}

清理资源Clean up resources

当不再需要时,可以删除 Java 项目,包括已编辑的类和导入的库。When no longer needed, delete the Java project, including the compiled class and imported libraries.

后续步骤Next steps

浏览一款 Java Swing 应用程序,该应用程序使用计算机视觉执行光学字符识别 (OCR)、创建智能裁剪缩略图,并对图像中的视觉特征(包括人脸)进行检测、分类、标记和描述。Explore a Java Swing application that uses Computer Vision to perform optical character recognition (OCR); create smart-cropped thumbnails; plus detect, categorize, tag, and describe visual features, including faces, in an image. 要快速体验计算机视觉 API,请尝试使用 Open API 测试控制台To rapidly experiment with the Computer Vision API, try the Open API testing console.