如何将图像和一些文本发送到服务器Flask

问题描述

我想使用 Flask 创建 API,该 API 可以接受带有一些字符串数组的图像。有许多解决方案可以保存图像然后作为文件发送。我有兴趣将图像作为 Json 数据发送。这是演示它的链接https://gist.github.com/kylehounslow/767fb72fde2ebdd010a0bf4242371594

我只想修改上面链接上的代码,这样我也应该能够发送一些字符串值,例如图像中的人数、捕获的时间等。

请为服务器端和客户端编写代码片段。

给定的代码客户端:

from __future__ import print_function
import requests
import json
import cv2

addr = 'http://localhost:5000'
test_url = addr + '/api/test'

# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}

img = cv2.imread('lena.jpg')
# encode image as jpeg
_,img_encoded = cv2.imencode('.jpg',img)
# send http request with image and receive response
response = requests.post(test_url,data=img_encoded.tostring(),headers=headers)
# decode response
print(json.loads(response.text))

# expected output: {u'message': u'image received. size=124x124'}

给定的代码服务器:

from flask import Flask,request,Response
import jsonpickle
import numpy as np
import cv2

# Initialize the Flask application
app = Flask(__name__)


# route http posts to this method
@app.route('/api/test',methods=['POST'])
def test():
    r = request
    # convert string of image data to uint8
    nparr = np.fromstring(r.data,np.uint8)
    # decode image
    img = cv2.imdecode(nparr,cv2.IMREAD_COLOR)

    # do some fancy processing here....

    # build a response dict to send back to client
    response = {'message': 'image received. size={}x{}'.format(img.shape[1],img.shape[0])
                }
    # encode response using jsonpickle
    response_pickled = jsonpickle.encode(response)

    return Response(response=response_pickled,status=200,mimetype="application/json")


# start flask app
app.run(host="0.0.0.0",port=5000)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)