Determine whether an image is Grayscale in Matlab
Solution 1
Similar to what @Milo suggested, but with a different function. Use ndims
:
ndims(pic)
returns the number of dimensions in the image pic
. The number of dimensions in an array is always greater than or equal to 2, and in an RGB image it'll be >2
. Trailing singleton dimensions are ignored (A singleton dimension is any dimension for which size(A,dim) = 1
.)
Solution 2
Color images have 3 channels (R, G, B), so:
size(pic, 3) = 3
For grayscale:
size(pic, 3) = 1
Solution 3
f=imfinfo('yourimage.someextension');
f.ColorType
this will return you the ColorType of the image ,which you may check programmatically.
Reanimation
Updated on June 06, 2022Comments
-
Reanimation almost 2 years
I'm writing a function which can take an image and perform specific smoothing tasks on. At the very beginning of my function I convert the image to a grayscale image using
pic = rgb2gray(pic);
I'm hoping to allow the function to take any image (even if its already grayscale). In Matlab, if I pass it a grayscale image it currently errors because it cannot convert it (which is obvious).
Is there a built in function or an easy way to test an image and determine its colour format?
I read on google something about isRGB and isGrayscale functions but they have been removed from later versions of Matlab...
I'm thinking something like this would be cool if it had a built in function.
if (pic == RGB) do . . . elseif (pic == GrayScale) do . . . else do . . .
If not, maybe I could write a function that takes a
pixel x,y
and tests its value?if (p(x,y) == ....
or something? I'm unsure... Thoughts? -
Reanimation about 11 yearsThis makes sense. Out of curiousity, what would
size(pic, 3)=2
be used for? Are there any other colour formats i should include? -
Milo about 11 yearsIn theory you can have images of any number of channels, 2 of course, or even many more than 3 (hyperspectral imaging). In practice, color images are 3 or 4-channel (color spaces). Depending on what your code does, you should better loop over the third dimension of the array (depth) to be able to deal with any type of image.