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

Apr*_*cot 2 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)
Run Code Online (Sandbox Code Playgroud)

我的 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
Run Code Online (Sandbox Code Playgroud)

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

我尝试将 bytearray 与图像的宽度和高度一起传递给 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)
Run Code Online (Sandbox Code Playgroud)

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

在 api 接收图像

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

但例如收到以下错误:

TypeError: 'LocalProxy' does not have the buffer interface
Run Code Online (Sandbox Code Playgroud)

the*_*oan 5

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)
Run Code Online (Sandbox Code Playgroud)

使用 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)
Run Code Online (Sandbox Code Playgroud)

我提到了这个链接: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,因为它需要字节状物体这里提到:https://docs.python.org/3/library/io.html#io.BytesIO,和字节类对象的解释在这里:https : //docs.python.org/3/glossary.html#term-bytes-like-object 所以,而不是这样做。直接传递文件名来cv2.imread(img.filename)解决这个问题。