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

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

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅An Azure subscription - Create one for trial
  • GoGo
  • 拥有 Azure 订阅后,在 Azure 门户中创建计算机视觉资源 ,获取密钥和终结点。Once you have your Azure subscription, create a Computer Vision resource in the Azure portal to get your key and endpoint. 部署后,单击“转到资源”。After it deploys, click Go to resource.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到计算机视觉服务。You will need the key and endpoint from the resource you create to connect your application to the Computer Vision service. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.
  • 为密钥和终结点 URL 创建环境变量,分别将其命名为 COMPUTER_VISION_SUBSCRIPTION_KEYCOMPUTER_VISION_ENDPOINTCreate environment variables for the key and endpoint URL, named COMPUTER_VISION_SUBSCRIPTION_KEY and COMPUTER_VISION_ENDPOINT, respectively.

创建并运行示例Create and run the sample

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

  1. 将以下代码复制到文本编辑器中。Copy the below code into a text editor.
  2. (可选)将 imageUrl 的值替换为要分析的其他图像的 URL。Optionally, replace the value of imageUrl with the URL of a different image that you want to analyze.
  3. 将代码保存为以 .go 为扩展名的文件。Save the code as a file with a .go extension. 例如,analyze-image.goFor example, analyze-image.go.
  4. 打开命令提示符窗口。Open a command prompt window.
  5. 在提示符处运行 go build 命令,对文件中的包进行编译。At the prompt, run the go build command to compile the package from the file. 例如,go build analyze-image.goFor example, go build analyze-image.go.
  6. 在提示符处,运行所编译的包。At the prompt, run the compiled package. 例如,analyze-imageFor example, analyze-image.
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "strings"
    "time"
)

func main() {
    // Add your Computer Vision subscription key and endpoint to your environment variables.
    subscriptionKey := os.Getenv("COMPUTER_VISION_SUBSCRIPTION_KEY")
    endpoint := os.Getenv("COMPUTER_VISION_ENDPOINT")

    uriBase := endpoint + "vision/v3.0/analyze"
    const imageUrl =
        "https://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg"

    const params = "?visualFeatures=Description&details=Landmarks"
    uri := uriBase + params
    const imageUrlEnc = "{\"url\":\"" + imageUrl + "\"}"

    reader := strings.NewReader(imageUrlEnc)

    // Create the HTTP client
    client := &http.Client{
        Timeout: time.Second * 2,
    }

    // Create the POST request, passing the image URL in the request body
    req, err := http.NewRequest("POST", uri, reader)
    if err != nil {
        panic(err)
    }

    // Add request headers
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)

    // Send the request and retrieve the response
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    // Read the response body
    // Note, data is a byte array
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    // Parse the JSON data from the byte array
    var f interface{}
    json.Unmarshal(data, &f)

    // Format and display the JSON result
    jsonFormatted, _ := json.MarshalIndent(f, "", "  ")
    fmt.Println(string(jsonFormatted))
}

检查响应Examine the response

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

{
  "categories": [
    {
      "detail": {
        "landmarks": []
      },
      "name": "outdoor_water",
      "score": 0.9921875
    }
  ],
  "description": {
    "captions": [
      {
        "confidence": 0.916458423253597,
        "text": "a large waterfall over a rocky cliff"
      }
    ],
    "tags": [
      "nature",
      "water",
      "waterfall",
      "outdoor",
      "rock",
      "mountain",
      "rocky",
      "grass",
      "hill",
      "covered",
      "hillside",
      "standing",
      "side",
      "group",
      "walking",
      "white",
      "man",
      "large",
      "snow",
      "grazing",
      "forest",
      "slope",
      "herd",
      "river",
      "giraffe",
      "field"
    ]
  },
  "metadata": {
    "format": "Jpeg",
    "height": 959,
    "width": 1280
  },
  "requestId": "a92f89ab-51f8-4735-a58d-507da2213fc2"
}

后续步骤Next steps

了解计算机视觉 API,它用于分析图像、检测名人和地标、创建缩略图,并提取印刷体文本和手写文本。Explore the Computer Vision API used to analyze an image, detect celebrities and landmarks, create a thumbnail, and extract printed and handwritten text. 要快速体验计算机视觉 API,请尝试使用 Open API 测试控制台To rapidly experiment with the Computer Vision API, try the Open API testing console.