Save a grayscale image as an colored image

18 ビュー (過去 30 日間)
ac_bm_mat
ac_bm_mat 2022 年 6 月 21 日
回答済み: Image Analyst 2022 年 6 月 21 日
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 Center および File ExchangeBlue についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by