How to convert from numpy array to file byte object?

Question:

I read an image file as

with open('abc.jpg', 'rb') as f:
    a = f.read()

On the other hand, I use cv2 to read the same file

b = cv2.imread('abc.jpg', -1)

How to convert b to a directly?

Thanks.

Asked By: Chan

||

Answers:

Answer to your question:

success, a_numpy = cv2.imencode('.jpg', b)
a = a_numpy.tostring()

Things you should know:

First, type(a) is a binary string, and type(b) is a numpy array. It’s easy to convert between those types, since you can make np.array(binary_string) to go from string to numpy, and np_array.tostring() to go from numpy to binary string.

However, a and b represent different things. In the string a, you’re reading the JPEG encoded version of the image, and in b you have the decoded image. You can check that len(b.tostring()) is massively larger than len(a). You need to know which one you want to use. Also, keep in mind that each time you encode a JPEG, you will loose some quality.

How to save an image to disk:

Your question looks like you want an encoded binary string. The only use I can imagine for that is dumping it to the disk (or sending it over http?).

To save the image on your disk, you can use

cv2.imwrite('my_file.jpg', b)
Answered By: Marco Lavagnino
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.