2

I am having difficulty sending a jpeg opened with cv2 to a server as bytes. The server complains that the file type is not supported. I can send it without problems using Python's "open" function, but not with OpenCV. How can I get this to work?

import cv2

path = r".\test\frame1.jpg"

with open(path, "rb") as image:
    image1 = image.read()
image2 = cv2.imread(path, -1)
image2 = cv2.imencode(".jpg", image2)[1].tobytes() #also tried tostring()

print(image1 == image2)
#This prints False. 
#I want it to be True or alternatively encoded in a way that the server accepts.

1 Answer 1

1

I want to start by getting your test case working, we will do this by using a lossless format with no compression so we are comparing apples to apples:

import cv2

path_in = r".\test\frame1.jpg"
path_temp = r".\test\frame1.bmp"
img = cv2.imread(path_in, -1)
cv2.imwrite(path_temp, img) # save in lossless format for a fair comparison

with open(path_temp, "rb") as image:
    image1 = image.read()

image2 = cv2.imencode(".bmp", img)[1].tobytes() #also tried tostring()

print(image1 == image2)
#This prints True. 

This is not ideal since compression is desirable for moving around bytes, but it illustrates that there is nothing inherently wrong with your encoding.

Without knowing the details of your server it is hard to know why it isn't accepting the opencv encoded images. Some suggestions are:

  • provide format specific encoding parameters as described in the docs, available flags are here
  • try different extensions
Sign up to request clarification or add additional context in comments.

1 Comment

After getting them to match I tried uploading the image as a PNG to the server but encountered the same error. This helped me realize that the problem wasn't the file type or the encoding but the way the HTTP library that I was using (requests) was sending the image file. It seemed to have been prepending something to my image and corrupting it. I was able to resolve this by more explicitly defining the content type and headers: requests.readthedocs.io/en/master/user/quickstart

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.