Python 如何在 OpenCV 2 中从图像中获取通道数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19062875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get the number of channels from an image, in OpenCV 2?
提问by LarsH
The answers at Can I determine the number of channels in cv::Mat Opencvanswer this question for OpenCV 1: you use the Mat.channels()
method of the image.
在这些问题的答案我能决定的通道数在简历::垫opencv的回答这个问题了OpenCV的1:使用Mat.channels()
图像的方法。
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.
但是在 cv2(我使用的是 2.4.6)中,我拥有的图像数据结构没有channels()
方法。我正在使用 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.
谢谢你的帮助。
采纳答案by Abid Rahman K
Use img.shape
用 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.
它为您提供全方位的 img 形状。即二维数组(灰度图像)的行数、列数。对于 3D 阵列,它还为您提供通道数。
So if len(img.shape)
gives you two, it has a single channel.
所以如果len(img.shape)
给你两个,它只有一个通道。
If len(img.shape)
gives you three, third element gives you number of channels.
如果len(img.shape)
给你三个,第三个元素给你通道数。
For more details, visit here
欲了解更多详情,请访问这里
回答by abhiTronix
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:
使用image.ndim
Source,将为您提供正确数量的频道,如下所示:
if image.ndim == 2:
channels = 1 #single (grayscale)
if image.ndim == 3:
channels = image.shape[-1]
Since a imageis a nothing but a numpyarray. Checkout OpenCV docs here: docs
因为图像只不过是一个numpy数组。在此处查看 OpenCV 文档:docs
回答by songofhawk
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.
据我所知,你应该使用 image.shape[2] 来确定通道数,而不是 len(img.shape),后者给出了数组的尺寸。