MATLAB Answers


How to convert a matrix to a Gray scale image?

Asked by vikas
on 1 Mar 2012
Latest activity Commented on by Image Analyst
on 23 Mar 2016

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.


That's what I already said in my Answer, but since vikas never Accepted it, I guess it either didn't do what he wanted to do, or he just never came back here to see who took the time to answer his question.

Log in to comment.

8 Answers

Answer by 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);
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);


Show 1 older comment

Great. Glad it helped you. Vikas still has not accepted any answer so I guess it's still an open issue for him.

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 to write the image which was displayed by using imshow(A,[])

Log in to comment.

Answer by Jonathan Sullivan on 1 Mar 2012

M = randi(255,[1e3 1e3]); % Your Matrix


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.

should be


Log in to comment.

Answer by 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

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.

Log in to comment.

Answer by yang
on 1 Mar 2012

THE matrix[M,N],[M,N,3],[M,N,O]?

  1 Comment

Log in to comment.

Answer by 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.


Log in to comment.

Answer by Hieu
on 4 Dec 2014

I have a matrix 200x200. Format -ASCII, .dat or .txt. How to convert to a image for proccessing? Thanks everyone!

  1 Comment

Hieu- go ahead and post your question as a new one. You can simply do it if you scroll up this page, click on "Ask a question" and ask your question there.

Log in to comment.

Answer by 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 to write the image which was displayed by using imshow(A,[])

  1 Comment

Please start your own new, separate discussion.

Log in to comment.

Answer by pavithra bai on 23 Mar 2016

how to display matrix of gray scale image in matlab

  1 Comment

Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!