如何调用 Azure 认知服务 API?

How to call Azure Cognitive Services API?

我使用 Azure Custom Vision(认知服务)创建并训练了一个图像分类模型,并使用 API 发布了该模型。 现在,我在 Python 中编写了一个简单的代码,它从给定的 URL 中获取图像并调用 API。但是,即使图像确实存在,我仍然收到此错误:

with open(URL, "rb") as image_contents: FileNotFoundError: [Errno 2] No such file or directory: 'https://upload.wikimedia.org/wikipedia/commons/5/55/Dalailama1_20121014_4639.jpg'

代码如下:

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient

ENDPOINT = "https://westeurope.api.cognitive.microsoft.com/"
PROJECT_ID = "bbed3f99-4199-4a17-81f2-df83f0659be3"

# Replace with a valid key
prediction_key = "<my prediction key>"
prediction_resource_id = "/subscriptions/97c4e143-9c0c-4f1e-b880-15492e327dd1/resourceGroups/WestEurope/providers/Microsoft.CognitiveServices/accounts/HappyAI"
publish_iteration_name = "Iteration5"

# Classify image
URL = "https://upload.wikimedia.org/wikipedia/commons/5/55/Dalailama1_20121014_4639.jpg"

# Now there is a trained endpoint that can be used to make a prediction
predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT)

with open(URL, "rb") as image_contents:
    results = predictor.classify_image(
        PROJECT_ID, publish_iteration_name, image_contents.read())

    # Display the results.
    for prediction in results.predictions:
        print("\t" + prediction.tag_name +
              ": {0:.2f}%".format(prediction.probability * 100))

不胜感激!

提前致谢!

有两种方法可以将图像提供给认知服务。你把两者混在一起了 ;)

1) 为可通过 Internet 访问的图像提供 URL。您可以通过向服务发送 JSON 来执行此操作: {"url":"https://sample.com/myimage.png"}

2) 在 POST 请求中上传二进制图像。

来源:https://docs.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/use-prediction-api#get-the-url-and-prediction-key

您的问题是您正尝试将 open() 用于方法 2。但是,这不适用于 Python 中的远程文件。如果您想这样做(而不是方法 1),请使用例如 urllib2.urlopen like this.