从 RBG 数组创建数组

问题描述 投票:0回答:0

我在 python [c, x, y] 中有一个栅格,其中 C 具有三个值,使用 0 到 255 之间的数字组合,例如 ((0, 255, 0) 表示绿色以及 X 和 Y 值是光栅的行和列值。我需要创建一个带有颜色图的 python 脚本,它将一个信号编号分配给 C 点并替换 RBG 值,例如,如果颜色为红色,则新的 C 值变为如果蓝色比 c 值变为 3,则为 1。但是我需要考虑 RBG 值的细微变化,例如 (111, 143, 111) 仍然是绿色,但对于红色和蓝色也是如此。

我试图为每个购买的 vaule 创建一个范围,但由于某种原因它不起作用。有什么想法吗?

def load_FOA_raster(patchfolder, string='FOA'):
    files = os.listdir(patchfolder) 
    tiffs =  [f for f in files if f.endswith('.JP2') and f.startswith(string)][0]
    FOA = gdal.Open(patchfolder+tiffs)

    raster = FOA.ReadAsArray()
    
    # Create a lookup table for the color values
    color_map = {
        (255, 0, 0): 1,  # Red
        ((140, 130, 130),(255, 0, 0)): 1,

        (0, 255, 0): 2,  # Green
        ((130, 140, 130),(0, 255, 0)): 2,

        (0, 0, 255): 3,  # Blue
        ((130, 130, 140),(0, 0, 255)): 3,

        (0,0,0): 4, #black
    }
    
    
    # Create the output filename
    foa_raster = np.zeros((1, raster.shape[1], raster.shape[2]))
    
    for i in range(raster.shape[1]):
        for j in range(raster.shape[2]):
            # Get the RGB values for the current pixel
            pixel_color = tuple(raster[:, i, j])

            # Check if the pixel color is in the color map
            if pixel_color in color_map:
                # If so, set the pixel value to the corresponding number
                foa_raster[0, i, j] = color_map[pixel_color]
            else:
                # If not, set the pixel value to 0 (or some other default value)
                foa_raster[0, i, j] = 0

    return foa_raster

我的 for 循环正在运行。它适用于黑色像素并在正确的位置返回 4 但对于其他颜色它返回 0 因为我的其他声明

python dataframe rgb
© www.soinside.com 2019 - 2024. All rights reserved.