Save a grayscale image as an colored image

조회 수: 23 (최근 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 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