代码之家  ›  专栏  ›  技术社区  ›  chaimp

我如何使用numpy来合成N层灰度图像数据,每层都在RGB空间中着色?

  •  0
  • chaimp  · 技术社区  · 7 年前

    考虑一下这个有三种颜色(红色、蓝色和绿色)的简单示例:

    layers = {
      'red': np.random.rand(100, 100),
      'blu': np.random.rand(100, 100),
      'grn': np.random.rand(100, 100)
    }
    
    # Express composite as 3-channel RGB data
    composite_arr = np.zeros(shape=(100, 100, 3))
    
    # For each channel red, blue, and green, insert the data for the corresponding layer
    composite_arr[:, :, 0] = layers['red']
    composite_arr[:, :, 1] = layers['blu']
    composite_arr[:, :, 2] = layers['grn']
    
    # Finally, output the image expressed in RGB
    composite_img = Image.fromarray(np.array(composite_arr * 255, dtype=np.uint8), mode="RGB")
    composite_img.save('test.png')
    

    现在,让我们用一个包含四个层的列表来代替上面的示例:

    layers = [
        np.random.rand(100, 100),
        np.random.rand(100, 100),
        np.random.rand(100, 100),
        np.random.rand(100, 100)
    }
    

    colors = {
        (1, 0, 0),
        (0, 1, 1),
        (0, 0, 1),
        (1, 1, 0)
    }
    

    在上面的例子中,我如何同样地为四个层构建一个组合?

    那么,对于任意数量的图层和颜色呢?

    我正在寻找一些我可以顺序应用的通用表达式 composite_arr 这将更新任何数量的层和颜色。

    或者,如果可以使用 PIL 或者类似的库来给每一层上色并应用一些复合函数,请建议如何做到这一点。


    编辑:为了澄清,我想用RGB空间来表达最终结果。因此,任何数量的层都应该适合于此(以下是上面的100x100图像示例):

    composite_arr = np.zeros(shape=(100, 100, 3))
    
    0 回复  |  直到 7 年前