A faster way to scroll each pixel of an image in Python?

I need to cut through each pixel of a 2560x2160 2D memory array (image). A simplified version of my problem is this:

import time import numpy as np t = time.clock() limit = 9000 for (x,y), pixel in np.ndenumerate(image): if( pixel > limit ) pass tt = time.clock() print tt-t 

It will take about 30 seconds to shut down on my computer. (Core i7, 8 GB RAM) Is ​​there a faster way to execute this loop with an internal "if" expression? I'm only interested in pixels above a certain limit, but I need their (x, y) indices and value.

+8
python loops numpy time image
source share
2 answers

Use the logical matrix:

 x, y = (image > limit).nonzero() vals = image[x, y] 
+13
source share

First try using vectorization calculation:

 i, j = np.where(image > limit) 

If your problem cannot be solved by vectorizing the calculation, you can speed up the for loop like:

 for i in xrange(image.shape[0]): for j in xrange(image.shape[1]): pixel = image.item(i, j) if pixel > limit: pass 

or

 from itertools import product h, w = image.shape for pos in product(range(h), range(w)): pixel = image.item(pos) if pixel > limit: pass 

The numpy.ndenumerate statement is slow, using the regular for loop and getting the value from the array using the item method, you can speed up the loop 4 times.

If you need a higher speed, try using Cython, it will make your code as fast as C code.

+6
source share

All Articles