MATLAB Answers

How can i check if an image is RGB or grayscale or binary?

356 views (last 30 days)
I'm a new in matlab, need answer to this question.. And, may i change the size of matrix of RGB image to two-dimensional matrix? I wanna try edge detection, i load an grayscale image but the image matrix show an image have three-dimensional matrix.. Any solutions?? Thank you for your response..
  3 Comments

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 18 Aug 2012
You can convert to grayscale using a combination of all color channels:
grayImage = rgb2gray(rgbImage);
Or you can extract one of the color channels:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
You can get the size (dimensions) like this:
[rows columns numberOfColorChannels] = size(yourImageArray);
  5 Comments
Walter Roberson
Walter Roberson on 15 Jun 2018
ndims(A) ==2 && islogical(A) --> true if binary image
ndims(A) == 2 && length(unique(A(:))) == 1 --> true if grayscale or indexed or bi-level but all the same color
ndims(A) == 2 && length(unique(A(:))) == 2 --> true if grayscale or indexed or bi-level with two different values
ndims(A) > 2 --> cannot be grayscale or indexed or binary
ndims(A) == 3 && size(A,3) == 3 && size(unique(A, 'rows'),1) == 1 --> rgb or hsv with all the same color
ndims(A) == 3 size(A,3) == 3 && size(unique(A, 'rows'),1) == 2 --> bilevel rgb or bilevel hsv
Here, bi-level refers to images that have two distinct colors. They might be binary images, but they might not be (for example, red letters on blue background). It is common to encode binary images as the values 0 and 1, but it is also common to encode binary images as the values 0 and 255.

Sign in to comment.

More Answers (2)


Noor Ul Islam
Noor Ul Islam on 27 Dec 2013
% first Read image
img=imread('imag.jpg');
% Check img whether it rgb or grayscale
[r c d]=size(img)
% if image is 3D above command will give an error; solution=remove o/p variable d, then it is %perfect
% to convert to grayscale
% use inbuilt command
img1=rgb2gray(img); %now you get 2D image
% to manipulate the true colors RGB; split image into R,G,B components as follow
R=img(:,:,1);
G=img(:,:,2);
B=img(:,:,3);
%Note: each R,G and B component is 2D matrix... hope this is what u required

Community Treasure Hunt

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

Start Hunting!