Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending opencv image along with additional data to Flask Server

I am currently able to send OpenCV image frames to my Flask Server using the following code

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

But I want to send a unique_id along with the frame I tried combining the frame and the id using JSON but getting following error TypeError: Object of type 'bytes' is not JSON serializable does anybody have any idea how I can send some additional data along with the frame to the server.

UPDATED:

json format code

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
like image 401
Mohd Shibli Avatar asked Jan 01 '23 20:01

Mohd Shibli


1 Answers

I have actually solved the query by using the Python requests module instead of the http.client module and have done the following changes to my above code.

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

As I was trying to send a multipart/form-data and requests module has the ability to send both files and data in a single request.

like image 196
Mohd Shibli Avatar answered Jan 14 '23 05:01

Mohd Shibli