0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

or even arr.sum((0,1))
1

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.

Comments

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.