呼叫影像分析 4.0 分析 API

本文將示範如何呼叫影像分析 4.0 API,以傳回與該影像視覺特徵相關的資訊。 此外也會說明如何剖析傳回的資訊。

必要條件

本指南假設您已遵循快速入門頁面中所述的步驟。 這表示:

  • 已建立電腦視覺資源並擁有金鑰與端點 URL。
  • 您已安裝適當的 SDK 套件,而且您有執行中的快速入門應用程式。 您可以根據這裡的程式碼範例修改此快速入門應用程式。

建立及驗證用戶端

若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。 本指南假設您已使用金鑰和端點來定義環境變數VISION_KEYVISION_ENDPOINT

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

從建立 ImageAnalysisClient 對象開始。 例如:

string endpoint = Environment.GetEnvironmentVariable("VISION_ENDPOINT");
string key = Environment.GetEnvironmentVariable("VISION_KEY");

// Create an Image Analysis client.
ImageAnalysisClient client = new ImageAnalysisClient(
    new Uri(endpoint),
    new AzureKeyCredential(key));

選取要分析的影像

您可以藉由提供可公開存取的影像 URL,或將二進位數據傳遞至 SDK,來選取影像。 請參閱 支援影像格式的影像需求

圖像 URL

為您想要分析的影像建立 URI 物件。

Uri imageURL = new Uri("https://aka.ms/azsdk/image-analysis/sample.jpg");

影像緩衝區

或者,您可以透過 BinaryData 物件將影像資料傳遞至 SDK。 例如,從您想要分析的本機圖像檔讀取。

using FileStream stream = new FileStream("sample.jpg", FileMode.Open);
BinaryData imageData = BinaryData.FromStream(stream);

選取視覺效果功能

分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例選擇要執行的作業。 如需每項功能的描述,請參閱概觀。 本節中的範例會新增所有 可用的視覺功能,但為了實際使用,您可能需要較少的功能。

重要

視覺效果功能和CaptionsDenseCaptions僅支援下列 Azure 區域:美國東部、法國中部、韓國中部、北歐、東南亞、西歐、美國西部。

VisualFeatures visualFeatures =
    VisualFeatures.Caption |
    VisualFeatures.DenseCaptions |
    VisualFeatures.Objects |
    VisualFeatures.Read |
    VisualFeatures.Tags |
    VisualFeatures.People |
    VisualFeatures.SmartCrops;

選取分析選項

使用 ImageAnalysisOptions 物件來指定分析 API 呼叫的各種選項。

  • 語言:您可以指定傳回數據的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺特徵,請參閱語言支援
  • 性別中性 標題:如果您要擷取 標題 或密集 標題(使用 VisualFeatures.CaptionVisualFeatures.DenseCaptions),您可以要求性別中性 標題。 性別中性 標題 是選擇性的,預設為性別 標題。 例如,在英文中,當您選取性別中性標題時,像是女人男人等字詞會取代為,而男孩女孩則會取代為小孩
  • 裁剪外觀比例:將目標裁剪寬度除以高度來計算外觀比例。 支援的值從 0.75 到 1.8 (含)。 只有在選取 VisualFeatures.SmartCrops 做為視覺功能清單的一部分時,才能設定此屬性。 如果您選取 VisualFeatures.SmartCrops 但未指定外觀比例,則服務會傳回一個裁剪建議,其中包含其外觀比例。 在此案例中,外觀比例介於 0.5 到 2.0 (含) 之間。
ImageAnalysisOptions options = new ImageAnalysisOptions { 
    GenderNeutralCaption = true,
    Language = "en",
    SmartCropsAspectRatios = new float[] { 0.9F, 1.33F }};

呼叫分析 API

本節說明如何對服務進行分析呼叫。

在 ImageAnalysisClient 物件上呼叫 Analyze 方法,如下所示。 呼叫是同步的,而且會封鎖直到服務傳回結果或發生錯誤為止。 或者,您可以呼叫非封鎖 的 AnalyzeAsync 方法。

使用在上述各節中建立的輸入物件。 若要從影像緩衝區而不是 URL 進行分析,請將方法呼叫中的 取代 imageURLimageData 變數。

ImageAnalysisResult result = client.Analyze(
    imageURL,
    visualFeatures,
    options);

取得來自服務的結果

下列程式代碼示範如何剖析各種分析作業的結果。

Console.WriteLine("Image analysis results:");

// Print caption results to the console
Console.WriteLine(" Caption:");
Console.WriteLine($"   '{result.Caption.Text}', Confidence {result.Caption.Confidence:F4}");

// Print dense caption results to the console
Console.WriteLine(" Dense Captions:");
foreach (DenseCaption denseCaption in result.DenseCaptions.Values)
{
    Console.WriteLine($"   '{denseCaption.Text}', Confidence {denseCaption.Confidence:F4}, Bounding box {denseCaption.BoundingBox}");
}

// Print object detection results to the console
Console.WriteLine(" Objects:");
foreach (DetectedObject detectedObject in result.Objects.Values)
{
    Console.WriteLine($"   '{detectedObject.Tags.First().Name}', Bounding box {detectedObject.BoundingBox.ToString()}");
}

