共用方式為


快速入門:影像分析

開始使用影像分析 REST API 或用戶端程式庫來設定基本映像標記指令碼。 分析影像服務為您提供 AI 演算法,以便處理影像及傳回其視覺功能的資訊。 請遵循下列步驟將套件安裝至您的應用程式,並試用範例程式碼。

使用適用於 C# 的影像分析用戶端程式庫來分析影像的內容標記。 本快速入門會定義 AnalyzeImageUrl 方法,以使用用戶端物件來分析遠端影像並輸出結果。

參考文件 | 程式庫來源程式碼 | 套件 (NuGet) | 範例

提示

您也可以分析本機影像。 請參閱 ComputerVisionClient 方法,例如 AnalyzeImageInStreamAsync。 或如需本機映像的相關案例,請參閱 GitHub 上的範例程式碼。

提示

分析 API 可以執行產生影像標記以外的許多不同作業。 如需展示所有可用功能的範例,請參閱影像分析操作指南

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • Visual Studio IDE 或目前版本的 .NET Core
  • 擁有 Azure 訂用帳戶之後,在 Azure 入口網站中建立電腦視覺資源,以取得您的金鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要來自所建立資源的金鑰和端點,以便將應用程式連線至 Azure AI 視覺服務。
    • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於實際執行環境。

建立環境變數

在此範例中,在執行應用程式的本機電腦上將認證寫入環境變數。

前往 Azure 入口網站。 如果已成功部署您在 [必要條件] 區段中建立的資源,請選取 [後續步驟] 下的 [前往資源] 按鈕。 您可以在 [金鑰和端點] 頁面中 [資源管理] 底下找到金鑰和端點。 您的資源金鑰與您的 Azure 訂用帳戶識別碼不同。

若要設定金鑰和端點的環境變數,請開啟主控台視窗,然後遵循作業系統和開發環境的指示進行。

  • 若要設定 VISION_KEY 環境變數,請以您其中一個資源索引碼取代 <your_key>
  • 若要設定 VISION_ENDPOINT 環境變數,請將 <your_endpoint> 取代為您資源的端點。

重要

如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx VISION_KEY <your_key>
setx VISION_ENDPOINT <your_endpoint>

新增環境變數之後,您可能需要重新啟動任何將讀取環境變數的執行中程式,包括主控台視窗。

分析影像

  1. 建立新的 C# 應用程式。

    使用 Visual Studio,建立新的 .NET Core 應用程式。

    安裝用戶端程式庫

    建立新專案後,以滑鼠右鍵按一下 [方案總管] 中的專案解決方案,然後選取 [管理 NuGet 套件],以安裝用戶端程式庫。 在開啟的套件管理員中,選取 [瀏覽]、核取 [包含發行前版本],然後搜尋 Microsoft.Azure.CognitiveServices.Vision.ComputerVision。 選取版本 7.0.0,然後 安裝

  2. 從專案目錄,在慣用的編輯器或 IDE 中開啟 Program.cs 檔案。 貼上下列程式碼:

    using System;
    using System.Collections.Generic;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
    using System.Threading.Tasks;
    using System.IO;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Threading;
    using System.Linq;
    
    namespace ComputerVisionQuickstart
    {
        class Program
        {
            // Add your Computer Vision key and endpoint
            static string key = Environment.GetEnvironmentVariable("VISION_KEY");
            static string endpoint = Environment.GetEnvironmentVariable("VISION_ENDPOINT");
    
            // URL image used for analyzing an image (image of puppy)
            private const string ANALYZE_URL_IMAGE = "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png";
    
            static void Main(string[] args)
            {
                Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
                Console.WriteLine();
    
                // Create a client
                ComputerVisionClient client = Authenticate(endpoint, key);
    
                // Analyze an image to get features and other properties.
                AnalyzeImageUrl(client, ANALYZE_URL_IMAGE).Wait();
            }
    
            /*
             * AUTHENTICATE
             * Creates a Computer Vision client used by each example.
             */
            public static ComputerVisionClient Authenticate(string endpoint, string key)
            {
                ComputerVisionClient client =
                  new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
                  { Endpoint = endpoint };
                return client;
            }
           
            public static async Task AnalyzeImageUrl(ComputerVisionClient client, string imageUrl)
            {
                Console.WriteLine("----------------------------------------------------------");
                Console.WriteLine("ANALYZE IMAGE - URL");
                Console.WriteLine();
    
                // Creating a list that defines the features to be extracted from the image. 
    
                List<VisualFeatureTypes?> features = new List<VisualFeatureTypes?>()
                {
                    VisualFeatureTypes.Tags
                };
    
                Console.WriteLine($"Analyzing the image {Path.GetFileName(imageUrl)}...");
                Console.WriteLine();
                // Analyze the URL image 
                ImageAnalysis results = await client.AnalyzeImageAsync(imageUrl, visualFeatures: features);
    
                // Image tags and their confidence score
                Console.WriteLine("Tags:");
                foreach (var tag in results.Tags)
                {
                    Console.WriteLine($"{tag.Name} {tag.Confidence}");
                }
                Console.WriteLine();
            }
        }
    }
    

    重要

    完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  3. 執行應用程式

    按一下 IDE 視窗頂端的 [偵錯] 按鈕,以執行應用程式。


輸出

----------------------------------------------------------
ANALYZE IMAGE - URL

Analyzing the image sample16.png...

Tags:
grass 0.9957543611526489
dog 0.9939157962799072
mammal 0.9928356409072876
animal 0.9918001890182495
dog breed 0.9890419244766235
pet 0.974603533744812
outdoor 0.969241738319397
companion dog 0.906731367111206
small greek domestic dog 0.8965123891830444
golden retriever 0.8877675533294678
labrador retriever 0.8746421337127686
puppy 0.872604250907898
ancient dog breeds 0.8508287668228149
field 0.8017748594284058
retriever 0.6837497353553772
brown 0.6581960916519165

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

在本快速入門中,您已了解如何安裝影像分析用戶端程式庫,並進行基本的影像分析呼叫。 接下來,深入了解分析 API 功能。

使用適用於 Python 的影像分析用戶端程式庫來分析遠端影像的內容標記。

提示

您也可以分析本機影像。 請參閱 ComputerVisionClientOperationsMixin 方法,例如 analyze_image_in_stream。 或如需本機映像的相關案例,請參閱 GitHub 上的範例程式碼。

提示

分析 API 可以執行產生影像標記以外的許多不同作業。 如需展示所有可用功能的範例,請參閱影像分析操作指南

參考文件 | 程式庫原始程式碼 | 套件 (PiPy) | 範例

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶

  • Python 3.x

    • 您安裝的 Python 應包含 pip。 您可以在命令列上執行 pip --version 來檢查是否已安裝 pip。 安裝最新版本的 Python 以取得 pip。
  • 擁有 Azure 訂用帳戶之後,在 Azure 入口網站中建立視覺資源,以取得您的金鑰和端點。 在其部署後,選取 [前往資源]

    • 您需要來自所建立資源的金鑰和端點,以便將應用程式連線至 Azure AI 視覺服務。
    • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於實際執行環境。

建立環境變數

在此範例中,在執行應用程式的本機電腦上將認證寫入環境變數。

前往 Azure 入口網站。 如果已成功部署您在 [必要條件] 區段中建立的資源,請選取 [後續步驟] 下的 [前往資源] 按鈕。 您可以在 [金鑰和端點] 頁面中 [資源管理] 底下找到金鑰和端點。 您的資源金鑰與您的 Azure 訂用帳戶識別碼不同。

若要設定金鑰和端點的環境變數,請開啟主控台視窗,然後遵循作業系統和開發環境的指示進行。

  • 若要設定 VISION_KEY 環境變數,請以您其中一個資源索引碼取代 <your_key>
  • 若要設定 VISION_ENDPOINT 環境變數,請將 <your_endpoint> 取代為您資源的端點。

重要

如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx VISION_KEY <your_key>
setx VISION_ENDPOINT <your_endpoint>

新增環境變數之後,您可能需要重新啟動任何將讀取環境變數的執行中程式,包括主控台視窗。

分析影像

  1. 安裝用戶端程式庫。

    您可以使用下列命令來安裝用戶端程式庫:

    pip install --upgrade azure-cognitiveservices-vision-computervision
    

    也可以安裝 Pillow 程式庫。

    pip install pillow
    
  2. 建立新的 Python 應用程式。

    建立新的 Python 指令碼,例如 quickstart-file.py

  3. 在文字編輯器或 IDE 中開啟 quickstart-file.py,然後貼上下列程式碼。

    from azure.cognitiveservices.vision.computervision import ComputerVisionClient
    from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
    from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
    from msrest.authentication import CognitiveServicesCredentials
    
    from array import array
    import os
    from PIL import Image
    import sys
    import time
    
    '''
    Authenticate
    Authenticates your credentials and creates a client.
    '''
    subscription_key = os.environ["VISION_KEY"]
    endpoint = os.environ["VISION_ENDPOINT"]
    
    computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
    '''
    END - Authenticate
    '''
    
    '''
    Quickstart variables
    These variables are shared by several examples
    '''
    # Images used for the examples: Describe an image, Categorize an image, Tag an image, 
    # Detect faces, Detect adult or racy content, Detect the color scheme, 
    # Detect domain-specific content, Detect image types, Detect objects
    images_folder = os.path.join (os.path.dirname(os.path.abspath(__file__)), "images")
    remote_image_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg"
    '''
    END - Quickstart variables
    '''
    
    
    '''
    Tag an Image - remote
    This example returns a tag (key word) for each thing in the image.
    '''
    print("===== Tag an image - remote =====")
    # Call API with remote image
    tags_result_remote = computervision_client.tag_image(remote_image_url )
    
    # Print results with confidence score
    print("Tags in the remote image: ")
    if (len(tags_result_remote.tags) == 0):
        print("No tags detected.")
    else:
        for tag in tags_result_remote.tags:
            print("'{}' with confidence {:.2f}%".format(tag.name, tag.confidence * 100))
    print()
    '''
    END - Tag an Image - remote
    '''
    print("End of Computer Vision quickstart.")
    
  4. 使用快速入門檔案上使用 python 命令執行應用程式。

    python quickstart-file.py
    

輸出

===== Tag an image - remote =====
Tags in the remote image:
'outdoor' with confidence 99.00%
'building' with confidence 98.81%
'sky' with confidence 98.21%
'stadium' with confidence 98.17%
'ancient rome' with confidence 96.16%
'ruins' with confidence 95.04%
'amphitheatre' with confidence 93.99%
'ancient roman architecture' with confidence 92.65%
'historic site' with confidence 89.55%
'ancient history' with confidence 89.54%
'history' with confidence 86.72%
'archaeological site' with confidence 84.41%
'travel' with confidence 65.85%
'large' with confidence 61.02%
'city' with confidence 56.57%

End of Azure AI Vision quickstart.

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

在本快速入門中,您已了解如何安裝影像分析用戶端程式庫,並進行基本的影像分析呼叫。 接下來,深入了解分析 API 功能。

使用影像分析用戶端程式庫來分析遠端影像中的標記、文字描述、臉部、成人內容等等。

提示

您也可以分析本機影像。 請參閱 ComputerVision 方法,例如 AnalyzeImage。 或如需本機映像的相關案例,請參閱 GitHub 上的範例程式碼。

提示

分析 API 可以執行產生影像標記以外的許多不同作業。 如需展示所有可用功能的範例,請參閱影像分析操作指南

參考文件 | 程式庫原始程式碼 |成品 (Maven) | 範例

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 最新版的 Java Development Kit (JDK)
  • Gradle 建置工具,或其他相依性管理員。
  • 擁有 Azure 訂用帳戶之後,在 Azure 入口網站中建立視覺資源,以取得您的金鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要來自所建立資源的金鑰和端點,以便將應用程式連線至 Azure AI 視覺服務。
    • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於實際執行環境。

建立環境變數

在此範例中,在執行應用程式的本機電腦上將認證寫入環境變數。

前往 Azure 入口網站。 如果已成功部署您在 [必要條件] 區段中建立的資源,請選取 [後續步驟] 下的 [前往資源] 按鈕。 您可以在 [金鑰和端點] 頁面中 [資源管理] 底下找到金鑰和端點。 您的資源金鑰與您的 Azure 訂用帳戶識別碼不同。

若要設定金鑰和端點的環境變數,請開啟主控台視窗,然後遵循作業系統和開發環境的指示進行。

  • 若要設定 VISION_KEY 環境變數,請以您其中一個資源索引碼取代 <your_key>
  • 若要設定 VISION_ENDPOINT 環境變數,請將 <your_endpoint> 取代為您資源的端點。

重要

如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx VISION_KEY <your_key>
setx VISION_ENDPOINT <your_endpoint>

新增環境變數之後,您可能需要重新啟動任何將讀取環境變數的執行中程式,包括主控台視窗。

分析影像

  1. 建立新的 Gradle 專案。

    在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

    mkdir myapp && cd myapp
    

    從您的工作目錄執行 gradle init 命令。 此命令會建立 Gradle 的基本組建檔案,包括 build.gradle.kts,此檔案將在執行階段用來建立及設定您的應用程式。

    gradle init --type basic
    

    出現選擇 DSL 的提示時,請選取 [Kotlin]

  2. 安裝用戶端程式庫。

    本快速入門會使用 Gradle 相依性管理員。 您可以在 Maven 中央存放庫中找到用戶端程式庫和其他相依性管理員的資訊。

    找出 build.gradle.kts,並使用您慣用的 IDE 或文字編輯器加以開啟。 然後,在其中複製下列組建組態。 此組態會將專案定義為進入點為 ImageAnalysisQuickstart 類別的 JAVA 應用程式。 它會匯入 Azure AI 視覺程式庫。

    plugins {
        java
        application
    }
    application { 
        mainClass.set("ImageAnalysisQuickstart")
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        implementation(group = "com.microsoft.azure.cognitiveservices", name = "azure-cognitiveservices-computervision", version = "1.0.9-beta")
    }
    
  3. 建立 Java 檔案。

    在您的工作目錄中執行下列命令,以建立專案來源資料夾:

    mkdir -p src/main/java
    

    瀏覽至新的資料夾,並建立名為 ImageAnalysisQuickstart.java 的檔案。

  4. 在慣用的編輯器或 IDE 中開啟 ImageAnalysisQuickstart.java,並貼上下列程式碼。

    import com.microsoft.azure.cognitiveservices.vision.computervision.*;
    import com.microsoft.azure.cognitiveservices.vision.computervision.implementation.ComputerVisionImpl;
    import com.microsoft.azure.cognitiveservices.vision.computervision.models.*;
    
    import java.io.*;
    import java.nio.file.Files;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    public class ImageAnalysisQuickstart {
    
        // Use environment variables
        static String key = System.getenv("VISION_KEY");
        static String endpoint = System.getenv("VISION_ENDPOINT");
    
        public static void main(String[] args) {
            
            System.out.println("\nAzure Cognitive Services Computer Vision - Java Quickstart Sample");
    
            // Create an authenticated Computer Vision client.
            ComputerVisionClient compVisClient = Authenticate(key, endpoint); 
    
            // Analyze local and remote images
            AnalyzeRemoteImage(compVisClient);
    
        }
    
        public static ComputerVisionClient Authenticate(String key, String endpoint){
            return ComputerVisionManager.authenticate(key).withEndpoint(endpoint);
        }
    
    
        public static void AnalyzeRemoteImage(ComputerVisionClient compVisClient) {
            /*
             * Analyze an image from a URL:
             *
             * Set a string variable equal to the path of a remote image.
             */
            String pathToRemoteImage = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/faces.jpg";
    
            // This list defines the features to be extracted from the image.
            List<VisualFeatureTypes> featuresToExtractFromRemoteImage = new ArrayList<>();
            featuresToExtractFromRemoteImage.add(VisualFeatureTypes.TAGS);
    
            System.out.println("\n\nAnalyzing an image from a URL ...");
    
            try {
                // Call the Computer Vision service and tell it to analyze the loaded image.
                ImageAnalysis analysis = compVisClient.computerVision().analyzeImage().withUrl(pathToRemoteImage)
                        .withVisualFeatures(featuresToExtractFromRemoteImage).execute();
    
    
                // Display image tags and confidence values.
                System.out.println("\nTags: ");
                for (ImageTag tag : analysis.tags()) {
                    System.out.printf("\'%s\' with confidence %f\n", tag.name(), tag.confidence());
                }
            }
    
            catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        // END - Analyze an image from a URL.
    
    }
    
  5. 瀏覽回專案根資料夾,並使用下列項目建置應用程式:

    gradle build
    

    然後,使用 gradle run 命令加以執行:

    gradle run
    

輸出

Azure AI Vision - Java Quickstart Sample

Analyzing an image from a URL ...

Tags:
'person' with confidence 0.998895
'human face' with confidence 0.997437
'smile' with confidence 0.991973
'outdoor' with confidence 0.985962
'happy' with confidence 0.969785
'clothing' with confidence 0.961570
'friendship' with confidence 0.946441
'tree' with confidence 0.917331
'female person' with confidence 0.890976
'girl' with confidence 0.888741
'social group' with confidence 0.872044
'posing' with confidence 0.865493
'adolescent' with confidence 0.857371
'love' with confidence 0.852553
'laugh' with confidence 0.850097
'people' with confidence 0.849922
'lady' with confidence 0.844540
'woman' with confidence 0.818172
'group' with confidence 0.792975
'wedding' with confidence 0.615252
'dress' with confidence 0.517169

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

在本快速入門中,您已了解如何安裝影像分析用戶端程式庫,並進行基本的影像分析呼叫。 接下來,深入了解分析 API 功能。

使用適用於 JavaScript 的影像分析用戶端程式庫來分析遠端影像的內容標記。

提示

您也可以分析本機影像。 請參閱 ComputerVisionClient 方法,例如 describeImageInStream。 或如需本機映像的相關案例,請參閱 GitHub 上的範例程式碼。

提示

分析 API 可以執行產生影像標記以外的許多不同作業。 如需展示所有可用功能的範例,請參閱影像分析操作指南

參考文件 | 套件 (npm) | 範例

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 最新版的 Node.js
  • 擁有 Azure 訂用帳戶之後,在 Azure 入口網站中建立視覺資源,以取得您的金鑰和端點。 在其部署後,選取 [前往資源]
    • 您需要來自所建立資源的金鑰和端點,以便將應用程式連線至 Azure AI 視覺服務。
    • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於實際執行環境。

建立環境變數

在此範例中,在執行應用程式的本機電腦上將認證寫入環境變數。

前往 Azure 入口網站。 如果已成功部署您在 [必要條件] 區段中建立的資源,請選取 [後續步驟] 下的 [前往資源] 按鈕。 您可以在 [金鑰和端點] 頁面中 [資源管理] 底下找到金鑰和端點。 您的資源金鑰與您的 Azure 訂用帳戶識別碼不同。

若要設定金鑰和端點的環境變數,請開啟主控台視窗,然後遵循作業系統和開發環境的指示進行。

  • 若要設定 VISION_KEY 環境變數,請以您其中一個資源索引碼取代 <your_key>
  • 若要設定 VISION_ENDPOINT 環境變數,請將 <your_endpoint> 取代為您資源的端點。

重要

如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx VISION_KEY <your_key>
setx VISION_ENDPOINT <your_endpoint>

新增環境變數之後,您可能需要重新啟動任何將讀取環境變數的執行中程式,包括主控台視窗。

分析影像

  1. 建立新的 Node.js 應用程式

    在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

    mkdir myapp && cd myapp
    

    執行命令 npm init,以使用 package.json 檔案建立節點應用程式。

    npm init
    

    安裝用戶端程式庫

    安裝 ms-rest-azure@azure/cognitiveservices-computervision npm 套件:

    npm install @azure/cognitiveservices-computervision
    

    也請安裝非同步模組:

    npm install async
    

    您應用程式的 package.json 檔案會隨著相依性而更新。

    建立新檔案 index.js

  2. 在文字編輯器中開啟 index.js,然後貼上下列程式碼。

    'use strict';
    
    const async = require('async');
    const fs = require('fs');
    const https = require('https');
    const path = require("path");
    const createReadStream = require('fs').createReadStream
    const sleep = require('util').promisify(setTimeout);
    const ComputerVisionClient = require('@azure/cognitiveservices-computervision').ComputerVisionClient;
    const ApiKeyCredentials = require('@azure/ms-rest-js').ApiKeyCredentials;
    
    /**
     * AUTHENTICATE
     * This single client is used for all examples.
     */
    const key = process.env.VISION_KEY;
    const endpoint = process.env.VISION_ENDPOINT;
    
    
    const computerVisionClient = new ComputerVisionClient(
      new ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': key } }), endpoint);
    /**
     * END - Authenticate
     */
    
    
    function computerVision() {
      async.series([
        async function () {
    
          /**
           * DETECT TAGS  
           * Detects tags for an image, which returns:
           *     all objects in image and confidence score.
           */
          console.log('-------------------------------------------------');
          console.log('DETECT TAGS');
          console.log();
    
          // Image of different kind of dog.
          const tagsURL = 'https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png';
    
          // Analyze URL image
          console.log('Analyzing tags in image...', tagsURL.split('/').pop());
          const tags = (await computerVisionClient.analyzeImage(tagsURL, { visualFeatures: ['Tags'] })).tags;
          console.log(`Tags: ${formatTags(tags)}`);
    
          // Format tags for display
          function formatTags(tags) {
            return tags.map(tag => (`${tag.name} (${tag.confidence.toFixed(2)})`)).join(', ');
          }
          /**
           * END - Detect Tags
           */
          console.log();
          console.log('-------------------------------------------------');
          console.log('End of quickstart.');
    
        },
        function () {
          return new Promise((resolve) => {
            resolve();
          })
        }
      ], (err) => {
        throw (err);
      });
    }
    
    computerVision();
    
  3. 使用快速入門檔案上使用 node 命令執行應用程式。

    node index.js
    

輸出

-------------------------------------------------
DETECT TAGS

Analyzing tags in image... sample16.png
Tags: grass (1.00), dog (0.99), mammal (0.99), animal (0.99), dog breed (0.99), pet (0.97), outdoor (0.97), companion dog (0.91), small greek domestic dog (0.90), golden retriever (0.89), labrador retriever (0.87), puppy (0.87), ancient dog breeds (0.85), field (0.80), retriever (0.68), brown (0.66)

-------------------------------------------------
End of quickstart.

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

在本快速入門中,您已了解如何安裝影像分析用戶端程式庫,並進行基本的影像分析呼叫。 接下來,深入了解分析 API 功能。

使用影像分析 REST API 來分析標籤的影像。

提示

分析 API 可以執行產生影像標記以外的許多不同作業。 如需展示所有可用功能的範例,請參閱影像分析操作指南

注意

本快速入門會使用 cURL 命令來呼叫 REST API。 您也可以使用程式設計語言來呼叫 REST API。 如需 C#PythonJavaJavaScript 的範例,請參閱 GitHub 範例。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 擁有 Azure 訂用帳戶之後,在 Azure 入口網站中建立視覺資源,以取得您的金鑰和端點。 在其部署後,選取 [前往資源]
    • 您將需要來自所建立資源的金鑰和端點,以便將應用程式連線至 Azure AI 視覺服務。 您稍後會在快速入門中將金鑰和端點貼到下列程式碼中。
    • 您可以使用免費定價層 (F0) 來試用服務,之後可升級至付費層以用於實際執行環境。
  • 已安裝 cURL

分析影像

若要分析影像中的各種視覺特徵,請執行下列步驟:

  1. 將下列 命令複製到文字編輯器。

    curl.exe -H "Ocp-Apim-Subscription-Key: <subscriptionKey>" -H "Content-Type: application/json" "https://westcentralus.api.cognitive.microsoft.com/vision/v3.2/analyze?visualFeatures=Tags" -d "{'url':'https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png'}"
    
  2. 視需要在命令中進行下列變更:

    1. <subscriptionKey> 的值取代為您的金鑰。
    2. 將要求 URL 的第一個部分 (westcentralus) 取代為您端點 URL 中的文字。

      注意

      2019 年 7 月 1 日之後建立的新資源會使用自訂的子網域名稱。 如需詳細資訊和完整的區域端點清單,請參閱 Azure AI 服務的自訂子網域名稱

    3. (選擇性) 將要求本文 (https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png) 中的影像 URL 變更為要分析之不同影像的 URL。
  3. 開啟 [命令提示字元] 視窗。

  4. 從文字編輯器將經過編輯的 curl 命令貼上到命令提示字元視窗中,然後執行該命令。

檢查回應

成功的回應會以 JSON 的形式傳回。 範例應用程式會在命令提示字元視窗中剖析並顯示成功的回應,如下列範例所示:

{{
   "tags":[
      {
         "name":"text",
         "confidence":0.9992657899856567
      },
      {
         "name":"post-it note",
         "confidence":0.9879657626152039
      },
      {
         "name":"handwriting",
         "confidence":0.9730165004730225
      },
      {
         "name":"rectangle",
         "confidence":0.8658561706542969
      },
      {
         "name":"paper product",
         "confidence":0.8561884760856628
      },
      {
         "name":"purple",
         "confidence":0.5961999297142029
      }
   ],
   "requestId":"2788adfc-8cfb-43a5-8fd6-b3a9ced35db2",
   "metadata":{
      "height":945,
      "width":1000,
      "format":"Jpeg"
   },
   "modelVersion":"2021-05-01"
}

下一步

在本快速入門中,您已了解如何使用 REST API 進行基本影像分析呼叫。 接下來,深入了解分析 API 功能。