Convert multi-dimensional Numpy array to 2-dimensional array based on color values

前端 未结 3 1629
猫巷女王i
猫巷女王i 2021-01-23 04:21

I have an image which is read as a uint8 array with the shape (512,512,3). Now I would like to convert this array to a uint8 array of shape (512,512,1)

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-23 05:22

    One way: separately create the boolean arrays with True values where the input's pixel value matches one of the palette values, and then use arithmetic to combine them. Thus:

    palette = [
        [0, 0, 0], 
        [0, 0, 255], 
        [255, 0, 0],
        # etc.
    ]
    
    def palettized(data, palette):
        # Initialize result array
        shape = list(data.shape)
        shape[-1] = 1
        result = np.zeros(shape)
        # Loop and add each palette index component.
        for value, colour in enumerate(palette, 1):
            result += (data == colour).all(axis=2) * value
        return result
    

提交回复
热议问题