// Print text (OCR) analysis results to the console
Console.WriteLine(" Read:");
foreach (DetectedTextBlock block in result.Read.Blocks)
    foreach (DetectedTextLine line in block.Lines)
    {
        Console.WriteLine($"   Line: '{line.Text}', Bounding Polygon: [{string.Join(" ", line.BoundingPolygon)}]");
        foreach (DetectedTextWord word in line.Words)
        {
            Console.WriteLine($"     Word: '{word.Text}', Confidence {word.Confidence.ToString("#.####")}, Bounding Polygon: [{string.Join(" ", word.BoundingPolygon)}]");
        }
    }

// Print tags results to the console
Console.WriteLine(" Tags:");
foreach (DetectedTag tag in result.Tags.Values)
{
    Console.WriteLine($"   '{tag.Name}', Confidence {tag.Confidence:F4}");
}

// Print people detection results to the console
Console.WriteLine(" People:");
foreach (DetectedPerson person in result.People.Values)
{
    Console.WriteLine($"   Person: Bounding box {person.BoundingBox.ToString()}, Confidence {person.Confidence:F4}");
}

// Print smart-crops analysis results to the console
Console.WriteLine(" SmartCrops:");
foreach (CropRegion cropRegion in result.SmartCrops.Values)
{
    Console.WriteLine($"   Aspect ratio: {cropRegion.AspectRatio}, Bounding box: {cropRegion.BoundingBox}");
}

// Print metadata
Console.WriteLine(" Metadata:");
Console.WriteLine($"   Model: {result.ModelVersion}");
Console.WriteLine($"   Image width: {result.Metadata.Width}");
Console.WriteLine($"   Image hight: {result.Metadata.Height}");

疑難排解

例外狀況處理

當您使用 .NET SDK 與影像分析互動時,沒有 200 (成功) 狀態代碼之服務的任何回應都會擲回例外狀況。 例如,如果您嘗試分析因 URL 中斷而無法存取的影像, 400 則會傳回狀態,指出不正確的要求,並擲回對應的例外狀況。

在下列代碼段中,會藉由攔截例外狀況並顯示錯誤的其他資訊,以正常方式處理錯誤。

var imageUrl = new Uri("https://some-host-name.com/non-existing-image.jpg");

try
{
    var result = client.Analyze(imageUrl, VisualFeatures.Caption);
}
catch (RequestFailedException e)
{
    if (e.Status != 200)
    {
        Console.WriteLine("Error analyzing image.");
        Console.WriteLine($"HTTP status code {e.Status}: {e.Message}");
    }
    else
    {
        throw;
    }
}

您可以在這裏深入瞭解如何啟用 SDK 記錄

必要條件

本指南假設您已遵循快速入門中所述的步驟。 這表示:

  • 已建立電腦視覺資源並擁有金鑰與端點 URL。
  • 您已安裝適當的 SDK 套件,而且您有執行中的快速入門應用程式。 您可以根據這裡的程式代碼範例來修改本快速入門應用程式。

建立及驗證用戶端

若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。 本指南假設您已使用金鑰和端點來定義環境變數VISION_KEYVISION_ENDPOINT

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

首先,使用其中一個建構函式建立 ImageAnalysisClient 物件。 例如:

client = ImageAnalysisClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key)
)

選取要分析的影像

您可以藉由提供可公開存取的影像 URL,或將影像數據讀入 SDK 的輸入緩衝區,來選取影像。 請參閱 支援影像格式的影像需求

圖像 URL

您可以使用下列範例影像 URL。

# Define image URL
image_url = "https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png"

影像緩衝區

或者,您可以將影像當做 位元組 物件傳入。 例如,從您想要分析的本機圖像檔讀取。

# Load image to analyze into a 'bytes' object
with open("sample.jpg", "rb") as f:
    image_data = f.read()

選取視覺效果功能

分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例選擇要執行的作業。 如需每項功能的描述,請參閱概觀。 本節中的範例會新增所有 可用的視覺功能,但為了實際使用,您可能需要較少的功能。

visual_features =[
        VisualFeatures.TAGS,
        VisualFeatures.OBJECTS,
        VisualFeatures.CAPTION,
        VisualFeatures.DENSE_CAPTIONS,
        VisualFeatures.READ,
        VisualFeatures.SMART_CROPS,
        VisualFeatures.PEOPLE,
    ]

使用選項呼叫analyze_from_url方法

下列程式代碼會呼叫 用戶端上的 analyze_from_url 方法,其中包含您上述選取的功能,以及下面定義的其他選項。 若要從影像緩衝區而不是 URL 進行分析,請改為image_data=image_data使用 作為第一個自變數來分析 方法

# Analyze all visual features from an image stream. This will be a synchronously (blocking) call.
result = client.analyze_from_url(
    image_url=image_url,
    visual_features=visual_features,
    smart_crops_aspect_ratios=[0.9, 1.33],
    gender_neutral_caption=True,
    language="en"
)

選取智慧裁剪外觀比例

外觀比例的計算方式是將目標裁剪寬度除以高度。 支援的值從 0.75 到 1.8 (含)。 只有在選取VisualFeatures.SMART_CROPS做為視覺功能清單的一部分時 才能設定此屬性。 如果您選取 VisualFeatures.SMART_CROPS 但未指定外觀比例,服務會傳回一個裁剪建議,其外觀比例會符合。 在此案例中,外觀比例介於 0.5 到 2.0 (含) 之間。

