使用 numpy 花式索引分配 arr

Assign arr with numpy fancy indexing

我真的希望这不是重复的,这可能是一个非常愚蠢的问题。抱歉 ;)

问题: 我有一个带有 values/classes 1 和 2 的灰度图像,我想 convert/map 将其转换为彩色图像,其中 1 等于黄色,2 等于蓝色。

import numpy as np
import cv2

result=cv2.imread("image.png", cv2.IMREAD_GRAYSCALE)

result[result==2]=[15,100,100]

result[result==1]=[130,255,255]

但是失败并出现错误 ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 1995594 output values where the mask is true

我认为我非常接近解决方案,但我不明白。 预先感谢您的帮助!

result 是一个 Numpy 数组并且是 typed,它的类型是一个整数,你试图给一个整数槽分配一个整数的三元组......不好。

您想要做的是创建一个空的彩色图像,其尺寸与 result 相同,并将请求的三元组分配给最后一个轴。

我还没有安装 cv2 但您可以查看以下代码以了解如何继续。

等同于你所做的,同样的错误

In [36]: import numpy as np                                                               
In [37]: a = np.random.randint(0,2,(2,4))                                                 
In [38]: a                                                                                
Out[38]: 
array([[1, 0, 0, 0],
       [0, 1, 0, 1]])
In [39]: a[a==1] = (1,2,3)                                                                  
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-24af4c8dbf5a> in <module>
----> 1 a[a==1] = (1,1)

ValueError: NumPy boolean array indexing assignment cannot assign 2 input values to the 3 output values where the mask is true

现在,分配一个 3D 数组并对其应用索引,默认分配给最后一个轴

In [40]: b = np.zeros((2,4,3))                                                            
In [41]: b[a==1] = (1,2,3)                                                                
In [42]: b                                                                                
Out[42]: 
array([[[1., 2., 3.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [1., 2., 3.],
        [0., 0., 0.],
        [1., 2., 3.]]])

我们有两个内部矩阵(对应a的两行),每个矩阵有四行(对应a的四列)最后列是RGB三元组你需要的。

我不知道数据在 cv2 图像中的确切排列方式,但我认为您必须进行微小的调整,如果有的话。

感谢@gboffi,我得到了答案。我想我希望有更多的 pythonic 方式来做这件事,但是没关系。

# Load in Image File
img=cv2.imread("imgfile", cv2.IMREAD_GRAYSCALE)
# Create new array with the shape of the original image
color=np.zeros((img.shape[0],result.shape[1],3))
# Note that opencv needs BGR and values from 0..1
color[result==1]=(0.84,117/225,2/225)
color[result==2]=(78/225,173/225,240/225)