MATLAB Answers

Saving gray scale image

167 views (last 30 days)
Babu Sankhi
Babu Sankhi on 28 Jul 2020
Commented: Babu Sankhi on 30 Jul 2020
Hi all,
I want to save my image in gray scale. Of course I can display the gray image by using code;
figure(3);
imagesc ((testI(:,:,1)));colormap gray
But I want those images to be saved and I tried this way;
for k=1
I1 =medfilt2(testI(:,:,k)-sat);%actual
filename=sprintf('kalyan%02d.png', k);%saves all files
imagesc(I1); axis image; colorbar; colormap(gray);
imwrite(I1, filename, 'png');
end
But saved images are not gray. Can you please help me ??
Thank you

Accepted Answer

jonas
jonas on 28 Jul 2020
Edited: jonas on 28 Jul 2020
Using a single color channel to convert your image to grayscale is not optimal. The gray tone is usually a combination of red, blue and green. Better use rgb2gray() instead
imwrite(rgb2gray(I1), filename, 'png');
If you really want to save the gray image based on a single channel, then just pass that channel as input to imwrite().
  8 Comments
Babu Sankhi
Babu Sankhi on 30 Jul 2020
ok thank you analyst.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 28 Jul 2020
Edited: Image Analyst on 29 Jul 2020
What is sat? A scalar? I1 should be gray scale because you took it as the red channel of testI. In fact, this code shows they are gray scale:
testI = imread('Peppers.png'); % Read in sample RGB image.
sat = 10;
for k = 1 % Red channel ONLY
I1 =medfilt2(testI(:,:,k)-sat);%actual
filename=sprintf('kalyan%02d.png', k);%saves all files
imagesc(I1); axis image; colorbar; colormap(gray);
imwrite(I1, filename);
% Recall
recalledI = imread(filename);
[rows, columns, numberOfColorChannels] = size(recalledI);
if numberOfColorChannels == 1
fprintf('%s is grayscale.\n', filename); % This is what prints.
else
fprintf('%s is RGB.\n', filename);
end
end
  3 Comments
Babu Sankhi
Babu Sankhi on 29 Jul 2020
I am sorry, I mean the saved image is not like attached image ( image I want .png).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by