Skip to main content
 首页 » 编程设计

python之根据条件更改多维 numpy 数组值

2025年05月04日13dflying

我将 RGB 图像存储为 numpy 数组。我有一个颜色数组,我将在图像中搜索这些颜色并将这些 RGB 值替换为相同的标量值。其余不匹配的 RGB 值应简单地替换为 0。

我正在搜索的颜色可能如下所示,

colors = [] 
colors.append((69, 0, 9, 17)) 
colors.append((196, 127, 128,1)) 
colors.append((199, 5, 126, 19)) 
colors.append((55, 127, 126, 4)) 
colors.append((0, 127, 29, 2)) 
colors.append((68, 6, 124, 18)) 

每种颜色的第 4 个值是将替换相应 RGB 值的值。

我尝试使用 np.asin 但它不搜索数组。它只搜索标量。现在我正在使用 for 循环,但它非常慢。

for i in range(image.shape[0]): 
   for j in range(image.shape[1]): 
      match = -1 
      for k in range(len(colors)):   
         match = k        
         for l in range(3): 
            if image[i,j,l] != colors[k][l]: 
               match=-1 
               break 
         if match >=0 : 
            break 
 
      val = [0,0,0] 
      if match >= 0: 
         val = [colors[match][3],colors[match][3],colors[match][3]] 
      for l in range(3): 
         image[i,j,l] = val[l] 

任何有效的方法将不胜感激。

请您参考如下方法:

@加布里埃尔中号

一个很好的方法。但我认为应该是

for r,g,b, replace in colors: 
 
    colors_match = np.where( np.all([image[:,:,0] == r, image[:,:,1] == g, image[:,:,2] == b], axis=0)) 
    image[colors_match] = replace 
    print(colors_match) 

或者更简单的说

for r,g,b, replace in colors: 
 
    colors_match = np.all([image[:,:,0] == r, image[:,:,1] == g, image[:,:,2] == b], axis=0) 
    image[colors_match] = replace 
    print(colors_match) 

已编辑

要替换未转换的值,可以选择将转换历史记录保存在另一个数组中。

converted = np.zeros((image.shape[0], image.shape[1]), dtype=bool) 
for r,g,b, replace in colors: 
 
    colors_match = np.all([image[:,:,0] == r, image[:,:,1] == g, image[:,:,2] == b], axis=0) 
    image[colors_match] = replace 
    converted[colors_match] = True 
image[~converted] = 0