FriendofaFriend
FriendofaFriend

Reputation: 11

Numpy: faster array access

I've written a little python program where in one function I iterate over a Numpy array of an image. Almost the whole runtime happens in one small portion where I access the individual pixels (they have RGB values). It looks something like this:

arr #800x800 pixel
for x in range(height):
    for y in range(width):
        temp = [0,0,0]
        #prepare some stuff

        tmp[0]+=arr.item(x, y, 0) # This takes
        tmp[1]+=arr.item(x, y, 1) # almost all
        tmp[2]+=arr.item(x, y, 2) # the runtime

        #do some stuff with the values

Is there a faster way to access the pixel values?

Upvotes: 0

Views: 162

Answers (2)

Sadaf Shafi
Sadaf Shafi

Reputation: 1438

Use vectorisation, i.e. by matrices' operations, not by each element,like adding whole matrix A+B (where both A and B are 2 matrices on same dimensions). What you are doing is, you're adding each element of A with that of B, one by one, which makes it slower.

Upvotes: 1

Rob
Rob

Reputation: 3513

Use the sum method:

tmp = arr.sum((0, 1))

You should never have to write an explicit loop over numpy array values. Almost always, there is a vectorized solution that runs much faster.

Upvotes: 2

Related Questions