選取性別中性標題

如果您要擷取 標題 或密集 標題(使用 VisualFeatures.CAPTIONVisualFeatures.DENSE_CAPTIONS),您可以要求性別中性 標題。 性別中性 標題 是選擇性的,預設為性別 標題。 例如,在英文中,當您選取性別中性標題時,像是女人男人等字詞會取代為,而男孩女孩則會取代為小孩

指定語言

您可以指定傳回資料的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺特徵,請參閱語言支援

取得來自服務的結果

下列程式代碼示範如何剖析analyze_from_url分析作業的結果

# Print all analysis results to the console
print("Image analysis results:")

if result.caption is not None:
    print(" Caption:")
    print(f"   '{result.caption.text}', Confidence {result.caption.confidence:.4f}")

if result.dense_captions is not None:
    print(" Dense Captions:")
    for caption in result.dense_captions.list:
        print(f"   '{caption.text}', {caption.bounding_box}, Confidence: {caption.confidence:.4f}")

if result.read is not None:
    print(" Read:")
    for line in result.read.blocks[0].lines:
        print(f"   Line: '{line.text}', Bounding box {line.bounding_polygon}")
        for word in line.words:
            print(f"     Word: '{word.text}', Bounding polygon {word.bounding_polygon}, Confidence {word.confidence:.4f}")

if result.tags is not None:
    print(" Tags:")
    for tag in result.tags.list:
        print(f"   '{tag.name}', Confidence {tag.confidence:.4f}")

if result.objects is not None:
    print(" Objects:")
    for object in result.objects.list:
        print(f"   '{object.tags[0].name}', {object.bounding_box}, Confidence: {object.tags[0].confidence:.4f}")

if result.people is not None:
    print(" People:")
    for person in result.people.list:
        print(f"   {person.bounding_box}, Confidence {person.confidence:.4f}")

if result.smart_crops is not None:
    print(" Smart Cropping:")
    for smart_crop in result.smart_crops.list:
        print(f"   Aspect ratio {smart_crop.aspect_ratio}: Smart crop {smart_crop.bounding_box}")

print(f" Image height: {result.metadata.height}")
print(f" Image width: {result.metadata.width}")
print(f" Model version: {result.model_version}")

疑難排解

例外狀況

方法會 analyze 針對來自服務的非成功 HTTP 狀態代碼回應,引發 HttpResponseError 例外狀況。 例外 status_code 狀況是 HTTP 回應狀態代碼。 例外狀況 error.message 包含詳細的訊息,可讓您診斷問題:

try:
    result = client.analyze( ... )
except HttpResponseError as e:
    print(f"Status code: {e.status_code}")
    print(f"Reason: {e.reason}")
    print(f"Message: {e.error.message}")

例如,當您提供錯誤的驗證金鑰時:

Status code: 401
Reason: PermissionDenied
Message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.

或者,當您提供不存在或無法存取的影像 URL 時:

Status code: 400
Reason: Bad Request
Message: The provided image url is not accessible.

記錄

用戶端會使用標準 Python 記錄連結庫。 SDK 會記錄 HTTP 要求和回應詳細數據,這可能有助於疑難解答。 若要登入 stdout,請新增下列專案:

import sys
import logging

# Acquire the logger for this client library. Use 'azure' to affect both
# 'azure.core` and `azure.ai.vision.imageanalysis' libraries.
logger = logging.getLogger("azure")

# Set the desired logging level. logging.INFO or logging.DEBUG are good options.
logger.setLevel(logging.INFO)

# Direct logging output to stdout (the default):
handler = logging.StreamHandler(stream=sys.stdout)
# Or direct logging output to a file:
# handler = logging.FileHandler(filename = 'sample.log')
logger.addHandler(handler)

# Optional: change the default logging format. Here we add a timestamp.
formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
handler.setFormatter(formatter)

根據預設,記錄會修訂 URL 查詢字串的值、某些 HTTP 要求和響應標頭的值(包括 Ocp-Apim-Subscription-Key 保留密鑰),以及要求和響應承載。 若要在沒有修訂的情況下建立記錄,請在建立 ImageAnalysisClient時或當您在用戶端上呼叫 analyze 時設定 方法自變數logging_enable = True

# Create an Image Analysis client with none redacted log
client = ImageAnalysisClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
    logging_enable=True
)

只會針對記錄層級 logging.DEBUG 產生未修訂的記錄。 請務必保護未修改的記錄,以避免危害安全性。 如需詳細資訊,請參閱 在適用於 Python 的 Azure 連結庫中設定記錄

必要條件

本指南假設您已遵循快速入門頁面中的步驟。 這表示:

  • 已建立電腦視覺資源並擁有金鑰與端點 URL。
  • 您已安裝適當的 SDK 套件,而且您有執行中的快速入門應用程式。 您可以根據這裡的程式碼範例修改此快速入門應用程式。

建立及驗證用戶端

若要向影像分析服務進行驗證,您需要 電腦視覺 金鑰和端點 URL。 本指南假設您已使用金鑰和端點來定義環境變數VISION_KEYVISION_ENDPOINT

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

從建立 ImageAnalysisClient 對象開始。 例如:

