Tzn
Tzn

Reputation: 632

How to encode OpenCV Image as bytes using Python

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.

Upvotes: 2

Views: 6278

Answers (1)

shortcipher3
shortcipher3

Reputation: 1380

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

Upvotes: 1

Related Questions