【问题标题】:Read data from an Azure blob container into the Computer Vision service将 Azure blob 容器中的数据读入计算机视觉服务
【发布时间】:2020-07-16 04:32:31
【问题描述】:

我正在使用 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 中的?下载 blob 的内容后,您必须从这些内容中检索图像,然后将图像转换为原始字节。完成此操作后,您应该可以使用您的第一个脚本将其发送到 CV。
  • @Tyson 图片为 JPG 格式,在将图片发送到 CV API 之前,我宁愿不要将图片下载到我的机器上;只需从 CV API 读取它们,这可能吗?
  • 是的,这肯定是最好的方法。听起来应该是可能的,但我不知道如何做,也找不到任何关于如何去做的文档。对不起。关于如何在将图像发送到 CV 之前将图像下载到本地,这里有一些类似的问题/答案:stackoverflow.com/questions/44588402/…stackoverflow.com/questions/55170572/…

标签: azure computer-vision storage


【解决方案1】:

两个简单的选择:

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

带有 SAS 令牌的完整 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]

【讨论】:

    【解决方案2】:

    如果您检查示例:

    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)
    

    您需要做的就是从 my_blob 获取一个字节数组

    而不是

    将图像读入字节数组

    image_data = open(image_path, "rb").read()
    

    你应该

    从字节数组中读取

    image_data = my_blob.tobytes()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 2020-05-24
      • 2021-10-26
      • 2010-12-04
      • 2018-11-07
      • 1970-01-01
      相关资源
      最近更新 更多