String endpoint = System.getenv("VISION_ENDPOINT");
String key = System.getenv("VISION_KEY");

if (endpoint == null || key == null) {
    System.out.println("Missing environment variable 'VISION_ENDPOINT' or 'VISION_KEY'.");
    System.out.println("Set them before running this sample.");
    System.exit(1);
}

// Create a synchronous Image Analysis client.
ImageAnalysisClient client = new ImageAnalysisClientBuilder()
    .endpoint(endpoint)
    .credential(new KeyCredential(key))
    .buildClient();

選取要分析的影像

您可以藉由提供可公開存取的影像 URL,或將影像數據讀入 SDK 的輸入緩衝區,來選取影像。 請參閱 支援影像格式的影像需求

圖像 URL

建立 imageUrl 字串來保存您想要分析之影像的可公開存取 URL。

String imageUrl = "https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png";

影像緩衝區

或者,您可以使用 BinaryData 物件,將影像當作記憶體緩衝區傳入。 例如,從您想要分析的本機圖像檔讀取。

BinaryData imageData = BinaryData.fromFile(new File("sample.png").toPath());

選取視覺效果功能

分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例選擇要執行的作業。 如需每項功能的描述,請參閱概觀。 本節中的範例會新增所有 可用的視覺功能,但為了實際使用,您可能需要較少的功能。

重要

視覺效果功能 CaptionsDenseCaptions 僅支援下列 Azure 區域:美國東部、法國中部、韓國中部、北歐、東南亞、西歐、美國西部。

// visualFeatures: Select one or more visual features to analyze.
List<VisualFeatures> visualFeatures = Arrays.asList(
            VisualFeatures.SMART_CROPS,
            VisualFeatures.CAPTION,
            VisualFeatures.DENSE_CAPTIONS,
            VisualFeatures.OBJECTS,
            VisualFeatures.PEOPLE,
            VisualFeatures.READ,
            VisualFeatures.TAGS);

選取分析選項

使用 ImageAnalysisOptions 物件來指定分析 API 呼叫的各種選項。

  • 語言:您可以指定傳回數據的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺特徵,請參閱語言支援
  • 性別中性 標題:如果您要擷取 標題 或密集 標題(使用 VisualFeatures.CAPTIONVisualFeatures.DENSE_CAPTIONS),您可以要求性別中性 標題。 性別中性 標題 是選擇性的,預設為性別 標題。 例如,在英文中,當您選取性別中性標題時,像是女人男人等字詞會取代為,而男孩女孩則會取代為小孩
  • 裁剪外觀比例:將目標裁剪寬度除以高度來計算外觀比例。 支援的值從 0.75 到 1.8 (含)。 只有在選取VisualFeatures.SMART_CROPS做為視覺功能清單的一部分時 才能設定此屬性。 如果您選取 VisualFeatures.SMART_CROPS 但未指定外觀比例,服務會傳回一個裁剪建議,其外觀比例會符合。 在此案例中,外觀比例介於 0.5 到 2.0 (含) 之間。
// Specify analysis options (or set `options` to null for defaults)
ImageAnalysisOptions options = new ImageAnalysisOptions()
    .setLanguage("en")
    .setGenderNeutralCaption(true)
    .setSmartCropsAspectRatios(Arrays.asList(0.9, 1.33, 1.78));

呼叫 analyzeFromUrl 方法

本節說明如何對服務進行分析呼叫。

在 ImageAnalysisClient 物件上呼叫 analyzeFromUrl 方法,如下所示。 呼叫是同步的,而且會封鎖直到服務傳回結果或發生錯誤為止。 或者,您可以改用 ImageAnalysisAsyncClient 物件,並呼叫其 analyzeFromUrl 方法,這是非封鎖的。

若要從影像緩衝區而非 URL 進行分析,請改為呼叫 analyze 方法,並傳入 imageData 作為第一個自變數。

try {
    // Analyze all visual features from an image URL. This is a synchronous (blocking) call.
    ImageAnalysisResult result = client.analyzeFromUrl(
        imageUrl,
        visualFeatures,
        options);

    printAnalysisResults(result);

} catch (HttpResponseException e) {
    System.out.println("Exception: " + e.getClass().getSimpleName());
    System.out.println("Status code: " + e.getResponse().getStatusCode());
    System.out.println("Message: " + e.getMessage());
} catch (Exception e) {
    System.out.println("Message: " + e.getMessage());
}

取得來自服務的結果

下列程式代碼示範如何剖析 analyzeFromUrl分析作業的結果

