使用Numpy将值映射到更高的维度

Xer*_*Xes 5 python opencv numpy

我正在尝试将颜色图应用于Numpy中的二维灰度图像(该图像由OpenCV加载/生成)。

我有256个条目的长列表,其中包含RGB值,这是我的颜色图:

cMap = [np.array([0, 0, 0], dtype=np.uint8),
        np.array([0, 1, 1], dtype=np.uint8),
        np.array([0, 0, 4], dtype=np.uint8),
        np.array([0, 0, 6], dtype=np.uint8),
        np.array([0, 1, 9], dtype=np.uint8),
        np.array([ 0,  0, 12], dtype=np.uint8),
        # Many more entries here
       ]
Run Code Online (Sandbox Code Playgroud)

输入灰度图像(形状(y,x,1))时,我想输出彩色图像(形状(y,x,3)),其中每个输入像素的灰度值用作索引,cMap以找到适合输出像素的颜色。到目前为止,我的尝试很小(受numpy数组中的值快速替换启发)看起来像这样:

colorImg = np.zeros(img.shape[:2] + (3,), dtype=np.uint8)

for k, v in enumerate(cMap):
    colorImg[img==k] = v
Run Code Online (Sandbox Code Playgroud)

这给了我错误ValueError: array is not broadcastable to correct shape。我想我已经缩小了问题的范围:我的切片导致一维布尔数组,其中每个都有一个条目imgcolorImg,但是条目的数量是的三倍img,因此布尔数组不会足够长。

我已经尝试过各种重塑和其他切片,但是我现在很困。我敢肯定有一种优雅的方法可以解决这个问题:-)

Aur*_*ius 1

您正在寻找的功能是numpy.take(). 唯一棘手的一点是指定axis = 0返回的图像具有正确的通道数。

colorImg = np.take(np.asarray(cMap), img, axis = 0)
Run Code Online (Sandbox Code Playgroud)