快速入門:在電腦視覺中使用 REST API 搭配 Node.js 分析遠端影像Quickstart: Analyze a remote image using the REST API with Node.js in Computer Vision

在此快速入門中,您將使用電腦視覺的 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

若要建立並執行範例,請執行下列步驟:To create and run the sample, do the following steps:

  1. 安裝 npm request 套件。Install the npm request package.

    1. 以系統管理員身分開啟 [命令提示字元] 視窗。Open a command prompt window as an administrator.

    2. 執行以下命令:Run the following command:

      npm install request
      
    3. 成功安裝套件之後,關閉命令提示字元視窗。After the package is successfully installed, close the command prompt window.

  2. 將下列程式碼複製到文字編輯器。Copy the following code into a text editor.

  3. 視需要在程式碼中進行下列變更:Make the following changes in code where needed:

    1. subscriptionKey 的值取代為您的訂用帳戶金鑰。Replace the value of subscriptionKey with your subscription key.
    2. 如有需要,請從您取得訂用帳戶金鑰的 Azure 區域,將 uriBase 的值取代為分析影像方法的端點 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. (選擇性) 將 imageUrl 的值取代為您要分析之不同影像的 URL。Optionally, replace the value of imageUrl with the URL of a different image that you want to analyze.
    4. (選擇性) 以不同的語言取代 language 要求參數的值。Optionally, replace the value of the language request parameter with a different language.
  4. 將程式碼儲存為副檔名為 .js 的檔案。Save the code as a file with a .js extension. 例如: analyze-image.jsFor example, analyze-image.js.

  5. 開啟命令提示字元視窗。Open a command prompt window.

  6. 出現提示時,使用 node 命令來執行該檔案。At the prompt, use the node command to run the file. 例如: node analyze-image.jsFor example, node analyze-image.js.

'use strict';

const request = require('request');

// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = '<Subscription Key>';

// You must use the same location in your REST call as you used to get your
// subscription keys. For example, if you got your subscription keys from
// westus, replace "westcentralus" in the URL below with "westus".
const uriBase =
    'https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze';

const imageUrl =
    'https://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg';

// Request parameters.
const params = {
    'visualFeatures': 'Categories,Description,Color',
    'details': '',
    'language': 'en'
};

const options = {
    uri: uriBase,
    qs: params,
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

request.post(options, (error, response, body) => {
  if (error) {
    console.log('Error: ', error);
    return;
  }
  let jsonResponse = JSON.stringify(JSON.parse(body), null, '  ');
  console.log('JSON Response\n');
  console.log(jsonResponse);
});

檢查回應Examine the response

成功的回應會以 JSON 的形式傳回。A successful response is returned in JSON. 範例會在命令提示字元視窗中剖析並顯示成功的回應,如下列範例所示:The sample parses and displays a successful response in the command prompt window, similar to the following example:

{
  "categories": [
    {
      "name": "outdoor_water",
      "score": 0.9921875,
      "detail": {
        "landmarks": []
      }
    }
  ],
  "description": {
    "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"
    ],
    "captions": [
      {
        "text": "a large waterfall over a rocky cliff",
        "confidence": 0.916458423253597
      }
    ]
  },
  "color": {
    "dominantColorForeground": "Grey",
    "dominantColorBackground": "Green",
    "dominantColors": [
      "Grey",
      "Green"
    ],
    "accentColor": "4D5E2F",
    "isBwImg": false
  },
  "requestId": "81b4e400-e3c1-41f1-9020-e6871ad9f0ed",
  "metadata": {
    "height": 959,
    "width": 1280,
    "format": "Jpeg"
  }
}

清除資源Clean up resources

不再需要檔案時請將它刪除,然後再解除安裝 npm request 套件。When no longer needed, delete the file, and then uninstall the npm request package. 若要解除安裝套件,請執行下列步驟:To uninstall the package, do the following steps:

  1. 以系統管理員身分開啟 [命令提示字元] 視窗。Open a command prompt window as an administrator.

  2. 執行以下命令:Run the following command:

    npm uninstall request
    
  3. 將套件成功解除安裝之後,關閉命令提示字元視窗。After the package is successfully uninstalled, close the command prompt window.

後續步驟Next steps

探索用來分析影像、偵測名人和地標、建立縮圖及擷取印刷和手寫文字的「電腦視覺 API」。Explore the Computer Vision APIs 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.