[英]Image Classification Using Google Cloud Vision API
I have a Flask app in which a user uploads a file and then I make a request to google cloud vision API to classify it.我有一个 Flask 应用程序,用户在其中上传文件,然后我向 google cloud vision API 发出请求以对其进行分类。
I'm doing the following:我正在做以下事情:
@app.route('/cloud_vision', methods=['POST'])
def cloud_vision():
files = flask.request.files.getlist('files')
client = vision.ImageAnnotatorClient()
if len(files) > 1 or files[0].filename != '':
for file in files:
with io.open(file, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
(...)
But im getting this error TypeError: expected str, bytes or os.PathLike object, not FileStorage
when opening the file.但我收到此错误
TypeError: expected str, bytes or os.PathLike object, not FileStorage
打开文件时。 How can I correct this?我该如何纠正这个问题?
Please note that I'm not familiar with flask but to resolve your issue you should use file.filename
in io.open()
.请注意,我不熟悉 flask但要解决您的问题,您应该在
file.filename
io.open()
中使用 file.filename。 I used the sample code in this article to be able to use getlist()
.我使用本文中的示例代码来使用
getlist()
。 See code below:请参阅下面的代码:
app.py应用程序.py
from flask import Flask, render_template, request, redirect, url_for
from google.cloud import vision
import io
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def upload_file():
client = vision.ImageAnnotatorClient()
files = request.files.getlist('file')
if len(files) > 1 or files[0].filename != '':
for file in files:
file.save(file.filename) # I add saving for testing
with io.open(file.filename, 'rb') as image_file: # use file.filename
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
return str(labels)
if __name__==('__main__'):
app.run(debug=True)
index.html index.html
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
Testing (image used is seen here ):测试(使用的图像见此处):
After submitting the image, I returned the response on the webpage.提交图片后,我在网页上返回了响应。
Output after submitting the image: Output 提交图片后:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.