2

I want to vectorize the process of adding a 2d array to every 2d array inside a 3d array.

I imported an image file using image from matplotlib

data = image.imread('test.jpg')

Then I tried to add the average of each RGB array to another array of the same shape as data

data2 = np.zeros_like(data)
data3 = np.average(data, axis=2)
for i in range(len(data2[0,0,:])):
    data2[:,:,i] = data3

I just want to vectorize the above 2 line code to one line

1 Answer 1

1

Convert data3 to the result datatype and then broadcast/repeat after extending to 3D with np.newaxis/None -

b = data3.astype(data.dtype)
data2_out = np.broadcast_to(b[...,None], data.shape)

The output would simply be a view into b and hence we are gaining memory-efficiency there.

If you need an output with its own memory space, we can force the copy with data2_out.copy() or use np.repeat, like so -

np.repeat(b[...,None],data.shape[2],axis=2)

If you already have the output array data2 initialized and just want to assign into it, we can do so with extending data3 to 3D and this might more intuitive in some scenarios too, like so -

data2[:] = data3[...,None]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that did the job
What does the [...,None] indexing mean? Or can you link the docs which explain this type of indexing.
@PrashantGaikwad Added.
Oh sorry, I am new here so I didn't know I needed to do that.

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.