I have a 3D numpy array representing an RGB image. I would like to fill the whole image with a particular RGB value. numpy.fill only takes a scalar as an argument-- is there a cleaner way than looping to assign the same third-dimension RGB triplet to each point in the 2d grid?
2 Answers
Initialize the array
In [2]: m = numpy.zeros((2,2,3))
In [3]: m
Out[3]:
array([[[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.]]])
Fill out each (x, y) element with an (r, g, b) triplet
In [22]: m[...] = (11, 22, 33)
In [23]: m
Out[23]:
array([[[ 11., 22., 33.],
[ 11., 22., 33.]],
[[ 11., 22., 33.],
[ 11., 22., 33.]]])
Is this what you want to do?
Also, if you want to set, say, only green component
In [25]: m[..., 0] = 77
In [26]: m
Out[26]:
array([[[ 77., 22., 33.],
[ 77., 22., 33.]],
[[ 77., 22., 33.],
[ 77., 22., 33.]]])
2 Comments
trueter
I want to basically do this, but instead of
[11, 22, 33] I want random numbers generated in a specific way (here: a function with random noise on top). If i'd do m[...] = np.random(3), i'd always have the same three random numbers. If I'd do m = np.random((2, 2, 3)), i'd have to little control over how the random numbers are generated. Of course, I don't want for-loops. Do you have an idea?Dima Tisnek
You can assign an array too, e.g.
m[..., 0] = [1, 2, 3, 4] it has to be correct size and data is up to you.