发送和接收opencv图像烧瓶

时间:2018-01-26 16:42:43

标签: python opencv flask

我正在尝试从客户端到服务器发送和接收openCV图像,并在处理后返回客户端。我无法理解服务器发回的数据类型......

服务器:

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)

客户端:

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 )

print语句推出

<Response [200]>

错误是......

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

我是新手,请帮我解决这个错误。


谢谢。

1 个答案:

答案 0 :(得分:0)

想法:

  • 客户

使用 cv2.imread('lena.jpeg') 将图像加载到 numpy 数组。 将数组腌制为数据。 使用 POST 请求发送数据,multipart/form-data

  • 服务器

接收数据 Pickle 加载数据 我们有与 cv2.imread('lena.jpeg') 相同的 numpy 数组

这是代码:

客户端上的序列化numpy数组

img = cv2.imread('lena.jpeg')
serialized = pickle.dumps(frame, protocol=0)

将其与发布请求一起发送到服务器

name_img = "frame.jpeg"
files = {'image': (name_img, serialized, 'multipart/form-data', {'Expires': '0'})}
with requests.Session() as s:
    r = s.post(url, files=files)
    print("status ", r.status_code)
    return r

在服务器上,将其加载回 numpy 数组

@app.route('/receive-frame', methods=['POST'])
def handler_receive_frame():
    timestamp = str(int(time.time()))
    file = request.files['image']
    file_path = os.path.join(save_dir, "image_" + timestamp + ".jpeg")
    # file.save(file_path)
    # cv2.imwrite(file_path, file.read())
    image_numpy = pickle.loads(file.read())
    cv2.imwrite(filename=file_path, img=image_numpy)

    print("receive file name ", file.filename)
    print("output_file_name ", file_path)
    result = {"error": 0}
    return result

我们在服务器上的 image_numpy 与客户端上的 img 相同(它是一个 numpy 数组)。

无论你想用img = cv2.imread('lena.jpeg')做什么,你都可以用image_numpy