// Print all analysis results to the console
public static void printAnalysisResults(ImageAnalysisResult result) {

    System.out.println("Image analysis results:");

    if (result.getCaption() != null) {
        System.out.println(" Caption:");
        System.out.println("   \"" + result.getCaption().getText() + "\", Confidence "
            + String.format("%.4f", result.getCaption().getConfidence()));
    }

    if (result.getDenseCaptions() != null) {
        System.out.println(" Dense Captions:");
        for (DenseCaption denseCaption : result.getDenseCaptions().getValues()) {
            System.out.println("   \"" + denseCaption.getText() + "\", Bounding box "
                + denseCaption.getBoundingBox() + ", Confidence " + String.format("%.4f", denseCaption.getConfidence()));
        }
    }

    if (result.getRead() != null) {
        System.out.println(" Read:");
        for (DetectedTextLine line : result.getRead().getBlocks().get(0).getLines()) {
            System.out.println("   Line: '" + line.getText()
                + "', Bounding polygon " + line.getBoundingPolygon());
            for (DetectedTextWord word : line.getWords()) {
                System.out.println("     Word: '" + word.getText()
                    + "', Bounding polygon " + word.getBoundingPolygon()
                    + ", Confidence " + String.format("%.4f", word.getConfidence()));
            }
        }
    }

    if (result.getTags() != null) {
        System.out.println(" Tags:");
        for (DetectedTag tag : result.getTags().getValues()) {
            System.out.println("   \"" + tag.getName() + "\", Confidence " + String.format("%.4f", tag.getConfidence()));
        }
    }

    if (result.getObjects() != null) {
        System.out.println(" Objects:");
        for (DetectedObject detectedObject : result.getObjects().getValues()) {
            System.out.println("   \"" + detectedObject.getTags().get(0).getName() + "\", Bounding box "
                + detectedObject.getBoundingBox() + ", Confidence " + String.format("%.4f", detectedObject.getTags().get(0).getConfidence()));
        }
    }

    if (result.getPeople() != null) {
        System.out.println(" People:");
        for (DetectedPerson person : result.getPeople().getValues()) {
            System.out.println("   Bounding box "
                + person.getBoundingBox() + ", Confidence " + String.format("%.4f", person.getConfidence()));
        }
    }

    if (result.getSmartCrops() != null) {
        System.out.println(" Crop Suggestions:");
        for (CropRegion cropRegion : result.getSmartCrops().getValues()) {
            System.out.println("   Aspect ratio "
                + cropRegion.getAspectRatio() + ": Bounding box " + cropRegion.getBoundingBox());
        }
    }

    System.out.println(" Image height = " + result.getMetadata().getHeight());
    System.out.println(" Image width = " + result.getMetadata().getWidth());
    System.out.println(" Model version = " + result.getModelVersion());
}

疑難排解

例外狀況

analyze 服務以非成功 HTTP 狀態代碼回應時,方法會擲回 HttpResponseException 。 例外狀況 getResponse().getStatusCode() 會保存 HTTP 回應狀態代碼。 例外狀況 getMessage() 包含詳細的訊息,可讓您診斷問題:

try {
    ImageAnalysisResult result = client.analyze(...)
} catch (HttpResponseException e) {
    System.out.println("Exception: " + e.getClass().getSimpleName());
    System.out.println("Status code: " + e.getResponse().getStatusCode());
    System.out.println("Message: " + e.getMessage());
} catch (Exception e) {
    System.out.println("Message: " + e.getMessage());
}

例如,當您提供錯誤的驗證金鑰時:

Exception: ClientAuthenticationException
Status code: 401
Message: Status code 401, "{"error":{"code":"401","message":"Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource."}}"

或者,當您以無法辨識的格式提供影像時:

Exception: HttpResponseException
Status code: 400
Message: Status code 400, "{"error":{"code":"InvalidRequest","message":"Image format is not valid.","innererror":{"code":"InvalidImageFormat","message":"Input data is not a valid image."}}}"

啟用 HTTP 要求/回應記錄

檢閱透過網路傳送至影像分析服務的 HTTP 要求或響應,對於疑難解答很有用。 影像分析客戶端連結庫支援內建的控制台記錄架構,以供暫時偵錯之用。 它也支援使用SLF4J介面進行更進階的記錄。 如需詳細資訊,請參閱 在 Azure SDK for Java 中使用記錄。

下列各節討論如何使用內建架構來啟用主控台記錄。

藉由設定環境變數

您可以藉由設定下列兩個環境變數,為整個應用程式啟用 HTTP 要求和回應的控制台記錄。 這項變更會影響支持記錄 HTTP 要求和回應的每個 Azure 用戶端。

  • 將環境變數 AZURE_LOG_LEVEL 設定為 debug
  • 將環境變數 AZURE_HTTP_LOG_DETAIL_LEVEL 設定為下列其中一個值:
記錄層級
none HTTP 要求/回應記錄已停用
basic 僅記錄 URL、HTTP 方法和完成要求的時間。
headers 記錄 BASIC 中的所有專案,以及所有要求和響應標頭。
body 記錄 BASIC 中的所有專案,以及所有要求和回應本文。
body_and_headers 記錄 HEADERS 和 BODY 中的所有內容。

藉由設定 HTTPLogOptions

啟用單一用戶端的 HTTP 要求和回應的控制台記錄

  • 將環境變數 AZURE_LOG_LEVEL 設定為 debug
  • 在建置 時新增 對 的ImageAnalysisClient呼叫httpLogOptions
ImageAnalysisClient client = new ImageAnalysisClientBuilder()
    .endpoint(endpoint)
    .credential(new KeyCredential(key))
    .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
    .buildClient();

列舉 HttpLogDetailLevel 會定義支援的記錄層級。

根據預設,當記錄時,會修訂特定 HTTP 標頭和查詢參數值。 您可以藉由指定哪些標頭和查詢參數安全地記錄,來覆寫此預設值:

ImageAnalysisClient client = new ImageAnalysisClientBuilder()
    .endpoint(endpoint)
    .credential(new KeyCredential(key))
    .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
        .addAllowedHeaderName("safe-to-log-header-name")
        .addAllowedQueryParamName("safe-to-log-query-parameter-name"))
    .buildClient();

例如,若要取得 HTTP 要求的完整未修訂記錄檔,請套用下列專案:

    .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
        .addAllowedHeaderName("Ocp-Apim-Subscription-Key")
        .addAllowedQueryParamName("features")
        .addAllowedQueryParamName("language")
        .addAllowedQueryParamName("gender-neutral-caption")
        .addAllowedQueryParamName("smartcrops-aspect-ratios")
        .addAllowedQueryParamName("model-version"))

將更多新增至上述內容,以取得未修改的 HTTP 回應。 當您共用未修訂的記錄檔時,請確定它不包含秘密,例如您的訂用帳戶密鑰。

必要條件

本指南假設您已遵循快速入門中所述的步驟。 這表示:

  • 已建立電腦視覺資源並擁有金鑰與端點 URL。
  • 您已安裝適當的 SDK 套件,而且您有執行中的快速入門應用程式。 您可以根據這裡的程式代碼範例來修改本快速入門應用程式。

建立及驗證用戶端

若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。 本指南假設您已使用金鑰和端點來定義環境變數VISION_KEYVISION_ENDPOINT

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

從建立 ImageAnalysisClient 對象開始。 例如:

// Load the .env file if it exists
require("dotenv").config();

const endpoint = process.env['VISION_ENDPOINT'] || '<your_endpoint>';
const key = process.env['VISION_KEY'] || '<your_key>';

const credential = new AzureKeyCredential(key);
const client = createClient(endpoint, credential);

選取要分析的影像

您可以藉由提供可公開存取的影像 URL,或將影像數據讀入 SDK 的輸入緩衝區,來選取影像。 請參閱 支援影像格式的影像需求

圖像 URL

您可以使用下列範例影像 URL。

const imageUrl = 'https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png';

影像緩衝區

或者,您可以將影像當做數據數位傳入。 例如,從您想要分析的本機圖像檔讀取。

const imagePath = '../sample.jpg';
const imageData = fs.readFileSync(imagePath);

選取視覺效果功能

分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例選擇要執行的作業。 如需每項功能的描述,請參閱概觀。 本節中的範例會新增所有可用的視覺特徵,但為了實用起見,您可能不需要這麼多特徵。

const features = [
  'Caption',
  'DenseCaptions',
  'Objects',
  'People',
  'Read',
  'SmartCrops',
  'Tags'
];

使用選項呼叫分析 API

下列程式代碼會呼叫分析 API,其中包含您上述選取的功能,以及以下定義的其他選項。 若要從影像緩衝區分析,而不是URL,請將方法呼叫中的 取代 imageURLimageData

const result = await client.path('/imageanalysis:analyze').post({
  body: {
      url: imageUrl
  },
  queryParameters: {
      features: features,
      'language': 'en',
      'gender-neutral-captions': 'true',
      'smartCrops-aspect-ratios': [0.9, 1.33]
  },
  contentType: 'application/json'
});

選取智慧裁剪外觀比例

外觀比例的計算方式是將目標裁剪寬度除以高度。 支援的值從 0.75 到 1.8 (含)。 只有在選取 VisualFeatures.SmartCrops 做為視覺功能清單的一部分時,才能設定此屬性。 如果您選取 VisualFeatures.SmartCrops 但未指定外觀比例,則服務會傳回一個裁剪建議,其中包含其外觀比例。 在此案例中,外觀比例介於 0.5 到 2.0 (含) 之間。

選取性別中性標題

如果您要擷取 標題 或密集 標題(使用 VisualFeatures.CaptionVisualFeatures.DenseCaptions),您可以要求性別中性 標題。 性別中性 標題 是選擇性的,預設為性別 標題。 例如,在英文中,當您選取性別中性標題時,像是女人男人等字詞會取代為,而男孩女孩則會取代為小孩

指定語言

您可以指定傳回資料的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺特徵,請參閱語言支援

取得來自服務的結果

下列程式代碼示範如何剖析各種 分析 作業的結果。

const iaResult = result.body;

console.log(`Model Version: ${iaResult.modelVersion}`);
console.log(`Image Metadata: ${JSON.stringify(iaResult.metadata)}`);
if (iaResult.captionResult) {
  console.log(`Caption: ${iaResult.captionResult.text} (confidence: ${iaResult.captionResult.confidence})`);
}
if (iaResult.denseCaptionsResult) {
  iaResult.denseCaptionsResult.values.forEach(denseCaption => console.log(`Dense Caption: ${JSON.stringify(denseCaption)}`));
}
if (iaResult.objectsResult) {
  iaResult.objectsResult.values.forEach(object => console.log(`Object: ${JSON.stringify(object)}`));
}
if (iaResult.peopleResult) {
  iaResult.peopleResult.values.forEach(person => console.log(`Person: ${JSON.stringify(person)}`));
}
if (iaResult.readResult) {
  iaResult.readResult.blocks.forEach(block => console.log(`Text Block: ${JSON.stringify(block)}`));
}
if (iaResult.smartCropsResult) {
  iaResult.smartCropsResult.values.forEach(smartCrop => console.log(`Smart Crop: ${JSON.stringify(smartCrop)}`));
}
if (iaResult.tagsResult) {
  iaResult.tagsResult.values.forEach(tag => console.log(`Tag: ${JSON.stringify(tag)}`));
}

