How to save an 8-bit bmp with Julia

156 Views Asked by At

I am trying to save 8-bit bmp files for use with a hardware device*. I am using Julia. Whatever I try, I am only able to get 24-bit bmp files. Here is a minimal working example to illustrate the problem:

using Images, FileIO
dir = "/path/to/dir/"
img = n0f8.(Gray.(rand(100,100)))
save(dir * "image.bmp",img)

If I examine the properties of the resulting image, it is 24 bits. The problem seems to be that, even though the image is grayscale, Julia saves it with three color channels. Apparently 8-bit bmps use a different format, but it is unclear to me whether it is possible to save in this format using Julia.

How can I save an 8-bit .bmp with Julia?


*The hardware is a spatial light modulator, and the 8-bit .bmp format is non-negotiable.

2

There are 2 best solutions below

0
Thomas Jalabert On

It seems like Images.jl does not support 8-bit .bmp but ".pgm" and ".png" allow 8-bit color depth.

0
Mark Setchell On

As it seems from @ThomasJalabert answer, Julia is unable to save an 8bpp (palette) BMP, you will probably need a work-around like I suggested in the comments using NetPBM which seems already to be used in Images.jl anyway.

So, as you would be using NetPBM to write the 8bpp BMP, you might as well save your image from Julia in NetPBM's native format which is PGM for grayscale images and PPM for colour images.

Assuming you can do that, and create IMAGE.PPM from Julia, you then need to execute the following command (which I presume you enclose in backticks in Julia) to create 8bpp result.bmp:

ppmtobmp -bpp 8 > result.bmp < IMAGE.PPM

I assume you have created an image with fewer than 256 colours already, but if not, you can use pnmquant in the command to reduce to 256 colours suitable for an 8bpp BMP like this:

pnmquant 256 < IMAGE.PPM | ppmtobmp -bpp 8 > result.bmp