Python Flask API-发布和接收字节数组和元数据

时间:2018-07-16 07:05:17

标签: python arrays image flask

我正在创建一个API以接收和处理图像。我必须以字节数组格式接收图像。以下是我要发布的代码:

方法1 将图像发布到api

with open("test.jpg", "rb") as imageFile:
    f = imageFile.read()
    b = bytearray(f)    
    url = 'http://127.0.0.1:5000/lastoneweek'
    headers = {'Content-Type': 'application/octet-stream'}
    res = requests.get(url, data=b, headers=headers)
    ##print received json response
    print(res.text)

我的API:在api上接收图片

@app.route('/lastoneweek', methods=['GET'])
def get():
    img=request.files['data']
    image = Image.open(io.BytesIO(img))
    image=cv2.imread(image)
    ##do all image processing and return json response

在我的api中,我尝试了request.get['data'] request.params['data'] ....我遇到了object has no attribute错误。

我尝试将字节数组以及图像的宽度和高度传递给json,例如:

方法2 :将图像发布到api

data = '{"IMAGE":b,"WIDTH":16.5,"HEIGHT":20.5}'
url = 'http://127.0.0.1:5000/lastoneweek'
headers = {'Content-Type': 'application/json'}
res = requests.get(url, data=data, headers=headers)

并将我在API的get函数更改为

通过api接收图像

@app.route('/lastoneweek', methods=['GET'])
def get():
    data=request.get_json()
    w = data['WIDTH']
    h = data['HEIGHT']

但是例如收到以下错误:

TypeError: 'LocalProxy' does not have the buffer interface

1 个答案:

答案 0 :(得分:3)

server.py文件:

from flask import Flask
from flask import request
import cv2
from PIL import Image
import io
import requests
import numpy as np

app = Flask(__name__)

@app.route('/lastoneweek', methods=['POST'])
def get():
    print(request.files['image_data'])
    img = request.files['image_data']
    image = cv2.imread(img.filename)
    rows, cols, channels = image.shape
    M = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 1)
    dst = cv2.warpAffine(image, M, (cols, rows))
    cv2.imwrite('output.png', dst)
    ##do all image processing and return json response
    return 'image: success'

if __name__ == '__main__':
    try:
        app.run()
    except Exception as e:
        print(e)

client.py文件为:

import requests

with open("test.png", "rb") as imageFile:
    # f = imageFile.read()
    # b = bytearray(f)    
    url = 'http://127.0.0.1:5000/lastoneweek'
    headers = {'Content-Type': 'application/octet-stream'}
    try:
        response = requests.post(url, files=[('image_data',('test.png', imageFile, 'image/png'))])
        print(response.status_code)
        print(response.json())
    except Exception as e:
        print(e)
    # res = requests.put(url, files={'image': imageFile}, headers=headers)
    # res = requests.get(url, data={'image': imageFile}, headers=headers)
    ##print received json response
    print(response.text)

我引用了此链接:http://docs.python-requests.org/en/master/user/advanced/#post-multiple-multipart-encoded-files 这解决了第一个问题。

image = Image.open(io.BytesIO(img))行是错误的,因为img<class 'werkzeug.datastructures.FileStorage'>,不应将其传递给io.BytesIO,因为它采用了类似于字节的对象,如下所述:{{3} },并在此处说明类似字节的对象:https://docs.python.org/3/library/io.html#io.BytesIO 因此,不要这样做。直接将文件名传递给cv2.imread(img.filename)解决了该问题。