Ask Your Question

how to know grayscale or color img loaded

asked 2014-07-04 07:32:49 -0500

fedor gravatar image

updated 2015-10-31 14:34:21 -0500

I need to know, is loaded img grayscale or color to not process grayscale. My idea is get grayscale by cvtColor(src,src_gray,COLOR_BGR2GRAY) and compare with loaded img.

Perhaps there is a standard or a more interesting variant?

edit retag flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted

answered 2014-07-04 09:19:40 -0500


If you are loading a Gray scale image as a Color image. You can check that by Comparing RGB Values of All the pixels. For Example If the image is a Gray Scale image then


For more accurate results you can introduce some thresholds values. i.e

if((abs(R-G)< Threshold))// Threshold-> can be greater than zero. eg 0.006

By this way you can get pretty good results.

edit flag offensive delete link more

answered 2014-07-04 09:05:36 -0500

Haris gravatar image

updated 2014-07-04 09:10:13 -0500

Load image with default depth using the macro CV_LOAD_IMAGE_ANYDEPTH like,

  const cv::Mat src = cv::imread(filename, CV_LOAD_IMAGE_ANYDEPTH);

And check the number of channel using Mat::channels like,

edit flag offensive delete link more


print "1" for all images (color and grayscale). Are you sure that it works?

fedor gravatar imagefedor ( 2014-07-31 07:33:18 -0500 )edit

Saw the same behavior as the above comment.

krsw21 gravatar imagekrsw21 ( 2020-04-27 16:46:05 -0500 )edit

answered 2014-07-05 04:58:35 -0500

updated 2014-07-05 04:59:34 -0500

If you are not interested by a color image (ie you only want to convert color image into grayscale) and to avoid testing all values (RGB, RGBA, etc), you could directly load your image in grayscale:

cv::Mat image = cv::imread( "myImage.jpg/png/...", CV_LOAD_IMAGE_GRAYSCALE );

The mat 'image' will be in grayscale. See the doc of imread for more information.

edit flag offensive delete link more

Question Tools


Asked: 2014-07-04 07:32:49 -0500

Seen: 28,762 times

Last updated: Jul 05 '14