簡體   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