我目前可以使用以下代码将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
答案 0 :(得分:2)
我实际上是通过使用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
当我尝试发送多部分/表单数据和请求模块时,它具有在单个请求中同时发送文件和数据的功能。
答案 1 :(得分:0)
您可以尝试使用base64字符串对图像进行编码
import base64
with open("image.jpg", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
并将其作为普通字符串发送。
答案 2 :(得分:0)
正如其他人建议的那样,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。
希望有帮助