2013-09-28 93 views
3

Can I determine the number of channels in cv::Mat Opencv回答這個問題有關OpenCV 1的問題:您使用圖像的Mat.channels()方法。如何從OpenCV 2中的圖像獲取通道數量?

但是在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. 

互動的嘗試:

>>> 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. 

感謝您的幫助。

回答

19

使用img.shape

它爲您提供IMG在各個方向的形狀。即行數,二維數組的列數(灰度圖像)。對於3D陣列,它也會爲您提供多個通道。

所以,如果len(img.shape)給你兩個,它有一個單一的渠道。

如果len(img.shape)給你三個,第三個元素給你的通道數。

欲瞭解更多詳情,visit here

+0

正是我所需要的。謝謝! – LarsH

相關問題