【问题标题】:Sending opencv image along with additional data to Flask Server将 opencv 图像与附加数据一起发送到 Flask Server
【发布时间】:2019-02-20 09:20:42
【问题描述】:

我目前能够使用以下代码将 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

【问题讨论】:

  • 您能粘贴一下您是如何尝试将您的框架和唯一 ID 结合起来的吗?此外,如果您将 unique_id 显式转换为字节,您会发现此错误。将其留给 JSON 来处理事物的编码解码,如下所述:stackoverflow.com/questions/44682018/…
  • 我在@RahulRaghunath 问题中添加了我的 json 代码

标签: python opencv flask


【解决方案1】:

我实际上已经通过使用 Python requests 模块而不是 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

当我尝试发送 multipart/form-data 和 requests 模块时,它能够在单个请求中发送文件和数据。

【讨论】:

    【解决方案2】:

    你可以尝试用base64字符串编码你的图片

    import base64
    
    with open("image.jpg", "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    

    并将其作为普通字符串发送。

    【讨论】:

    • 我不是直接读取图像,图像是numpy数组的形式
    • encoded_string = base64.b64encode(np_array) 你能试试吗?
    【解决方案3】:

    正如其他人建议的那样,base64 编码可能是一个很好的解决方案,但是如果您不能或不想这样做,您可以在请求中添加自定义标头,例如

    headers = {"X-my-custom-header": "uniquevalue"}
    

    然后在烧瓶一侧:

    unique_value = request.headers.get('X-my-custom-header')
    

    unique_value = request.headers['X-my-custom-header']
    

    这样您就可以避免再次处理图像数据的开销(如果这很重要),并且您可以使用类似于 python uuid 模块的东西为每个帧生成一个唯一的 id。

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 2023-01-05
      • 2015-09-15
      • 2020-01-13
      相关资源
      最近更新 更多