Sending opencv image along with additional data to Flask Server Sending opencv image along with additional data to Flask Server flask flask

Sending opencv image along with additional data to Flask Server


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 requestsdef 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.


You can try encoding your image in base64 string

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

And send it as a normal string.


As others suggested base64 encoding might be a good solution, however if you can't or don't want to, you could add a custom header to the request, such as

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

Then on the flask side:

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

or

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

That way you avoid the overhead of processing your image data again (if that matters) and you can generate a unique id for each frame with something like the python uuid module.

Hope that helps