简体   繁体   中英

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?

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.

Use vectorisation, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM