azure - 将数据从 Azure Blob 容器读取到计算机视觉服务中

标签 azure computer-vision storage

我正在使用 Azure CV 模块来处理图像,到目前为止我只使用了本地镜像或网络上免费提供的图像。但现在我需要使用存储在存储帐户容器中的图像。

我在文档中没有看到如何执行此操作,例如:此代码允许使用本地镜像:

import os
import sys
import requests
# If you are using a Jupyter notebook, uncomment the following line.
# %matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO

# Add your Computer Vision subscription key and endpoint to your environment variables.
if 'COMPUTER_VISION_SUBSCRIPTION_KEY' in os.environ:
    subscription_key = os.environ['COMPUTER_VISION_SUBSCRIPTION_KEY']
else:
    print("\nSet the COMPUTER_VISION_SUBSCRIPTION_KEY environment variable.\n**Restart your shell or IDE for changes to take effect.**")
    sys.exit()

if 'COMPUTER_VISION_ENDPOINT' in os.environ:
    endpoint = os.environ['COMPUTER_VISION_ENDPOINT']

analyze_url = endpoint + "vision/v3.0/analyze"

# Set image_path to the local path of an image that you want to analyze.
# Sample images are here, if needed:
# https://github.com/Azure-Samples/cognitive-services-sample-data-files/tree/master/ComputerVision/Images
image_path = "C:/Documents/ImageToAnalyze.jpg"

# Read the image into a byte array
image_data = open(image_path, "rb").read()
headers = {'Ocp-Apim-Subscription-Key': subscription_key,
           'Content-Type': 'application/octet-stream'}
params = {'visualFeatures': 'Categories,Description,Color'}
response = requests.post(
    analyze_url, headers=headers, params=params, data=image_data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The most
# relevant caption for the image is obtained from the 'description' property.
analysis = response.json()
print(analysis)
image_caption = analysis["description"]["captions"][0]["text"].capitalize()

# Display the image and overlay it with the caption.
image = Image.open(BytesIO(image_data))
plt.imshow(image)
plt.axis("off")
_ = plt.title(image_caption, size="x-large", y=-0.1)
plt.show()

这另一个使用来自网络的图像:

computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

remote_image_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg"


'''
Describe an Image - remote
This example describes the contents of an image with the confidence score.
'''
print("===== Describe an image - remote =====")
# Call API
description_results = computervision_client.describe_image(remote_image_url )

# Get the captions (descriptions) from the response, with confidence level
print("Description of remote image: ")
if (len(description_results.captions) == 0):
    print("No description detected.")
else:
    for caption in description_results.captions:
        print("'{}' with confidence {:.2f}%".format(caption.text, caption.confidence * 100))

另一个从存储容器读取数据:

from azure.storage.blob import BlobClient

blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="my_container", blob_name="my_blob")

with open("./BlockDestination.txt", "wb") as my_blob:
    blob_data = blob.download_blob()
    blob_data.readinto(my_blob)

但我不知道如何在存储容器和 CV 服务之间建立连接

最佳答案

两个简单的选项:

  • 不推荐:将 Blob 容器设置为“public ”,并像使用任何其他公共(public) URL 一样使用完整的 Blob URL。
  • 推荐:Construct SAS tokens对于 blob 存储中的文件。将它们附加到完整的 blob URL 以创建“临时私有(private)下载链接”,该链接可用于下载文件,就好像该文件是公共(public)文件一样。如果您在简历服务之外遇到任何问题,也可以在其中建立链接。

带有 SAS token 的完整 Blob URL 应如下所示:

https://storagesamples.blob.core.windows.net/sample-container/blob1.txt?se=2019-08-03&sp=rw&sv=2018-11-09&sr=b&skoid=<skoid>&sktid=<sktid>&skt=2019-08-02T2
2%3A32%3A01Z&ske=2019-08-03T00%3A00%3A00Z&sks=b&skv=2018-11-09&sig=<signature>

https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/storage/azure-storage-blob/samples/blob_samples_authentication.py#L110

        # Instantiate a BlobServiceClient using a connection string
        from azure.storage.blob import BlobServiceClient
        blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

        # [START create_sas_token]
        # Create a SAS token to use to authenticate a new client
        from datetime import datetime, timedelta
        from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas

        sas_token = generate_account_sas(
            blob_service_client.account_name,
            account_key=blob_service_client.credential.account_key,
            resource_types=ResourceTypes(object=True),
            permission=AccountSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1)
        )
        # [END create_sas_token]

关于azure - 将数据从 Azure Blob 容器读取到计算机视觉服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62927500/

相关文章:

opencv - 对于汽车检测,阴性 sample 的大小应与阳性 sample 的大小相同吗?

matlab - 如何在 MATLAB 中绘制 gmdistribution 的结果?

machine-learning - SVM - 我可以标准化 W 向量吗?

database - 数据库系统是否包含/存储图片、声音和文件,或者只是它们的引用?

html - 使用 HTML5 数据库 API

Azure 函数和文档数据库

.net - 调试Azure部署(无法浏览)

linux - 如何创建从 Azure Linux M 到 Azure 文件存储的符号链接(symbolic link)

azure - TLS v1.1 与 TLS v1.2 中的 session 恢复有何区别?

Azure ACS 并在其上与本地存储用户信息?