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

标签 python arrays numpy indexing python-3.6

我将 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

关于python - 根据条件更改多维 numpy 数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52982356/

相关文章:

python - 类型错误 : '>' not supported between instances of 'int' and 'str'

javascript - JavaScript 中奇怪的数组行为

python - 使用 C API 创建自定义类对象的 numpy 数组

python - 如何在 Mac OSX 10.9 上为 python 3.3.5 安装 NumPy

Python Numpy Array 邻居的geht值

python - OpenCV cv2.moments将所有时刻返回零

python - 为什么我在 OS X 上使用 Python 的 SysLogHandler 在 syslog 消息中得到一个虚假的 ']' 字符?

python - docker-compose “/usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: ”时出错

c# - Unity Array of Struct : When setting a variable of one of the array subscripts, 它为所有这些设置它

php - MYSQL中如何逐行选择并设置为数组?