我使用 Python 3.6.5 - Flask 0.12.2 获取了此代码,公开服务并接收图像文件:
@app.route('/image', methods=['POST'])
def image():
try:
image_file = request.files['image'] # get the image
# Set an image confidence threshold value to limit returned data
threshold = request.form.get('threshold')
if threshold is None:
threshold = 0.5
else:
threshold = float(threshold)
# finally run the image through tensor flow object detection`
image_object = Image.open(image_file)
objects = od_ws_api.get_objects(image_object, threshold)
return objects
except Exception as e:
print(e)
当我使用此 CURL 命令运行程序时,一切都按预期正常工作:
curl -F "image=@xxx.jpg" http://localhost:5000/image
我的目标是使用相同的 POST 方法传递图像 URL 而不是本地文件,例如:
curl -F "image=https://i.ytimg.com/vi/aeLgjgoy_kE/maxresdefault.jpg" http://localhost:5000/image
如果我这样做,我会收到以下错误消息:
400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
127.0.0.1 - - [10/Apr/2018 08:20:52] "POST /image HTTP/1.1" 200
我应该使用其他方法或库吗? 谢谢 法规
<小时/>我确实修改为:
@app.route('/image_url', methods=['POST'])
def image_url():
try:
image_url = request.value['image_url'] # get the image URL
local_filename='c:/tensorflow/temp.jpg'
local_filename, headers = urllib.request.urlretrieve(image_url)
# Set an image confidence threshold value to limit returned data
threshold = request.form.get('threshold')
if threshold is None:
threshold = 0.5
else:
threshold = float(threshold)
# finally run the image through tensor flow object detection`
image_object = Image.open(image_file)
objects = od_ws_api.get_objects(image_object, threshold)
return objects
except Exception as e:
print(e)
return 'error'
尝试 CURL 后:
curl -F "image_url=@https://i.ytimg.com/vi/aeLgjgoy_kE/maxresdefault.jpg" http://localhost:5000/image_url
我收到以下错误:
Warning: setting file https://i.ytimg.com/vi/aeLgjgoy_kE/maxresdefault.jpg
Warning: failed!
curl: (26) read function returned funny value
最佳答案
如果您使用带文件名的curl,它不会存储在request.files
中,而是存储在request.values
中。因此,要获取图像网址,您需要调用
image_url = request.value['image']
现在您需要下载图像,例如通过使用 urlretrieve :
import urllib.request
local_filename, headers = urllib.request.urlretrieve(image_url)
图像现在存储在临时文件中,您可以通过 local_filename
访问该文件。
关于Python - Flask - 传递图像 URL 而不是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746774/