how to get the number of channels from an image, in OpenCV 2?

LarsH picture LarsH · Sep 28, 2013 · Viewed 45.6k times · Source

The answers at Can I determine the number of channels in cv::Mat Opencv answer this question for OpenCV 1: you use the Mat.channels() method of the image.

But in cv2 (I'm using 2.4.6), the image data structure I have doesn't have a channels() method. I'm using Python 2.7.

Code snippet:

cam = cv2.VideoCapture(source)
ret, img = cam.read()
# Here's where I would like to find the number of channels in img.

Interactive attempt:

>>> img.channels()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'channels'
>>> type(img)
<type 'numpy.ndarray'>
>>> img.dtype
dtype('uint8')
>>> dir(img)
['T',
 '__abs__',
 '__add__',
...
 'transpose',
 'var',
 'view']
# Nothing obvious that would expose the number of channels.

Thanks for any help.

Answer

Abid Rahman K picture Abid Rahman K · Sep 28, 2013

Use img.shape

It provides you the shape of img in all directions. ie number of rows, number of columns for a 2D array (grayscale image). For 3D array, it gives you number of channels also.

So if len(img.shape) gives you two, it has a single channel.

If len(img.shape) gives you three, third element gives you number of channels.

For more details, visit here