azure-ai-vision-imageanalysis-py
microsoft/skills
Azure AI Vision SDK を使用して画像を分析します。キャプションやタグの生成、オブジェクトの検出、テキストの抽出(OCR)、人物の検出、スマートトリミングの提案などが可能です。
...すべて拡張しますPython用 Azure AI Vision 画像分析 SDK
キャプション、タグ、オブジェクト、OCRなどを含む、Azure AI Vision 4.0 画像分析用のクライアント ライブラリ。
インストール
pip install azure-ai-vision-imageanalysis
環境変数
VISION_ENDPOINT=https://.cognitiveservices.azure.com # すべての認証方法で必須
AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合にのみ必要
VISION_KEY= # 以下のレガシー API キー認証パスでのみ必要
認証とライフサイクル
🔑 以下のすべてのコードサンプルには、次の2つのルールが適用されます:
DefaultAzureCredential を優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)および Azure(マネージド ID、ワークロード ID)で動作します。接続文字列やアカウント/API キーの使用は避けてください。これらは Entra の監査およびローテーションの対象外となります。
- ローカル開発:
DefaultAzureCredentialはそのまま使用できます。- 本番環境:
AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS=)を設定し、資格情報チェーンを本番環境に適した資格情報に制限してください。- すべてのクライアントをコンテキストマネージャーでラップし、HTTPトランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
- 同期:
(...) as client: - 非同期:
`async with` および(...) as client: `async with DefaultAzureCredential() as credential:` (azure.identity.aioより)スニペットではこの設定を省略している場合がありますが、本番環境のコードでは常に両方のルールに従う必要があります。
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
# ローカル開発環境: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=を設定
credential = DefaultAzureCredential(require_envvar=True)
# または、本番環境では特定の認証情報を直接使用します:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes を参照してください
# credential = ManagedIdentityCredential()
with ImageAnalysisClient(
endpoint=os.environ["VISION_ENDPOINT"],
credential=credential,
) as client:
result = client.analyze_from_url(
image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",
visual_features=[VisualFeatures.CAPTION],
)
レガシー: API キー (既存のキーベースのデプロイメント)
新しいコードでは、上記のDefaultAzureCredentialを使用してください。AzureKeyCredentialを使用するのは、Entra ID へまだ移行されていない既存のキーベースのデプロイメントがある場合のみです。たとえば、Entra の導入がまだ完了していない規制対象環境などが該当します。
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
with ImageAnalysisClient(
endpoint=os.environ["VISION_ENDPOINT"],
credential=AzureKeyCredential(os.environ["VISION_KEY"]),
) as client:
result = client.analyze_from_url(
image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",
visual_features=[VisualFeatures.CAPTION],
)
URL からの画像分析
from azure.ai.vision.imageanalysis.models import VisualFeatures
image_url = "https://example.com/image.jpg"
result = client.analyze_from_url(
image_url=image_url,
visual_features=[
VisualFeatures.CAPTION,
VisualFeatures.TAGS,
VisualFeatures.OBJECTS,
VisualFeatures.READ,
VisualFeatures.PEOPLE,
VisualFeatures.SMART_CROPS,
VisualFeatures.DENSE_CAPTIONS
],
gender_neutral_caption=True,
language="en"
)
ファイルから画像を分析する
with open("image.jpg", "rb") as f:
image_data = f.read()
result = client.analyze(
image_data=image_data,
visual_features=[VisualFeatures.CAPTION, VisualFeatures.TAGS]
)
画像キャプション
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION],
gender_neutral_caption=True
)
if result.caption:
print(f"キャプション: {result.caption.text}")
print(f"信頼度: {result.caption.confidence:.2f}")
高密度キャプション(複数領域)
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.DENSE_CAPTIONS]
)
if result.dense_captions:
for caption in result.dense_captions.list:
print(f"キャプション: {caption.text}")
print(f" 信頼度: {caption.confidence:.2f}")
print(f" バウンディングボックス: {caption.bounding_box}")
タグ
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.TAGS]
)
if result.tags:
for tag in result.tags.list:
print(f"タグ: {tag.name} (信頼度: {tag.confidence:.2f})")
物体検出
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.OBJECTS]
)
if result.objects:
for obj in result.objects.list:
print(f"オブジェクト: {obj.tags[0].name}")
print(f" 信頼度: {obj.tags[0].confidence:.2f}")
box = obj.bounding_box
print(f" バウンディングボックス: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
OCR(テキスト抽出)
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.READ]
)
if result.read:
for block in result.read.blocks:
for line in block.lines:
print(f"行: {line.text}")
print(f" バウンディングポリゴン: {line.bounding_polygon}")
# 単語レベルの詳細
for word in line.words:
print(f" 単語: {word.text} (信頼度: {word.confidence:.2f})")
人物検出
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.PEOPLE]
)
if result.people:
for person in result.people.list:
print(f"人物を検出しました:")
print(f" 信頼度: {person.confidence:.2f}")
box = person.bounding_box
print(f" バウンディングボックス: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
スマートクロップ
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.SMART_CROPS],
smart_crops_aspect_ratios=[0.9, 1.33, 1.78] # 縦長、4:3、16:9
)
if result.smart_crops:
for crop in result.smart_crops.list:
print(f"アスペクト比: {crop.aspect_ratio}")
box = crop.bounding_box
print(f" トリミング領域: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
非同期クライアント
from azure.ai.vision.imageanalysis.aio import ImageAnalysisClient
from azure.identity.aio import DefaultAzureCredential
async def analyze_image():
async with DefaultAzureCredential() as credential:
async with ImageAnalysisClient(
endpoint=endpoint,
credential=credential
) as client:
result = await client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION]
)
print(result.caption.text)
視覚的特徴
| 特徴 | 説明 |
|---|---|
CAPTION |
画像を説明する一文 |
DENSE_CAPTIONS |
複数の領域に対するキャプション |
TAGS |
コンテンツタグ(オブジェクト、シーン、アクション) |
OBJECTS |
バウンディングボックスを用いたオブジェクト検出 |
読み取り |
OCRによるテキスト抽出 |
人物 |
バウンディングボックスによる人物検出 |
SMART_CROPS |
サムネイル用の推奨トリミング領域 |
エラー処理
from azure.core.exceptions import HttpResponseError
try:
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION]
)
except HttpResponseError as e:
print(f"ステータスコード: {e.status_code}")
print(f"原因: {e.reason}")
print(f"メッセージ: {e.error.message}")
画像の要件
- 形式:JPEG、PNG、GIF、BMP、WEBP、ICO、TIFF、MPO
- 最大サイズ:20 MB
- サイズ:50×50~16000×16000ピクセル
ベストプラクティス
- 同期(sync)または非同期(async)のいずれかを選択し、一貫性を保ってください。同じ呼び出しパス内で、
azure.ai.vision.imageanalysisの同期クライアントとazure.ai.vision.imageanalysis.aioの非同期クライアントを混在させないでください。モジュールごとに 1 つのモードを選択してください。 - クライアントおよび非同期の認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを、(同期)
の場合は `ImageAnalysisClient(...) as client:`、(非同期) の場合は `ImageAnalysisClient(...) as client:(async)` でラップしてください。 非同期の場合、azure.identity.aioのDefaultAzureCredentialを使用する際は、credential: とともに非同期モードも使用し、トークンとトランスポートが適切にクリーンアップされるようにしてください。 - レイテンシとコストを最適化するために、必要な機能のみを選択してください
- 高スループットなシナリオでは、非同期クライアントを使用してください
- 無効な画像や認証の問題については、HttpResponseError を処理してください
- 包括的な説明文を作成するためにgender_neutral_caption を有効にしてください
- ローカライズされたキャプションには言語を指定してください
- サムネイルの要件に合ったsmart_crops_aspect_ratios を使用する
- 同じ画像を複数回分析する場合は、結果をキャッシュする
---
name: azure-ai-vision-imageanalysis-py
description: Analyze images using Azure AI Vision SDK: generate captions, tags, detect objects, extract text (OCR), detect people, and suggest smart crops.
license: MIT
---
# Azure AI Vision Image Analysis SDK for Python
Client library for Azure AI Vision 4.0 image analysis including captions, tags, objects, OCR, and more.
## Installation
```bash
pip install azure-ai-vision-imageanalysis
```
## Environment Variables
```bash
VISION_ENDPOINT=https://<resource>.cognitiveservices.azure.com # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
VISION_KEY=<your-api-key> # Only required for the legacy API-key auth path below
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with ImageAnalysisClient(
endpoint=os.environ["VISION_ENDPOINT"],
credential=credential,
) as client:
result = client.analyze_from_url(
image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",
visual_features=[VisualFeatures.CAPTION],
)
```
### Legacy: API Key (existing keyed deployments)
New code should use `DefaultAzureCredential` above. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
with ImageAnalysisClient(
endpoint=os.environ["VISION_ENDPOINT"],
credential=AzureKeyCredential(os.environ["VISION_KEY"]),
) as client:
result = client.analyze_from_url(
image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",
visual_features=[VisualFeatures.CAPTION],
)
```
## Analyze Image from URL
```python
from azure.ai.vision.imageanalysis.models import VisualFeatures
image_url = "https://example.com/image.jpg"
result = client.analyze_from_url(
image_url=image_url,
visual_features=[
VisualFeatures.CAPTION,
VisualFeatures.TAGS,
VisualFeatures.OBJECTS,
VisualFeatures.READ,
VisualFeatures.PEOPLE,
VisualFeatures.SMART_CROPS,
VisualFeatures.DENSE_CAPTIONS
],
gender_neutral_caption=True,
language="en"
)
```
## Analyze Image from File
```python
with open("image.jpg", "rb") as f:
image_data = f.read()
result = client.analyze(
image_data=image_data,
visual_features=[VisualFeatures.CAPTION, VisualFeatures.TAGS]
)
```
## Image Caption
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION],
gender_neutral_caption=True
)
if result.caption:
print(f"Caption: {result.caption.text}")
print(f"Confidence: {result.caption.confidence:.2f}")
```
## Dense Captions (Multiple Regions)
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.DENSE_CAPTIONS]
)
if result.dense_captions:
for caption in result.dense_captions.list:
print(f"Caption: {caption.text}")
print(f" Confidence: {caption.confidence:.2f}")
print(f" Bounding box: {caption.bounding_box}")
```
## Tags
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.TAGS]
)
if result.tags:
for tag in result.tags.list:
print(f"Tag: {tag.name} (confidence: {tag.confidence:.2f})")
```
## Object Detection
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.OBJECTS]
)
if result.objects:
for obj in result.objects.list:
print(f"Object: {obj.tags[0].name}")
print(f" Confidence: {obj.tags[0].confidence:.2f}")
box = obj.bounding_box
print(f" Bounding box: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
```
## OCR (Text Extraction)
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.READ]
)
if result.read:
for block in result.read.blocks:
for line in block.lines:
print(f"Line: {line.text}")
print(f" Bounding polygon: {line.bounding_polygon}")
# Word-level details
for word in line.words:
print(f" Word: {word.text} (confidence: {word.confidence:.2f})")
```
## People Detection
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.PEOPLE]
)
if result.people:
for person in result.people.list:
print(f"Person detected:")
print(f" Confidence: {person.confidence:.2f}")
box = person.bounding_box
print(f" Bounding box: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
```
## Smart Cropping
```python
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.SMART_CROPS],
smart_crops_aspect_ratios=[0.9, 1.33, 1.78] # Portrait, 4:3, 16:9
)
if result.smart_crops:
for crop in result.smart_crops.list:
print(f"Aspect ratio: {crop.aspect_ratio}")
box = crop.bounding_box
print(f" Crop region: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
```
## Async Client
```python
from azure.ai.vision.imageanalysis.aio import ImageAnalysisClient
from azure.identity.aio import DefaultAzureCredential
async def analyze_image():
async with DefaultAzureCredential() as credential:
async with ImageAnalysisClient(
endpoint=endpoint,
credential=credential
) as client:
result = await client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION]
)
print(result.caption.text)
```
## Visual Features
| Feature | Description |
|---------|-------------|
| `CAPTION` | Single sentence describing the image |
| `DENSE_CAPTIONS` | Captions for multiple regions |
| `TAGS` | Content tags (objects, scenes, actions) |
| `OBJECTS` | Object detection with bounding boxes |
| `READ` | OCR text extraction |
| `PEOPLE` | People detection with bounding boxes |
| `SMART_CROPS` | Suggested crop regions for thumbnails |
## Error Handling
```python
from azure.core.exceptions import HttpResponseError
try:
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION]
)
except HttpResponseError as e:
print(f"Status code: {e.status_code}")
print(f"Reason: {e.reason}")
print(f"Message: {e.error.message}")
```
## Image Requirements
- Formats: JPEG, PNG, GIF, BMP, WEBP, ICO, TIFF, MPO
- Max size: 20 MB
- Dimensions: 50x50 to 16000x16000 pixels
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.ai.vision.imageanalysis` sync clients with `azure.ai.vision.imageanalysis.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with ImageAnalysisClient(...) as client:` (sync) or `async with ImageAnalysisClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Select only needed features** to optimize latency and cost
4. **Use async client** for high-throughput scenarios
5. **Handle HttpResponseError** for invalid images or auth issues
6. **Enable gender_neutral_caption** for inclusive descriptions
7. **Specify language** for localized captions
8. **Use smart_crops_aspect_ratios** matching your thumbnail requirements
9. **Cache results** when analyzing the same image multiple times
すべてのファイル
0件のファイルazure-ai-vision-imageanalysis-pyをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-vision-imageanalysis-py # Copy SKILL.md to your .claude/skills/ directory
コピー





家
