How to convert a matrix to a Gray scale image?

73 views (last 30 days)
vikas
vikas on 1 Mar 2012
Commented: elnaz gh on 24 Apr 2021
i need a matrix(with values between 0 to 255) to be converted to a gray scale image. I have tried using the function mat2gray but the problem with this function is that it scales down the pixel values of the image within the range 0 to 1 .Although the correct image is being displayed the exact values(0-255) of the matrix are not being reflected in the image.My requirement is that the pixels of the image must have the same values as that of the corresponding matrix.I just want to know if there is any alternative solution to this problem. kindly help.
  5 Comments
Rik
Rik on 14 Dec 2020
Since R2017b you don't even have to think anymore:
gray_range=[0 255];
B = rescale(A,'InputMin',gray_range(1),'InputMax',gray_range(2));
%equivalent to (works on all releases):
B=(A-gray_range(1))/(gray_range(2)-gray_range(1));
Image Analyst
Image Analyst on 14 Dec 2020
Just note that after calling rescale on a uint8 image you get a double, not a uint8.
And note that depending on the range of gray_range, you may get clipping. But with the second B, the class remains uint8. It does not convert it to double.
Alternatives you may want to look into include mat2gray() and imadjust(). Just depends on what you want to do.
Remember if you're going to then save it you probably want to make sure it's uint8 or uint16 if you're going to use a standard image file format in imwrite(). Otherwise you can save it as a double if you use the MATLAB proprietary .MAT format with the save() function.

Sign in to comment.

Answers (6)

Image Analyst
Image Analyst on 7 Dec 2012
Your matrix is already a gray scale image. To display it use this:
imshow(yourMatrix, []);
The [] lets it scale the min value to 0 and the max value to 255. If you don't want that scaling, use
imshow(yourMatrix, [0 255]);
This won't do any scaling, so that if your min is at 100, it will show up with gray level 100, not at gray level 0 as in the [] case.
The reason you were seeing all white is that if the class of the image is single or double, then MATLAB expects the image to be in the range 0-1. 0 goes to 0 and 1 goes to 255 upon display. Because your values were all floating point values more than 1, they all got clipped at 255. You can use im2double() or gray2mat() to scale your image to the range 0-1, or just use [] with imshow() and not worry about it - that's what I do, it's the easiest way.
One final way is to just cast your image to uint8 before calling imshow:
imshow(uint8(yourImage), [0 255]);
Please run and understand this demo:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'pout.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Create a double-class image in the range 0-255
dblImage = double(grayImage);
% Display double image scaling min to 0 and max to 255.
subplot(2, 2, 2);
imshow(dblImage, []);
title('Double Grayscale Image', 'FontSize', fontSize);
% Display double image without intensity scaling.
subplot(2, 2, 3);
imshow(dblImage, [0 255]);
title('Double Grayscale Image', 'FontSize', fontSize);
% Create a double-class image in the range 0-1
dblImage2 = im2double(grayImage);
% Display double image scaling min to 0 and max to 255.
subplot(2, 2, 4);
imshow(dblImage2, []);
title('Double Grayscale Image in range 0-1', 'FontSize', fontSize);
  5 Comments
paramveer sran
paramveer sran on 22 Oct 2015
if we write this image as imwrite(A,'img1.png');.and then open the image as img2=imread('img.png'); imshow(img2).the output image show the edges only.how to write the image which was displayed by using imshow(A,[])
elnaz gh
elnaz gh on 24 Apr 2021
many thanks dear Image Analyst
this really helps me: imshow(yourMatrix, [0 255]);

Sign in to comment.


Jurgen
Jurgen on 6 Dec 2012
Its probably double. So do im2uint8(A) or uint8(A) if A is the matrix. Also use imshow instead of image if you can.

Jonathan Sullivan
Jonathan Sullivan on 1 Mar 2012
M = randi(255,[1e3 1e3]); % Your Matrix
image(M);
colormap('gray')
  2 Comments
vikas
vikas on 1 Mar 2012
By doing it this way the image is not being displayed(i am just getting a white image).But when i used the function impixelregion to view the pixel values i could see the values in the range 0-255.However this didn't match the original matrix.

Sign in to comment.


Walter Roberson
Walter Roberson on 1 Mar 2012
Is your original matrix RGB with distinct color planes? If so then there is no way to make it grayscale and preserve the original pixel values.
If your original matrix is RGB on which the color planes are all identical, then take any one of the color planes.
  1 Comment
vikas
vikas on 1 Mar 2012
The matrix basically contains values from 0 to 255. So if i try to convert it to an image it must be a gray image.

Sign in to comment.


yang
yang on 1 Mar 2012
THE matrix[M,N],[M,N,3],[M,N,O]?

pavithra bai
pavithra bai on 23 Mar 2016
how to display matrix of gray scale image in matlab

Community Treasure Hunt

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

Start Hunting!