如何从OpenCV 2中获取图像的通道数?

Lar*_*rsH 12 python opencv image channels

答案我可以确定cv :: Mat Opencv中的通道数为OpenCV 1回答这个问题:你使用Mat.channels()图像的方法.

但是在cv2(我使用2.4.6)中,我所拥有的图像数据结构没有channels()方法.我正在使用Python 2.7.

代码段:

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

互动尝试:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Abi*_*n K 33

使用 img.shape

它为您提供各方向的img形状.即行数,用于2D阵列(灰度图像)的列数.对于3D阵列,它还为您提供了多个通道.

所以,如果len(img.shape)给你两个,它有一个通道.

如果len(img.shape)给你三个,第三个元素给你通道数.

有关详细信息,请访问此处


abh*_*nix 6

我有点晚了,但是还有另一种简单的方法:

使用image.ndim Source,将为您提供正确的频道数,如下所示:


if image.ndim == 2:

    channels = 1 #single (grayscale)

if image.ndim == 3:

    channels = image.shape[-1]
Run Code Online (Sandbox Code Playgroud)

由于图像不过是一个numpy数组。在此处签出OpenCV文档:docs