I have a 3d numpy array as follows:
(3L, 5L, 5L)
If one element in 3d positions, for instance, [150, 160, 170]
exists. How can I convert all of them into [0,0,0]
?
import numpy as np
a = np.ones((3,5,5))
a[0,2:4,2:4] = 150
a[0,0:1,0:1] = 150 #important!
a[1,2:4,2:4] = 160
a[2,2:4,2:4] = 170
print a
The expected result should be:
[[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]]
First I would convert into a stack of triples:
b = np.reshape(a.transpose(2, 1, 0), [25,3])
Then find the values you want:
idx = np.where((b == np.array([150, 160, 170])).all(axis=1))
And replace with whatever value you want:
b[idx] = 0
And finally convert back to the original shape:
c = np.reshape(b, [5, 5, 3]).transpose(2, 1, 0)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments