快速入门:图像分析

开始使用图像分析 REST API 或客户端库来设置基本的图像标记脚本。 分析图像服务提供 AI 算法,可用于处理图像并返回其视觉特征的相关信息。 请按照以下步骤将包安装到应用程序中并试用示例代码。

使用适用于 C# 的图像分析客户端库分析内容标记的图像。 此快速入门定义了 AnalyzeImageUrl 方法,该方法使用客户端对象来分析远程图像并输出结果。

参考文档 | 库源代码 | 包 (NuGet) | 示例

提示

还可以分析本地图像。 请参阅 ComputerVisionClient 方法,例如 AnalyzeImageInStreamAsync。 或者,请参阅 GitHub 上的示例代码,了解涉及本地图像的方案。

提示

除了生成图像标记之外,Analyze API 还可以执行许多不同的操作。 有关展示所有可用功能的示例,请参阅图像分析操作指南

先决条件

  • Azure 订阅 - 创建试用订阅
  • Visual Studio IDE 或最新版本的 .NET Core
  • 拥有 Azure 订阅后,请在 Azure 门户中创建计算机视觉资源 ,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 Azure AI 视觉服务。
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。

创建环境变量

在此示例中,将凭据写入运行应用程序的本地计算机上的环境变量。

转到 Azure 门户。 如果在“先决条件”部分创建的资源部署成功,请选择“后续步骤”下的“转到资源”。 在“密钥和终结点”页的“资源管理”下,可以找到密钥和终结点。 你的资源密钥与你的 Azure 订阅 ID 不同。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为密钥和终结点设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 VISION_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 VISION_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
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.chinacloudapi.cn/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 服务安全性一文。

  1. 运行应用程序

    单击 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 上的示例代码,了解涉及本地图像的方案。

提示

除了生成图像标记之外,Analyze API 还可以执行许多不同的操作。 有关展示所有可用功能的示例,请参阅图像分析操作指南

参考文档 | 库源代码 | 包 (PiPy) | 示例

先决条件

  • Azure 订阅 - 创建试用订阅

  • Python 3.x

    • 你的 Python 安装应包含 pip。 可以通过在命令行上运行 pip --version 来检查是否安装了 pip。 通过安装最新版本的 Python 获取 pip。
  • 拥有 Azure 订阅后,请在 Azure 门户中创建视觉资源,以获取密钥和终结点。 部署后,选择”转到资源”。

    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 Azure AI 视觉服务。
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。

创建环境变量

在此示例中,将凭据写入运行应用程序的本地计算机上的环境变量。

转到 Azure 门户。 如果在“先决条件”部分创建的资源部署成功,请选择“后续步骤”下的“转到资源”。 在“密钥和终结点”页的“资源管理”下,可以找到密钥和终结点。 你的资源密钥与你的 Azure 订阅 ID 不同。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为密钥和终结点设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 VISION_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 VISION_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
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.")
  1. 在快速入门文件中使用 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 上的示例代码,了解涉及本地图像的方案。

提示

除了生成图像标记之外,Analyze API 还可以执行许多不同的操作。 有关展示所有可用功能的示例,请参阅图像分析操作指南

参考文档 | 库源代码 |项目 (Maven) | 示例

先决条件

  • Azure 订阅 - 创建试用订阅
  • 最新版的 Java 开发工具包 (JDK)
  • Gradle 生成工具,或其他依赖项管理器。
  • 拥有 Azure 订阅后,请在 Azure 门户中创建视觉资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 Azure AI 视觉服务。
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。

创建环境变量

在此示例中,将凭据写入运行应用程序的本地计算机上的环境变量。

转到 Azure 门户。 如果在“先决条件”部分创建的资源部署成功,请选择“后续步骤”下的“转到资源”。 在“密钥和终结点”页的“资源管理”下,可以找到密钥和终结点。 你的资源密钥与你的 Azure 订阅 ID 不同。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为密钥和终结点设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 VISION_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 VISION_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
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 或文本编辑器将其打开。 然后在该文件中复制以下生成配置。 此配置将项目定义为一个 Java 应用程序,其入口点为 ImageAnalysisQuickstart 类。 它会导入 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.

}
  1. 导航回项目根文件夹,并通过以下内容生成应用:

    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 上的示例代码,了解涉及本地图像的方案。

提示

除了生成图像标记之外,Analyze API 还可以执行许多不同的操作。 有关展示所有可用功能的示例,请参阅图像分析操作指南

参考文档 | 库源代码 | 包 (npm) | 示例

先决条件

  • Azure 订阅 - 创建试用订阅
  • 最新版本的 Node.js
  • 拥有 Azure 订阅后,请在 Azure 门户中创建视觉资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 Azure AI 视觉服务。
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。

创建环境变量

在此示例中,将凭据写入运行应用程序的本地计算机上的环境变量。

转到 Azure 门户。 如果在“先决条件”部分创建的资源部署成功,请选择“后续步骤”下的“转到资源”。 在“密钥和终结点”页的“资源管理”下,可以找到密钥和终结点。 你的资源密钥与你的 Azure 订阅 ID 不同。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为密钥和终结点设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 VISION_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 VISION_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

添加环境变量后,可能需要重启任何正在运行的、将读取环境变量的程序(包括控制台窗口)。

分析图像

  1. 创建新的 Node.js 应用程序

    在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

    mkdir myapp && cd myapp
    

    运行 npm init 命令以使用 package.json 文件创建一个 node 应用程序。

    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.chinacloudapi.cn/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();
  1. 在快速入门文件中使用 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 来分析图像的标记。

提示

除了生成图像标记之外,Analyze API 还可以执行许多不同的操作。 有关展示所有可用功能的示例,请参阅图像分析操作指南

注意

此快速入门使用 cURL 命令来调用 REST API。 也可以使用编程语言调用 REST API。 请参阅 GitHub 示例,查看 C#PythonJavaJavaScript 的相关示例。

先决条件

  • Azure 订阅 - 创建试用订阅
  • 拥有 Azure 订阅后,请在 Azure 门户中创建视觉资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 Azure AI 视觉服务。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。
  • 已安装 cURL

分析图像

若要分析图像的各种视觉特征,请执行以下步骤:

  1. 将以下命令复制到文本编辑器中。

    curl.exe -H "Ocp-Apim-Subscription-Key: <subscriptionKey>" -H "Content-Type: application/json" "https://chinaeast2.api.cognitive.azure.cn/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 的第一部分 (chinaeast2) 替换为你自己的终结点 URL 中的文本。

      注意

      2019 年 7 月 1 日之后创建的新资源将使用自定义子域名。 有关详细信息和区域终结点的完整列表,请参阅 Azure AI 服务的自定义子域名

    3. (可选)将请求正文中的图像 URL (https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png) 更改为要分析的其他图像的 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 功能。