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

标签 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']....我得到对象没有属性错误。

我尝试将字节数组以及图像的宽度和高度传递给 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

最佳答案

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,因为它采用类似字节的对象,如下所述: 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)解决了问题。

关于Python Flask API - 发送和接收字节数组和元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51356287/

相关文章:

python - 学生小团体代码共享

ruby - 当起始索引大于 (array.size -1) 时,关于 ruby​​ Array [] 方法的混淆结果

mysql - 需要知道MySQL数据库中保存的字节数组的类

java - ImageIO 无法正确解析有效的 .png?

html - 如何正确地在段落旁边 float 图像?

python - 使用 PDFminer 解析 pdf(梵文脚本)会给出错误的输出

python - 将一个K长度的列表拆分为尽可能 "even"的L个子列表,即使K/L留有余数

Python - Django Manage.py Syncdb 失败?

php - 使用 PHP 和 MySQL 按多种类型对事件进行排序。

php - 表单未从 MySQL 表中删除列数据