你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Python 的 Azure 认知服务计算机视觉 SDK

使用计算机视觉服务,开发人员可以访问用于处理图像并返回信息的高级算法。 计算机视觉算法根据你感兴趣的视觉特征,通过不同的方式分析图像的内容。

在应用程序中使用计算机视觉可以:

  • 通过分析图像来获取见解
  • 从图像中提取文本
  • 生成缩略图

想要更多文档?

先决条件

如果需要计算机视觉 API 帐户,可使用以下 Azure CLI 命令创建一个:

RES_REGION=westeurope
RES_GROUP=<resourcegroup-name>
ACCT_NAME=<computervision-account-name>

az cognitiveservices account create \
    --resource-group $RES_GROUP \
    --name $ACCT_NAME \
    --location $RES_REGION \
    --kind ComputerVision \
    --sku S1 \
    --yes

安装

(可选)在虚拟环境中安装包含 pip 的 Azure 认知服务计算机视觉 SDK。

配置虚拟环境(可选)

尽管并不要求使用虚拟环境,但使用这种环境可让基础系统与 Azure SDK 环境相互保持隔离。 执行以下命令进行配置,然后结合 venv 输入虚拟环境,例如 cogsrv-vision-env

python3 -m venv cogsrv-vision-env
source cogsrv-vision-env/bin/activate

安装 SDK

安装包含 pip 的适用于 Python 的 Azure 认知服务计算机视觉 SDK

pip install azure-cognitiveservices-vision-computervision

身份验证

创建计算机视觉资源后,需要使用该资源的区域及其帐户密钥之一来实例化客户端对象。

创建 ComputerVisionClient 客户端对象的实例时需要使用这些值。

获取凭据

使用以下 Azure CLI 代码片段在两个环境变量中填充计算机视觉帐户的区域及其密钥之一(也可以在 Azure 门户中找到这些值)。 此代码片段已针对 Bash shell 格式化。

RES_GROUP=<resourcegroup-name>
ACCT_NAME=<computervision-account-name>

export ACCOUNT_REGION=$(az cognitiveservices account show \
    --resource-group $RES_GROUP \
    --name $ACCT_NAME \
    --query location \
    --output tsv)

export ACCOUNT_KEY=$(az cognitiveservices account keys list \
    --resource-group $RES_GROUP \
    --name $ACCT_NAME \
    --query key1 \
    --output tsv)

创建客户端

填充 ACCOUNT_REGIONACCOUNT_KEY 环境变量后,可以创建 ComputerVisionClient 客户端对象。

from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

import os
region = os.environ['ACCOUNT_REGION']
key = os.environ['ACCOUNT_KEY']

credentials = CognitiveServicesCredentials(key)
client = ComputerVisionClient(
    endpoint="https://" + region + ".api.cognitive.microsoft.com/",
    credentials=credentials
)

使用情况

初始化 ComputerVisionClient 客户端对象后,可以:

  • 分析图像:可以分析图像的某些特征,例如人脸、颜色、标记。
  • 生成缩略图:创建自定义 JPEG 图像,用作原始图像的缩略图。
  • 获取图像的说明:根据图像的主题域获取图像的说明。

有关此服务的详细信息,请参阅什么是计算机视觉?

示例

以下部分提供了多个代码片段,其中涵盖了一些最常见的计算机视觉任务,包括:

分析图像

可以使用 analyze_image 分析图像中的某些特征。 使用 visual_features 属性设置针对图像执行的分析类型。 常用值为 VisualFeatureTypes.tagsVisualFeatureTypes.description

url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg"

image_analysis = client.analyze_image(url,visual_features=[VisualFeatureTypes.tags])

for tag in image_analysis.tags:
    print(tag)

获取主题域列表

使用 list_models 查看用于分析图像的主题域。 按域分析图像时将使用这些域名。 域的示例是 landmarks

models = client.list_models()

for x in models.models_property:
    print(x)

按域分析图像

可以使用 analyze_image_by_domain 按主题域分析图像。 获取支持的主题域列表,以使用正确的域名。

domain = "landmarks"
url = "https://images.pexels.com/photos/338515/pexels-photo-338515.jpeg"
language = "en"

