【问题标题】:Python Flask API - post and receive bytearray and metadataPython Flask API - 发布和接收字节数组和元数据
【发布时间】:2018-07-16 07:05:16
【问题描述】:

我正在创建一个 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,例如:

方法二:上传图片到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

【问题讨论】:

    标签: python arrays image flask


    【解决方案1】:

    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) 解决了这个问题。

    【讨论】:

    • 谢谢...我最初的开发与您提供的非常相似...这是发布图像并接收另一端。它可以正常工作。但是,客户端只能以字节数组的形式发送图像,因此问题...再次感谢您引用帮助链接...我将通过它们。
    • 谢谢并道歉....我错过了“rb”参数,并认为您提供的代码只是读取并推送文件...这非常有效。再次感谢您。
    • 我正在学习 Flask,您的帖子和评论帮助我进一步了解了它,所以谢谢。
    • 当我尝试将图像作为字节数组发布到 127.0.0.1:5000 服务器时,我会使用 opencv 读取服务器中的图像......但是当我更改远程服务器的路径时。 ..图片没有送达...你有什么想法吗...
    • 服务器上的print (img.filename) 提供了什么?
    猜你喜欢
    • 2010-11-13
    • 2014-09-30
    • 2020-12-05
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多