JuliaImages / juliaimages.github.io

Documentation For JuliaImages
https://juliaimages.org
33 stars 55 forks source link

How to set bit depth when saving files? #260

Open orswan opened 11 months ago

orswan commented 11 months ago

I am trying to save a bitmap with a specific bit depth. However, regardless of the type of an image, when I save it as a bitmap, it ends up with bit depth 24. I cannot find anything in the documentation when I search for "bit depth". How can I accomplish this?

A minimal working example is as follows:

using Images, FileIO
#dir = "/path/to/dir"
im_large = n0f16.(Gray.(rand(100,100)))
save(dir * "large.bmp",im_large)
im_small = n0f8.(Gray.(rand(100,100)))
save(dir * "small.bmp",im_small)

Both saved bmp files end up having bit depth 24 on my system (Windows 10).

Edit: It seems that this issue has to do with the number of channels. Even though my images above are supposedly greyscale, the images are saved with three color channels (all having equal values). An 8-bit bmp should have just a single channel.

timholy commented 11 months ago

This is a limitation of the ImageMagick C library. To prove this, I added

    @show T ncolors colorspace depth

right before this line in constituteimage and got the following output:

julia> save(dir * "large.bmp",im_large)
T = UInt16
ncolors = 1
colorspace = "Gray"
depth = 16

So we're passing in the full grayscale 16-bit image to that ccall; what they do with it is up to them.

We've had a lot of trouble with ImageMagick for many different formats, and the ImageIO package is gradually accumulating Julia-native readers of different file formats. Care to write one for BMP? The file format seems well-documented: https://en.wikipedia.org/wiki/BMP_file_format.

Alternatively, use a format with support for 16-bit grayscale. PNG (as long as you're using ImageIO.jl rather than ImageMagick) and TIFF (via Tiffmages.jl) should work fine.

julia> save(dir * "large.png",im_large)

julia> imgl = load(dir * "large.png");

julia> eltype(imgl)
Gray{N0f16}
orswan commented 11 months ago

Alternatively, use a format with support for 16-bit grayscale. PNG (as long as you're using ImageIO.jl rather than ImageMagick) and TIFF (via Tiffmages.jl) should work fine.

The images I generate are to be uploaded to a hardware device (a spatial light modulator) which only accepts .bmp. So unless you know of an easy way to batch convert one of those other file types to 8-bit .bmp, this won't work.

We've had a lot of trouble with ImageMagick for many different formats, and the ImageIO package is gradually accumulating Julia-native readers of different file formats. Care to write one for BMP? The file format seems well-documented: https://en.wikipedia.org/wiki/BMP_file_format.

Maybe someday. For now I just need to get something working, so I'm heading to Mathematica land for now (at least for this problem).

At any rate, thanks for the clarifying reply.