Flask OpenCV以字节为单位发送和接收图像

时间:2018-09-14 05:51:11

标签: python api opencv flask

我想在我的flask API中以字节为单位发送和接收图像。我还想在图像旁边发送一些json。我该如何实现?

下面是我当前无法使用的解决方案

烧瓶:

    @app.route('/add_face', methods=['GET', 'POST'])
    def add_face():
    if request.method == 'POST':
        # print(request.json)
        nparr = np.fromstring(request.form['img'], np.uint8)
        print(request.form['img'])
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        cv2.imshow("frame", img)
        cv2.waitKey(1)

    return "list of names & faces"

客户端:

def save_encoding(img_file):
    URL = "http://localhost:5000/add_face"
    img = open(img_file, 'rb').read()

    response = requests.post(URL, data={"name":"obama", "img":str(img)})
    print(response.content)

产生的错误:

cv2.imshow("frame", img)
cv2.error: OpenCV(3.4.3) /io/opencv/modules/highgui/src/window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

2 个答案:

答案 0 :(得分:1)

以base64格式发送图像会更容易,因为您只需要处理字符串,就可以避免有关发送/接收二进制数据的问题。同样,它在Web中也更加方便。经过测试的代码如下: 服务器端:

from flask import Flask, render_template, request
import pandas as pd
import cv2
import numpy as np
import base64

app = Flask(__name__)



@app.route('/add_face', methods=['GET', 'POST'])
def add_face():
    if request.method == 'POST':
        #  read encoded image
        imageString = base64.b64decode(request.form['img'])

        #  convert binary data to numpy array
        nparr = np.fromstring(imageString, np.uint8)

        #  let opencv decode image to correct format
        img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR);
        cv2.imshow("frame", img)
        cv2.waitKey(0)

    return "list of names & faces"
if __name__ == '__main__':
    app.run(debug=True, port=5000)

客户端:

import requests
import base64

URL = "http://localhost:5000/add_face"

#  first, encode our image with base64
with open("block.png", "rb") as imageFile:
    img = base64.b64encode(imageFile.read())

response = requests.post(URL, data={"name":"obama", "img":str(img)})
print(response.content)

如果您确定输入的图像可以使用COLOR而不是ANYCOLOR。

答案 1 :(得分:1)

以下内容对我有用。 我没有客户端代码,但是有卷曲请求。应该可以解决问题,

服务器

from flask import request
from PIL import Image
import io

@app.route("/add_face", methods=["POST"])
def predict():
    image = request.files["image"]
    image_bytes = Image.open(io.BytesIO(image.read()))

客户侧

curl -X POST -F image=@PATH/TO/FILE 'http://localhost:5000/add_face'