Save a grayscale image as an colored image

23 次查看(过去 30 天)
I have a matrix
g
It is a grayscale image with size (32,32). I want it to save it as an colored image. How to do it?
imwrite(g, colormap(jet), 'test.png')
The above code gives some uniform random colored image and hence don't know what is the error in it.
Also,
imwrite(g, colormap(gray), 'test.png')
gives a completely white image. Can anyone tell me what is going wrong.

采纳的回答

DGM
DGM 2022-6-21
编辑:DGM 2022-6-21
Depending on what you mean when you say you want it to be a colored image, this might have the answer:
Of particular interest may be the use of ind2rgb() if you want the result to adhere to a given colormap.
If you actually want the output PNG to be an indexed image, that might be a different story. I can't know what values the image g contains, so I can't know how it will be mapped. For a uint8 image, things should be simple enough.
Don't use colormap() for this. Colormap() is a tool for getting/setting the current axes colormap. If you do something like colormap(jet), imread() will wind up getting some uncontrolled-length map. The length of the map will depend on the version you're using and whatever the last map was in whichever axes was most recent -- even if the image processing you're doing has nothing to do with any figures/axes.
If you want an actual Mx3 colormap, get it using the appropriate function like jet(), gray(), parula(), etc. You'll need to specify an appropriate map length.
g = imread('cameraman.tif');
% write the image with a given colormap
cmap = parula(256); % don't use colormap()
imwrite(g,cmap,'test.png')
% read it back
[g2 cmap2] = imread('test.png');
imshow(g2,cmap2)
I'm going to guess that the array g is either improperly-scaled for its class or something. I can't really know unless you show what it is though. You could always attach it as a .mat file if none of the above helps.

更多回答(1 个)

Image Analyst
Image Analyst 2022-6-21
Another option is to use ind2rgb to convert the image to a true color image
grayImage = imread('cameraman.tif');
subplot(2, 1, 1);
imshow(grayImage);
title('Original Gray Scale Image')
myColorMap = turbo(256);
rgbImage = ind2rgb(grayImage, myColorMap);
imwrite(rgbImage, fileName);
subplot(2, 1, 2);
imshow(rgbImage);
title('Image Converted to RGB with colormap and ind2rgb()')

类别

Help CenterFile Exchange 中查找有关 Blue 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by