analysis = client.analyze_image_by_domain(domain, url, language)

for landmark in analysis.result["landmarks"]:
    print(landmark["name"])
    print(landmark["confidence"])

获取图像的文本说明

可以使用 describe_image 获取图像的基于语言的文本说明。 如果你要针对与图像关联的关键字执行文本分析,请使用 max_description 属性请求多个说明。 以下图像的文本说明示例包括 a train crossing a bridge over a body of watera large bridge over a body of watera train crossing a bridge over a large body of water

domain = "landmarks"
url = "http://www.public-domain-photos.com/free-stock-photos-4/travel/san-francisco/golden-gate-bridge-in-san-francisco.jpg"
language = "en"
max_descriptions = 3

analysis = client.describe_image(url, max_descriptions, language)

for caption in analysis.captions:
    print(caption.text)
    print(caption.confidence)

获取图像中的文本

可以从图像中获取任何手写或打印的文本。 这需要对 SDK 进行两次调用:readget_read_result。 对读取的调用是异步的。 在get_read_result调用的结果中,需要在提取文本数据之前检查第一次调用是否已完成 OperationStatusCodes 。 结果包括文本以及该文本的边框坐标。

# import models
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes

url = "https://github.com/Azure-Samples/cognitive-services-python-sdk-samples/raw/master/samples/vision/images/make_things_happen.jpg"
raw = True
numberOfCharsInOperationId = 36

# SDK call
rawHttpResponse = client.read(url, language="en", raw=True)

# Get ID from returned headers
operationLocation = rawHttpResponse.headers["Operation-Location"]
idLocation = len(operationLocation) - numberOfCharsInOperationId
operationId = operationLocation[idLocation:]

# SDK call
result = client.get_read_result(operationId)

# Get data
if result.status == OperationStatusCodes.succeeded:

    for line in result.analyze_result.read_results[0].lines:
        print(line.text)
        print(line.bounding_box)

生成缩略图

可以使用 generate_thumbnail 生成图像的缩略图 (JPG)。 缩略图的比例不需要与原始图像相同。

此示例使用 Pillow 包在本地保存新的缩略图。

from PIL import Image
import io

width = 50
height = 50
url = "http://www.public-domain-photos.com/free-stock-photos-4/travel/san-francisco/golden-gate-bridge-in-san-francisco.jpg"

thumbnail = client.generate_thumbnail(width, height, url)

for x in thumbnail:
    image = Image.open(io.BytesIO(x))

image.save('thumbnail.jpg')

疑难解答

常规

使用 Python SDK 与 ComputerVisionClient 客户端对象交互时,将使用ComputerVisionErrorException类返回错误。 服务返回的错误对应于返回给 REST API 请求的相同 HTTP 状态代码。

例如,如果你尝试使用无效的密钥分析图像,则会返回 401 错误。 以下代码片段通过捕获异常并显示有关错误的其他信息来妥善处理该错误


domain = "landmarks"
url = "http://www.public-domain-photos.com/free-stock-photos-4/travel/san-francisco/golden-gate-bridge-in-san-francisco.jpg"
language = "en"
max_descriptions = 3

try:
    analysis = client.describe_image(url, max_descriptions, language)

    for caption in analysis.captions:
        print(caption.text)
        print(caption.confidence)
except HTTPFailure as e:
    if e.status_code == 401:
        print("Error unauthorized. Make sure your key and region are correct.")
    else:
        raise

使用重试处理暂时性错误

使用 ComputerVisionClient 客户端时,可能会遇到服务强制实施的速率限制所导致的暂时性错误,或者网络中断等其他暂时性问题。 有关如何处理此类故障的信息,请参阅云设计模式指南中的重试模式,以及相关的断路器模式

后续步骤

更多示例代码

SDK 的 GitHub 存储库中提供了多个计算机视觉 Python SDK 示例。 这些示例提供了在使用计算机视觉时经常遇到的其他场景的示例代码:

其他文档

有关计算机视觉服务的更详细文档,请参阅 docs.microsoft.com 上的 Azure 计算机视觉文档