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

无人久伴 提交于 2019-11-29 17:37:00

问题


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.


回答1:


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




回答2:


I'm kind of late but there is another simple way out there:

Use image.ndim Source, will give your right number of channels as below:


if image.ndim == 2:

    channels = 1 #single (grayscale)

if image.ndim == 3:

    channels = image.shape[-1]

Since a image is a nothing but a numpy array. Checkout OpenCV docs here: docs




回答3:


As i know, u should use image.shape[2] to determine number of channels, not len(img.shape), the latter gives the dimensions of the array.



来源:https://stackoverflow.com/questions/19062875/how-to-get-the-number-of-channels-from-an-image-in-opencv-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!