本文將示範如何呼叫影像分析 4.0 API,以傳回與該影像視覺輔助功能相關的資訊。 此外也會說明如何剖析傳回的資訊。
先決條件
本指南會假設您已遵循快速入門頁面所提及的步驟。 這表示:
新增 import 陳述式
請確定您的程式代碼檔案具有下列語句:
建立和驗證用戶端
若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。 本指南會假設您已使用金鑰和端點來定義環境變數 VISION_KEY 和 VISION_ENDPOINT。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱透過 Azure Key Vault 使用 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 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 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例,選擇要執行的作業。 如需各項功能的說明,請參閱概觀。 本章節的範例會新增所有可用的視覺效果功能,但實際使用時,您可能不需要那麽多。
重要事項
某些 Azure 區域僅支援視覺效果功能 Captions 和 DenseCaptions: 請參閱區域可用性
VisualFeatures visualFeatures =
VisualFeatures.Caption |
VisualFeatures.DenseCaptions |
VisualFeatures.Objects |
VisualFeatures.Read |
VisualFeatures.Tags |
VisualFeatures.People |
VisualFeatures.SmartCrops;
選取分析選項
使用 ImageAnalysisOptions 物件來指定分析影像 API 呼叫的各種選項。
- 語言: 您可以指定傳回資料的語言。 語言是選擇性的,預設值為英文。 如需支援的語言代碼清單,以及每個語言支援哪些視覺輔助功能,請參閱語言支援。
- 性別中立字幕: 如果您要擷取字幕或密集字幕 (使用 VisualFeatures.Caption 或 VisualFeatures.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 進行分析,請使用 imageData 變數取代方法呼叫中的 imageURL。
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。 本指南會假設您已使用金鑰和端點來定義環境變數 VISION_KEY 和 VISION_ENDPOINT。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱透過 Azure Key Vault 使用 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 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 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例,選擇要執行的作業。 如需各項功能的說明,請參閱概觀。 本章節的範例會新增所有可用的視覺效果功能,但實際使用時,您可能不需要那麽多。
重要事項
只有某些 Azure 區域支援視覺效果功能 Captions 和 DenseCaptions。 請參閱區域可用性 (英文)。
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.CAPTION 或 VisualFeatures.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。 本指南會假設您已使用金鑰和端點來定義環境變數 VISION_KEY 和 VISION_ENDPOINT。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱透過 Azure Key Vault 使用 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 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 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例,選擇要執行的作業。 如需各項功能的說明,請參閱概觀。 本章節的範例會新增所有可用的視覺效果功能,但實際使用時,您可能不需要那麽多。
重要事項
只有某些 Azure 區域支援視覺效果功能 Captions 和 DenseCaptions。 請參閱區域可用性 (英文)。
// 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.CAPTION 或 VisualFeatures.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 進行分析,請改為呼叫分析方法,並將 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());
}
疑難排解
例外狀況
當服務以非成功 HTTP 狀態碼回應時,analyze 方法會擲回 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。 本指南假定您已使用金鑰和端點來定義環境變數 VISION_KEY 和 VISION_ENDPOINT。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱透過 Azure Key Vault 使用 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 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 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例,選擇要執行的作業。 如需各項功能的說明,請參閱概觀。 本章節的範例會新增所有可用的視覺效果功能,但實際使用時,您可能不需要那麽多。
重要事項
只有某些 Azure 區域支援視覺效果功能 Captions 和 DenseCaptions。 請參閱 。
const features = [
'Caption',
'DenseCaptions',
'Objects',
'People',
'Read',
'SmartCrops',
'Tags'
];
使用選項呼叫分析 API
下列程式碼會使用您在上面選取的功能以及接下來定義的其他選項,來呼叫分析影像 API。 若要從影像緩衝區而不是 URL 進行分析,請使用 imageData 取代方法呼叫中的 imageURL。
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.Caption 或 VisualFeatures.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/logger 套件文件。
先決條件
本指南假設您已成功遵循 快速入門 頁面中所述的步驟。 這表示:
驗證服務
若要對影像分析服務進行驗證,您需要電腦視覺金鑰和端點 URL。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱透過 Azure Key Vault 使用 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求 (英文)。
SDK 範例假設您已使用金鑰和端點定義了環境變數 VISION_KEY 和 VISION_ENDPOINT。
藉由新增 HTTP 要求標頭 Ocp-Apim-Subscription-Key 並將其設定為您的視覺金鑰來完成驗證。 系統會呼叫 URL <endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01,其中 <endpoint> 是您的唯一電腦視覺端點 URL。 您可以根據分析選項新增查詢字串。
選取要分析的影像
本指南中的程式碼使用 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-stream 或 multipart/form-data。
選取分析選項
使用標準模型時選取視覺輔助功能
分析 4.0 API 可讓您存取服務的所有影像分析特徵。 根據您自己的使用案例,選擇要執行的作業。 如需各項功能的說明,請參閱概觀。 本章節的範例會新增所有可用的視覺效果功能,但實際使用時,您可能不需要那麽多。
某些 Azure 區域僅支援視覺效果功能「Captions」和「DenseCaptions」。
附註
REST API 使用智慧裁剪和智慧裁剪外觀比例等字詞。 SDK 使用裁剪建議和裁剪外觀比例等字詞。 兩者都指相同的服務作業。 同樣地,REST API 會使用「讀取」一詞透過光學字元辨識 (OCR) 來偵測影像中的文字,而 SDK 則是使用「文字」一詞來進行相同的作業。
您可藉由設定分析 4.0 API 的 URL 查詢參數,來指定您想要使用的特徵。 參數可以有多個值,並以逗號分隔。
| URL 參數 | 值 | 說明 |
|---|---|---|
features |
read |
讀取影像中的可見文字,並將其輸出為結構化 JSON 資料。 |
features |
caption |
使用支援語言的完整句子來描述影像內容。 |
features |
denseCaptions |
產生最多 10 個顯著影像區域的詳細標題。 |
features |
smartCrops |
尋找會將影像裁剪成所需外觀比例,同時保留感興趣區域的矩形座標。 |
features |
objects |
偵測影像內的各種物品,包括大約的位置。 物品引數僅於英文版中提供。 |
features |
tags |
使用與影像內容相關之字組的詳細清單標記影像。 |
features |
people |
偵測影像中出現的人員,包括大約的位置。 |
填入的 URL 可能會如下所示:
<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 參數 | 值 | 說明 |
|---|---|---|
language |
en |
英文 |
language |
es |
西班牙文 |
language |
ja |
日文 |
language |
pt |
葡萄牙文 |
language |
zh |
簡體中文 |
填入的 URL 可能會如下所示:
<endpoint>/computervision/imageanalysis:analyze?api-version=2024-02-01&features=caption&language=en
選取性別中性標題
如果您要擷取標題或密集標題,您可以要求性別中性標題。 性別中立輔助字幕為選用,預設為非性別中立輔助字幕。 例如,在英文中,當您選取性別中性標題時,像是女人或男人等字詞會取代為人,而男孩或女孩則會取代為小孩。
性別中性標題選項僅適用於使用標準模型時。
新增具有 true 或 false (預設) 值的選擇性查詢字串 gender-neutral-caption。
填入的 URL 可能會如下所示:
<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。
填入的 URL 可能會如下所示:
<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 回應中的內部錯誤碼和訊息
- JSON 回應中的錯誤碼和訊息
常見錯誤清單:
400 Bad RequestInvalidRequest - 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-stream或multipart/form-data
- 針對影像 URL,Content-Type 應為
InvalidRequest - Either 'features' or 'model-name' needs to be specified in the query parameter.InvalidRequest - Image format is not validInvalidImageFormat - Image format is not valid. 如需支援的影像格式,請參閱影像需求一節。
InvalidRequest - Analyze query is invalidNotSupportedVisualFeature - 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 PermissionDenied401 - 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 Found404 - Resource not found. 服務根據model-name查詢字串提供的名稱,找不到自訂模型。
相關內容
- 探索概念文章,以深入瞭解每項功能。
- 探索 GitHub 上的 SDK 程式碼範例:
- 請參閱 REST API 參照,以深入了解 API 功能。