疑難排解

記錄

啟用記錄有助於找出失敗的相關實用資訊。 若要查看 HTTP 的要求和回應記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在 @azure/logger 中呼叫 setLogLevel,以在執行階段啟用記錄:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

如需如何啟用記錄的詳細指示,您可以查看 @azure/記錄器套件檔

必要條件

本指南假設您已成功按照快速入門頁面所描述的步驟。 這表示:

  • 已建立電腦視覺資源並擁有金鑰與端點 URL。
  • 您已成功對服務進行 curl.exe 呼叫 (或使用替代工具)。 您可以根據這裡的範例修改 curl.exe 呼叫。

針對服務進行驗證

若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

SDK 範例假設您已使用金鑰和端點定義了環境變數 VISION_KEYVISION_ENDPOINT

藉由新增 HTTP 要求標頭 Ocp-Apim-Subscription-Key 並將其設定為您的視覺金鑰來完成驗證。 系統會呼叫 URL <endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01,其中 <endpoint> 是您的唯一電腦視覺端點 URL。 您可以根據分析選項新增查詢字串。

選取要分析的影像

本指南中的程式代碼會使用 URL 所參考的遠端影像。 您可能想要自行嘗試不同的影像,以查看影像分析功能的完整功能。

分析遠端影像時,您可以藉由格式化要求本文來指定影像的 URL: {"url":"https://learn.microsoft.com/azure/cognitive-services/computer-vision/images/windows-kitchen.jpg"}Content-Type 應為 application/json

若要分析本機影像,您會將二進位影像數據放在 HTTP 要求本文中。 Content-Type 應為 application/octet-streammultipart/form-data

選取分析選項

使用標準模型時選取視覺特徵

分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例選擇要執行的作業。 如需每項功能的描述,請參閱概觀。 本節中的範例會新增所有可用的視覺特徵,但為了實用起見,您可能不需要這麼多特徵。

只有下列 Azure 區域才支援視覺特徵 'Captions' 和 'DenseCaptions':美國東部、法國中部、南韓中部、北歐、東南亞、西歐、美國西部。

注意

REST API 使用智慧裁剪智慧裁剪外觀比例等字詞。 SDK 使用裁剪建議裁剪外觀比例等字詞。 兩者都指相同的服務作業。 同樣地,REST API 會使用 Read 一詞來偵測影像中的文字使用光學字元辨識 (OCR),而 SDK 則使用文字一詞來進行相同的作業。

您可藉由設定分析 4.0 API 的 URL 查詢參數,來指定您想要使用的特徵。 參數可以有多個值,並以逗號分隔。

URL 參數 Description
features read 讀取影像中的可見文字,並將其輸出為結構化 JSON 資料。
features caption 使用支援語言的完整句子來描述影像內容。
features denseCaptions 產生最多 10 個顯著影像區域的詳細標題。
features smartCrops 尋找會將影像裁剪成所需外觀比例,同時保留感興趣區域的矩形座標。
features objects 偵測影像內的各種物品,包括大約的位置。 Objects 自變數僅適用於英文。
features tags 使用與映像內容相關之字組的詳細清單標記影像。
features people 偵測影像中出現的人員,包括大約的位置。

填入的網址可能如下所示:

<endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01&features=tags,read,caption,denseCaptions,smartCrops,objects,people

使用自訂模型時設定模型名稱

您也可以使用自訂的定型模型來執行影像分析。 若要建立和定型模型,請參閱建立自訂影像分析模型。 模型定型之後,您只需要模型的名稱。 如果您使用自訂模型,則不需要指定視覺特徵。

若要使用自訂模型,請勿使用特徵查詢參數。 而是將 model-name 參數設定為模型的名稱,如下所示。 以您的自訂模型名稱取代 MyCustomModelName

<endpoint>/computervision/imageanalysis:analyze?api-version=2023-02-01&model-name=MyCustomModelName

指定語言

您可以指定傳回資料的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺特徵,請參閱語言支援

語言選項僅適用於使用標準模型時。

下列 URL 查詢參數會指定語言。 預設值是 en

URL 參數 Description
language en 英語
language es 西班牙文
language ja 日文
language pt 葡萄牙文
language zh 簡體中文

填入的網址可能如下所示:

<endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01&features=caption&language=en

選取性別中性標題

如果您要擷取標題或密集標題,您可以要求性別中性標題。 性別中性 標題 是選擇性的,預設為性別 標題。 例如,在英文中,當您選取性別中性標題時,像是女人男人等字詞會取代為,而男孩女孩則會取代為小孩

性別中性標題選項僅適用於使用標準模型時。

新增具有 truefalse (預設) 值的選擇性查詢字串 gender-neutral-caption

填入的網址可能如下所示:

<endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01&features=caption&gender-neutral-caption=true

選取智慧裁剪外觀比例

外觀比例的計算方式是將目標裁剪寬度除以高度。 支援的值從 0.75 到 1.8 (含)。 只有在選取 VisualFeatures.SmartCrops 做為視覺功能清單的一部分時,才能設定此屬性。 如果您選取 VisualFeatures.SmartCrops 但未指定外觀比例,則服務會傳回一個裁剪建議,其中包含其外觀比例。 在此案例中,外觀比例介於 0.5 到 2.0 (含) 之間。

