numpy改变多维数组上条件的所有元素

用户名

如果该颜色的像素为蓝色,我想将元素更改为[0,0,0]。下面的代码可以工作,但是非常慢:

for row in range(w):
    for col in range(h):
        if np.array_equal(image[row][col], [255,0,0]):
            image[row][col] = (0,0,0)
        else:
            image[row][col] = (255,255,255)

我知道np.where适用于一维数组,但是如何使用该函数替换3维对象的内容?

比里科

自从您长大以来numpy.where,这就是使用以下方法的方式nupmy.where

import numpy as np

# Make an example image
image = np.random.randint(0, 255, (10, 10, 3))
image[2, 2, :] = [255, 0, 0]

# Define the color you're looking for
pattern = np.array([255, 0, 0])

# Make a mask to use with where
mask = (image == pattern).all(axis=2)
newshape = mask.shape + (1,)
mask = mask.reshape(newshape)

# Finish it off
image = np.where(mask, [0, 0, 0], [255, 255, 255])

在那里进行了重塑,以便numpy可以应用广播这里也有更多

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章