发送opencv图像与额外数据到Flas

2024-10-03 23:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在可以使用以下代码将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

但是我想发送一个唯一的∗id和我尝试使用JSON组合框架和id的框架一起发送,但是得到以下错误TypeError: Object of type 'bytes' is not JSON serializable有人知道我如何将一些附加数据与帧一起发送到服务器吗。在

更新时间:

json格式代码

^{pr2}$

Tags: 代码图像服务器框架idjsonflaskresponse
3条回答

您可以尝试用base64字符串编码图像

import base64

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

把它作为普通的字符串发送。在

正如其他人建议的base64编码可能是一个好的解决方案,但是如果您不能或不想,您可以向请求添加一个定制的头,例如

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

然后在烧瓶侧:

^{pr2}$

或者

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

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

希望有帮助

实际上,我通过使用Python requests模块而不是http.客户端模块,并对我上面的代码做了以下更改。在

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

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

相关问题 更多 >