Numpy在多维数组上更改条件上的所有元素

时间:2014-12-09 02:03:38

标签: python image-processing numpy scipy

如果该颜色的像素为蓝色,我想将元素更改为[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维对象的东西呢?

2 个答案:

答案 0 :(得分: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将适用broadcastingmore here also

答案 1 :(得分:0)

您可以做的最简单的事情就是将要设置的元素乘以零的零数组。三维数组的此数组属性的示例如下所示。

x = array([ [ [ 1,2,3 ] , [ 2 , 3 , 4 ] ] , [ [ 1, 2, 3, ] , [ 2 , 3 , 4 ] ] , [ [ 1,2,3 ] , [ 2 , 3 , 4 ] ] , [ [ 1, 2, 3, ] , [ 2 , 3 , 4 ] ] ])

print x

if 1:
    x[0] = x[0] * 0

print x

这将产生两个打印输出:

[[[1 2 3]   [2 3 4]]

[[1 2 3]   [2 3 4]] ......

[[[0 0 0]   [0 0 0]]

[[1 2 3]  [2 3 4]] ......

此方法适用于示例中的image [row]和image [row] [column]。您重新编写的示例如下所示:

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