Converting binary file to png images

Hi,

I’ve a huge (3.63GB) binary file with 3 channel images (uint8 representation, pixel values range from 0-255). I load this bin file into python and convert it into PNG files using:

mpimg.imsave(save_path + "img.png", img)

However the final size of the folder containing these images is only 2.18 GB

What could be the reason behind this?

PNG files have a lossless form of compression, often more than 50% compression. Not sure but that could be why you’re seeing smaller file sizes.

If its lossless form of compression shouldn’t they be of the same size? (The reason I decided to save it as PNG is because it would be lossless compression)

That’s the idea of lossless compression. It means you are able to compress the data, i.e. encode it some way to reduce its size, and then decode it without losing the original information. So if I have a raw file, in this case an image, and I compress it with some lossless encoder and then decompress using the decoder, it is bit-for-bit identical to the file prior to being compressed at all. So if I understand correctly, in your case the file was 3.63GB in its raw “bitmap” form, then when you compressed it as PNG and stored it on disk, the file is now “encoded” at a reduced size until you decode it at some later point. See https://en.wikipedia.org/wiki/Lossless_compression and https://en.wikipedia.org/wiki/Portable_Network_Graphics#Compression for reference.

2 Likes

Thank you for the wonderful explanation :slight_smile:

1 Like