4

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 2

7

Maybe:

>>> m = np.zeros((2,2,3))
>>> m[:] = [10,20,3]
>>> m
array([[[ 10.,  20.,   3.],
        [ 10.,  20.,   3.]],

       [[ 10.,  20.,   3.],
        [ 10.,  20.,   3.]]])
>>> m[0,0]
array([ 10.,  20.,   3.])
>>> m[0,1]
array([ 10.,  20.,   3.])
>>> m[1,0]
array([ 10.,  20.,   3.])
>>> m[1,1]
array([ 10.,  20.,   3.])
Sign up to request clarification or add additional context in comments.

Comments

3

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

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.