2017-06-15 159 views
-1

我想根据条件替换数组中的值。这是我的数组看起来像根据Python中的条件替换数组中的值

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 
+0

你能提供更多的代码吗?你在使用一些第三方库吗? – Nurjan

+0

对于这个特定的操作,我已经尝试了上面的代码。不,我没有使用任何第三方库。 – Sameer

+1

那么'array'是什么?你有一个嵌套在另一个列表中的列表,而列表又嵌套在另一个列表中。这是对的吗? – Nurjan

回答

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à

相关问题