Question

I have a custom color map cmap that I use to display a matrix X that contains negative values. I display it using

image(X, 'CDataMapping', 'scaled');
colormap(cmap);
axis normal;

It works great, but now I would like to save the matrix as an image with that same color map.

When I try the following :

imwrite(X, cmap, 'test.tif');

I get an all-black image. I understand that tiff wants to map these into the 0 to 1 or 0 to 2^16 space, so I tried doing

X = X - min(X(:));
X = (X/max(X(:)))*(2^16);
X = uint16(X);

But then when I tried to save X with the cmap, the file was corrupted and wouldn't open. I tried regenerating the custom color map using the new scale of 0 to 2^16-1, but the image created from that also was unreadable.

Any ideas on how this might be accomplished?

Was it helpful?

Solution 2

Here's how I finally resolved it:

In addition to modifying the matrix, I had to normalize the color map into the 0 to 1 space. I also had to multiple by the length of the color map instead of 2^16.

Here's what that ended up looking like:

cmap = cmap - min(cmap(:));
cmap = cmap/max(cmap(:));
N = size(cmap, 1);
X = X - min(X(:));
X = (X/max(X(:)))*N;
X = uint16(X);
imwrite(X, cmap, 'test.tif');

I hope this saves some of you the trouble it caused me!

OTHER TIPS

it seems like there's no image file format that supports 16 bit indexed color image saving:
TIFF does not support indexed colors, and PNG does not support 16 bit index.

Try converting to full RGB and save that as tiff:

rgb = ind2rgb( uint16(X), cmp ); % with X scaled as in your question
imwrite( rgb, 'myTiffImage.tif' ); % write the RGB image
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top