python - 使用 OpenCV python 绑定(bind)索引 channel 数据(numpy 数组)

标签 python opencv numpy

我正在尝试对从 OpenCV (2.3.1) Python 绑定(bind)生成的两个 numpy 数组进行 channel 比较。因此,我有一个形状为 (x, y) 的掩码(数组/图像/ channel ),我想将其与形状为 (x,y,3) 的 RGB 数组/图像的每个 channel 进行比较。

在我对 numpy 的切片进行了一半的研究后,我可以更接近我想要的东西:

channel = ndarr[...,i:i+1]     #where i is the channel I want

...但这返回一个形状为 (x,y,1) 的 ndarray,而不是我需要的 (x,y)。有没有一种优雅的方法可以在一次切片操作中完成此操作。如果做不到这一点,最简单的方法是什么?

最佳答案

不要使用切片,而是使用简单的索引:

channel = ndarr[..., i]

这实际上与普通 Python 列表的切片和索引相同。使用长度为 1 的切片会生成子列表,使用简单索引会生成返回的元素:

>>> a = [0, 1, 2, 3, 4]
>>> a[2:3]
[2]
>>> a[2]
2

关于python - 使用 OpenCV python 绑定(bind)索引 channel 数据(numpy 数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930679/

相关文章:

python - 对称矩阵的 LDL^T 分解的 Numpy 数组乘法

Python Numpy : Replace duplicate values with mean value

python - 构造函数未能接受输入参数

python - sessionmaker 错误

python - '类型错误 : Scalar value for argument 'color' is not numeric' when using opencv-python drawing a circle

c++ - OpenCV 预测中错误 : Assertion failed (samples. cols == var_count &&samples.type() == CV_32F)

android - 在 native 代码中使用 opencv 进行 Android 应用程序开发

python - pandas 构建逐行比较矩阵

Python-满足不同条件时如何从变量中选择

python - 如何克服 'ValueError: Wrong number of items passed 2, placement implies 1'错误?