azure-ai-vision-imageanalysis-py
microsoft/skills
Analise imagens usando o Azure AI Vision SDK: gere legendas e tags, detecte objetos, extraia texto (OCR), identifique pessoas e sugira recortes inteligentes.
...Expandir tudoSDK de análise de imagens do Azure AI Vision para Python
Biblioteca cliente para análise de imagens do Azure AI Vision 4.0, incluindo legendas, tags, objetos, OCR e muito mais.
Instalação
pip install azure-ai-vision-imageanalysis
Variáveis de ambiente
VISION_ENDPOINT=https://.cognitiveservices.azure.com # Obrigatório para todos os métodos de autenticação
AZURE_TOKEN_CREDENTIALS=prod # Necessário apenas se DefaultAzureCredential for usado em produção
VISION_KEY= # Necessário apenas para o caminho de autenticação com chave de API legada abaixo
Autenticação e ciclo de vida
🔑 Duas regras se aplicam a todos os exemplos de código abaixo:
- Dê preferência
ao DefaultAzureCredential. Ele funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração no código. Evite cadeias de conexão, contas e chaves de API — elas contornam a auditoria e a rotação do Entra.
- Desenvolvimento local:
o DefaultAzureCredentialfunciona como está.- Produção: defina
AZURE_TOKEN_CREDENTIALS=prod(ouAZURE_TOKEN_CREDENTIALS=) para restringir a cadeia de credenciais a credenciais seguras para produção.- Envolva cada cliente em um gerenciador de contexto para que transportes HTTP, soquetes e caches de tokens sejam liberados de forma determinística:
- Sincrônica:
com(...) como cliente: - Assíncrono:
async come(...) como cliente: async com DefaultAzureCredential() como credencial:(deazure.identity.aio)Os trechos de código podem abreviar essa configuração, mas o código de produção deve sempre seguir ambas as regras.
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
# Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Ou use uma credencial específica diretamente em produção:
# Consulte https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
com ImageAnalysisClient(
endpoint=os.environ["VISION_ENDPOINT"],
credential=credential,
) como client:
result = client.analyze_from_url(
image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",
visual_features=[VisualFeatures.CAPTION],
)
Legado: Chave de API (implantações existentes com chave)
O novo código deve usar o `DefaultAzureCredential` acima. Use `AzureKeyCredential` apenas se você tiver uma implantação com chave existente que ainda não tenha sido migrada para o Entra ID — por exemplo, ambientes regulamentados que ainda estejam concluindo sua implantação do 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],
)
Analisar imagem a partir de 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"
)
Analisar imagem a partir de arquivo
com open("image.jpg", "rb") como f:
image_data = f.read()
result = client.analyze(
image_data=image_data,
visual_features=[VisualFeatures.CAPTION, VisualFeatures.TAGS]
)
Legenda da imagem
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.CAPTION],
gender_neutral_caption=True
)
se result.caption:
print(f"Legenda: {result.caption.text}")
print(f"Confiança: {result.caption.confidence:.2f}")
Legendas densas (várias regiões)
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"Legenda: {caption.text}")
print(f" Confiança: {caption.confidence:.2f}")
print(f" Caixa delimitadora: {caption.bounding_box}")
Tags
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} (confiança: {tag.confidence:.2f})")
Detecção de objetos
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.OBJECTS]
)
se result.objects:
para obj em result.objects.list:
print(f"Objeto: {obj.tags[0].name}")
print(f" Confiança: {obj.tags[0].confidence:.2f}")
box = obj.bounding_box
print(f" Caixa delimitadora: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
OCR (Extração de texto)
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"Linha: {line.text}")
print(f" Polígono delimitador: {line.bounding_polygon}")
# Detalhes no nível da palavra
para palavra em linha.palavras:
print(f" Palavra: {palavra.text} (confiança: {palavra.confidence:.2f})")
Detecção de pessoas
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.PEOPLE]
)
if result.people:
for person in result.people.list:
print(f"Pessoa detectada:")
print(f" Confiança: {person.confidence:.2f}")
box = person.bounding_box
print(f" Caixa delimitadora: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
Recorte Inteligente
result = client.analyze_from_url(
image_url=image_url,
visual_features=[VisualFeatures.SMART_CROPS],
smart_crops_aspect_ratios=[0.9, 1.33, 1.78] # Retrato, 4:3, 16:9
)
if result.smart_crops:
for crop in result.smart_crops.list:
print(f"Proporção: {crop.aspect_ratio}")
box = crop.bounding_box
print(f" Região de recorte: x={box.x}, y={box.y}, w={box.width}, h={box.height}")
Cliente assíncrono
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)
Recursos visuais
| Característica | Descrição |
|---|---|
CAPTION |
Uma única frase que descreve a imagem |
DENSE_CAPTIONS |
Legendas para várias regiões |
TAGS |
Tags de conteúdo (objetos, cenas, ações) |
OBJETOS |
Detecção de objetos com caixas delimitadoras |
LEITURA |
Extração de texto por OCR |
PESSOAS |
Detecção de pessoas com caixas delimitadoras |
RECORTES_INTELIGENTES |
Regiões de recorte sugeridas para miniaturas |
Tratamento de erros
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"Código de status: {e.status_code}")
print(f"Motivo: {e.reason}")
print(f"Mensagem: {e.error.message}")
Requisitos de imagem
- Formatos: JPEG, PNG, GIF, BMP, WEBP, ICO, TIFF, MPO
- Tamanho máximo: 20 MB
- Dimensões: 50x50 a 16.000x16.000 pixels
Práticas recomendadas
- Escolha entre síncrono OU assíncrono e mantenha a consistência. Não misture clientes síncronos
do azure.ai.vision.imageanalysiscom clientes assíncronosdo azure.ai.vision.imageanalysis.aiono mesmo caminho de chamada. Escolha um modo por módulo. - Sempre use gerenciadores de contexto para clientes e credenciais assíncronas. Envolva cada cliente
com ImageAnalysisClient(...) como cliente:(sinc.) ouassíncrono com ImageAnalysisClient(...) como cliente:(assíncrono). Para as credenciais assíncronasDefaultAzureCredentialdoazure.identity.aio, use tambéma sintaxe assíncrona com “credential:”,para que os tokens e transportes sejam limpos. - Selecione apenas os recursos necessários para otimizar a latência e o custo
- Use o cliente assíncrono para cenários de alto rendimento
- Trate o HttpResponseError para imagens inválidas ou problemas de autenticação
- Habilite gender_neutral_caption para descrições inclusivas
- Especifique o idioma para legendas localizadas
- Use smart_crops_aspect_ratios de acordo com seus requisitos de miniaturas
- Armazene os resultados em cache ao analisar a mesma imagem várias vezes
---
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
Todos os arquivos
0 arquivosInstalar azure-ai-vision-imageanalysis-py
Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.
Baixar ZIPClone o repositório e copie os arquivos da habilidade para o seu projeto.
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
Copiar





Lar
