根据python中的条件替换数组中的值

时间:2017-06-15 11:04:07

标签: python arrays numpy

我想根据条件替换数组中的值。这就是我的数组的样子

array([[[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [ 255, 255, 255],
        [  0,   0,   0],
        [  0,   0,   0],
        [255,  255, 255],
        [255,  255, 255]]])

我想用[255,255,255]在[255,255,255]和[255,255,255]之间迭代替换所有值         我的输出应该如下:

array([[[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [ 255, 255, 255],
        [ 255, 255, 255],
        [ 255, 255, 255],
        [255,  255, 255],
        [255,  255, 255]]])

我试过这段代码

img_rgb[img_rgb >= 255 & img_rgb <= 255] = 255

1 个答案:

答案 0 :(得分:0)

我正在为您提供一种使用numpy解决问题的方法:

import numpy as np

#create a matrix similar to yours:
img = np.zeros((100,100))
replace_line = np.transpose(np.random.randint(100,size=100))
#replace random lines to have a shape like yours
img[40,:] = replace_line
img[87,:] = replace_line

"""
now img should be like that:
 0 0 0 0 0 ...
 .
 .
 x y z ..
 0 0 0 0 0 ...
 0 0 0 0 0 ...
 x y z ..
 .
 .
"""

#now the actual replacement
#with the condition I take the indexes to start the replacement
#I assume that the rows are always equal so I can take the first column
#as representative of the entire row

non_zero_indexes = img[:,0] >0
non_zero_indexes = np.nonzero(non_zero_indexes)[0]

img[non_zero_indexes[0]:non_zero_indexes[1],:] = replace_line

Etvoilà