Send and receive opencv images flask

2020-07-27 02:41发布

问题:

I am trying to send and receive openCV images form client to server and back to client after processing. I am not able to understand the what type of data is being sent back by the server ...

Server:

from flask import Flask, request, Response, send_file
import jsonpickle
import numpy as np
import cv2

import ImageProcessingFlask

# Initialize the Flask application
app = Flask(__name__)


# route http posts to this method
@app.route('/api/test', methods=['POST'])
def test():
    r = request
    # convert string of image data to uint8
    nparr = np.fromstring(r.data, np.uint8)
    # decode image
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    # do some fancy processing here....

    img = ImageProcessingFlask.render(img)


    #_, img_encoded = cv2.imencode('.jpg', img)
    #print ( img_encoded)

    cv2.imwrite( 'new.jpeg', img)


    #response_pickled = jsonpickle.encode(response)
    #return Response(response=response_pickled, status=200, mimetype="application/json")
    return send_file( 'new.jpeg', mimetype="image/jpeg", attachment_filename="new.jpeg", as_attachment=True)

# start flask app
app.run(host="0.0.0.0", port=5000)

Client:

import requests
import json
import cv2

addr = 'http://localhost:5000'
test_url = addr + '/api/test'

# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}

img = cv2.imread('lena.jpeg')
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)

# send http request with image and receive response
response = requests.post(test_url, data=img_encoded.tostring(), headers=headers)



print response


cv2.imshow( 'API', response.content )

The print statement puts out

<Response [200]>

The error is ...

    cv2.imshow( 'API', response.content )
TypeError: mat is not a numpy array, neither a scalar

I am new to flask, please help me solve this error.


Thank you.