How to save image with custom colormap (imwrite problems)
21 views (last 30 days)
Show older comments
Hello everyone, I am trying to save a large matrix who's cells contain one of 6 possible values (0, 50, 100, 150, 200, 255)(if needed those values can be changed). I also have a 6 by 3 matrix as color map: cmap=[153 76 0; 0 128 255; 96 96 96; 224 224 224; 255 255 255; 0 0 0]/255; (those colors need to stay as they are).
I try to save the image like this
imwrite(matrix, cmap, 'name.png');
but the image is saved with only two colors. I have tried different image types and different rang values for the matrix but no solution.
Can anyone help me with this?
Thank you very much.
Cheers,
Camilo
0 Comments
Accepted Answer
Image Analyst
on 18 Apr 2016
Try imwrite() and see if that works. Use imread() to see if the saved colormap comes back with only 2 colors, or all 6.
12 Comments
Image Analyst
on 1 May 2016
You need to use a different colormap when you're creating the RGB image.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
s= load('cs_plot.mat')
cs_plot = s.cs_plot;
whos cs_plot
subplot(3, 2, 1);
imshow(cs_plot);
axis on;
title('Indexed Image with no colormap', 'FontSize', fontSize);
unique(cs_plot(:))
subplot(3, 2, 2);
histogram(cs_plot);
grid on;
title('Histogram', 'FontSize', fontSize);
cmap=[153 76 0; 0 128 255; 96 96 96; 224 224 224; 255 255 255; 0 0 0]/255;
h3 = subplot(3, 2, 3);
imshow(cs_plot);
title('Indexed Image', 'FontSize', fontSize);
colormap(h3, cmap);
colorbar
drawnow;
% Get an RGB image
colorMapForSaving = imresize(cmap,[256, 3], 'nearest');
rgbImage = ind2rgb(cs_plot, colorMapForSaving);
h4 = subplot(3, 2, 4);
imshow(rgbImage);
title('RGB Image', 'FontSize', fontSize);
drawnow;
filename = 'delete_me.png'
imwrite(rgbImage, filename);
% Recall from disk and see if it's okay.
rgbImage = imread(filename);
h4 = subplot(3, 2, 5);
imshow(rgbImage);
title('Recalled Image', 'FontSize', fontSize);
% Delete temporary file
delete(filename)
More Answers (0)
See Also
Categories
Find more on Red in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!