智慧裁剪外觀比例僅適用於使用標準模型時。

新增具有一或多個外觀比例 (以逗號分隔) 的選擇性查詢字串 smartcrops-aspect-ratios

填入的網址可能如下所示:

<endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01&features=smartCrops&smartcrops-aspect-ratios=0.8,1.2

取得來自服務的結果

使用標準模型取得結果

本節說明如何使用標準模型對服務進行分析呼叫,並取得結果。

服務會傳 200 回 HTTP 回應,主體會以 JSON 字串的形式包含傳回的數據。 下列文字是 JSON 回應的範例。

{
    "modelVersion": "string",
    "captionResult": {
      "text": "string",
      "confidence": 0.0
    },
    "denseCaptionsResult": {
      "values": [
        {
          "text": "string",
          "confidence": 0.0,
          "boundingBox": {
            "x": 0,
            "y": 0,
            "w": 0,
            "h": 0
          }
        }
      ]
    },
    "metadata": {
      "width": 0,
      "height": 0
    },
    "tagsResult": {
      "values": [
        {
          "name": "string",
          "confidence": 0.0
        }
      ]
    },
    "objectsResult": {
      "values": [
        {
          "id": "string",
          "boundingBox": {
            "x": 0,
            "y": 0,
            "w": 0,
            "h": 0
          },
          "tags": [
            {
              "name": "string",
              "confidence": 0.0
            }
          ]
        }
      ]
    },
    "readResult": {
      "blocks": [
        {
          "lines": [
            {
              "text": "string",
              "boundingPolygon": [
                {
                  "x": 0,
                  "y": 0
                },
                {
                    "x": 0,
                    "y": 0
                },
                {
                    "x": 0,
                    "y": 0
                },
                {
                    "x": 0,
                    "y": 0
                }
              ],
              "words": [
                {
                  "text": "string",
                  "boundingPolygon": [
                    {
                        "x": 0,
                        "y": 0
                    },
                    {
                        "x": 0,
                        "y": 0
                    },
                    {
                        "x": 0,
                        "y": 0
                    },
                    {
                        "x": 0,
                        "y": 0
                    }
                  ],
                  "confidence": 0.0
                }
              ]
            }
          ]
        }
      ]
    },
    "smartCropsResult": {
      "values": [
        {
          "aspectRatio": 0.0,
          "boundingBox": {
            "x": 0,
            "y": 0,
            "w": 0,
            "h": 0
          }
        }
      ]
    },
    "peopleResult": {
      "values": [
        {
          "boundingBox": {
            "x": 0,
            "y": 0,
            "w": 0,
            "h": 0
          },
          "confidence": 0.0
        }
      ]
    }
  }

錯誤碼

發生錯誤時,影像分析服務回應會包含有錯誤碼和錯誤訊息的 JSON 承載。 它也可能包含以內部錯誤碼和訊息形式出現的其他詳細資料。 例如:

{
    "error":
    {
        "code": "InvalidRequest",
        "message": "Analyze query is invalid.",
        "innererror":
        {
            "code": "NotSupportedVisualFeature",
            "message": "Specified feature type is not valid"
        }
    }
}

以下是常見的錯誤及其原因清單。 清單項目會以下列格式呈現:

  • HTTP 回應碼
    • JSON 回應中的錯誤碼和訊息
      • [選擇性] JSON 回應中的內部錯誤碼和訊息

常見錯誤清單:

  • 400 Bad Request
    • InvalidRequest - Image URL is badly formatted or not accessible. 請確定影像 URL 有效且可公開存取。
    • InvalidRequest - The image size is not allowed to be zero or larger than 20971520 bytes. 藉由壓縮和/或調整大小來減少影像的大小,然後重新提交您的要求。
    • InvalidRequest - The feature 'Caption' is not supported in this region. 只有特定 Azure 區域才支援此功能。 如需支援的 Azure 區域清單,請參閱快速入門必要條件
    • InvalidRequest - The provided image content type ... is not supported. 要求中的 HTTP 標頭 Content-Type 不是允許的類型:
      • 針對影像 URL,Content-Type 應為 application/json
      • 針對二進位影像資料,Content-Type 應為 application/octet-streammultipart/form-data
    • InvalidRequest - Either 'features' or 'model-name' needs to be specified in the query parameter.
    • InvalidRequest - Image format is not valid
      • InvalidImageFormat - Image format is not valid. 如需支援的影像格式,請參閱影像需求一節。
    • InvalidRequest - Analyze query is invalid
      • NotSupportedVisualFeature - Specified feature type is not valid. 請確定 features 查詢字串具有有效的值。
      • NotSupportedLanguage - The input language is not supported. 請根據下表,確定 language 查詢字串對選取的視覺特徵而言是有效值。
      • BadArgument - 'smartcrops-aspect-ratios' aspect ratio is not in allowed range [0.75 to 1.8]
  • 401 PermissionDenied
    • 401 - Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
  • 404 Resource Not Found
    • 404 - Resource not found. 服務根據 model-name 查詢字串提供的名稱,找不到自訂模型。

下一步