Warm tip: This article is reproduced from serverfault.com, please click

python-将opencv图像以及其他数据发送到Flask Server

(python - Sending opencv image along with additional data to Flask Server)

发布于 2018-09-16 04:37:48

我目前可以使用以下代码将OpenCV图像帧发送到我的Flask服务器

def sendtoserver(frame):
    imencoded = cv2.imencode(".jpg", frame)[1]
    headers = {"Content-type": "text/plain"}
    try:
        conn.request("POST", "/", imencoded.tostring(), headers)
        response = conn.getresponse()
    except conn.timeout as e:
        print("timeout")


    return response

但是我想发送一个unique_id以及我尝试使用JSON组合框架和ID的框架,但是遇到以下错误TypeError: Object of type 'bytes' is not JSON serializable,任何人都不知道我如何将一些其他数据与框架一起发送到服务器。

更新:

json格式代码

def sendtoserver(frame):
    imencoded = cv2.imencode(".jpg", frame)[1]
    data = {"uid" : "23", "frame" : imencoded.tostring()}
    headers = {"Content-type": "application/json"}
    try:
        conn.request("POST", "/", json.dumps(data), headers)
        response = conn.getresponse()
    except conn.timeout as e:
        print("timeout")


    return response
Questioner
Mohd Shibli
Viewed
11
Mohd Shibli 2018-09-17 21:11:52

我实际上已经通过使用Python请求模块而不是http.client模块解决了查询,并且对我的上述代码进行了以下更改。

import requests
def sendtoserver(frame):
    imencoded = cv2.imencode(".jpg", frame)[1]
    file = {'file': ('image.jpg', imencoded.tostring(), 'image/jpeg', {'Expires': '0'})}
    data = {"id" : "2345AB"}
    response = requests.post("http://127.0.0.1/my-script/", files=file, data=data, timeout=5)
    return response

当我尝试发送多部分/表单数据和请求模块时,模块可以在单个请求中发送文件和数据。