繁体   English   中英

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

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

Can Mat.channels() the number of channels in 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.

互动尝试:

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

谢谢你的帮助。

使用img.shape

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

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

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

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

我有点迟了但还有另外一个简单的方法:

使用image.ndim 来源 ,将提供正确数量的频道,如下所示:


if image.ndim == 2:

    channels = 1 #single (grayscale)

if image.ndim == 3:

    channels = image.shape[-1]

因为图像只是一个numpy数组。 在这里结帐OpenCV文档: docs

据我所知,你应该使用image.shape [2]来确定通道的数量,而不是len(img.shape),后者给出了数组的尺寸。

我想在这里添加一个使用PIL库的自包含脚本和另一个使用cv2库的cv2

CV2 库脚本

import cv2
import numpy as np

img = cv2.imread("full_path_to_image")

img_np = np.asarray(img)

print("img_np.shape: ", img_np.shape)

最后打印的最后一列将显示通道数,例如

img_np.shape: (1200, 1920, 4)

PIL 库脚本

from PIL import Image
import numpy as np

img = Image.imread("full_path_to_image")

img_np = np.asarray(img)

print("img_np.shape: ", img_np.shape)

最后打印的最后一列将显示通道数,例如

img_np.shape: (1200, 1920, 4)

注意:从上面的脚本中,您可能会想(我曾经)使用img_np.shape[2]来检索通道数。 但是,如果您的图像包含 1 个通道(例如,灰度),则该行会给您带来问题( IndexError: tuple index out of range )。 取而代之的是一个简单的形状打印(就像我在我的脚本中所做的那样)你会得到这样的东西

img_np.shape: (1200, 1920)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM