【发布时间】:2020-06-28 18:44:11
【问题描述】:
这不是我的代码,我只是编程的初学者,它是用于课程的。我无法调用 API 来分析照片,我发现这一行有错误:
response =requests.post(address, headers=headers, params=parameters, data=image_data)
就是解决不了。
# This code will show you how to call the Computer Vision API from Python
# You can find documentation on the Computer Vision Analyze Image method here
# https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa
# Use the requests library to simplify making a REST API call from Python
import requests
# We will need the json library to read the data passed back
# by the web service
import json
# You need to update the SUBSCRIPTION_KEY to
# they key for your Computer Vision Service
SUBSCRIPTION_KEY = "****************************"
# You need to update the vision_service_address to the address of
# your Computer Vision Service
vision_service_address = "https://pythonimageanalyzerr.cognitiveservices.azure.com/"
# Add the name of the function you want to call to the address
address = vision_service_address + "vision/v3.0/analyze"
# According to the documentation for the analyze image function
# There are three optional parameters: language, details & visualFeatures
parameters = {'visualFeatures':'Description,Color',
'language':'en'}
# Open the image file to get a file object containing the image to analyze
image_path = "./TestImages/PolarBear.jpg"
image_data = open(image_path, "rb").read
# According to the documentation for the analyze image function
# we need to specify the subscription key and the content type
# in the HTTP header. Content-Type is application/octet-stream when you pass in a image directly
headers = {'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY}
# According to the documentation for the analyze image function
# we use HTTP POST to call this function
response =requests.post(address, headers=headers, params=parameters, data=image_data)
# Raise an exception if the call returns an error code
response.raise_for_status()
# Display the JSON results returned
results = response.json()
print(json.dumps(results))
以下是我发现的错误:
File "e:/programming/API.py", line 42, in <module> response =requests.post(address, headers=headers, params=parameters, data=image_data) for i in request.body: TypeError: 'builtin_function_or_method' object is not iterable>
【问题讨论】:
-
问题中没有错误消息中的代码
-
我认为括号不见了。您需要一个对象而不是方法作为参数。传递函数调用的结果而不是函数本身。例如。 'image_data = open(image_path, "rb").read' 应该带有括号 'image_data = open(image_path, "rb").read()' 或 response =requests.post(address, headers=headers, params=parameters , data=image_data() )