[SciPy-User] Numpy/Scipy: Avoiding nested loops to operate on matrix-valued images

Martin De Kauwe mdekauwe@gmail....
Tue Mar 27 18:20:13 CDT 2012


I didn't quite follow exactly what you were doing, but someone previously 
showed me how to avoid inner loops and so perhaps this will help?

Instead of...

tmp = np.arange(500000).reshape(1000,500)
nrows, ncols = tmp.shape[0], tmp.shape[1]
out = np.zeros((nrows, ncols))
for i in xrange(nrows):
    for j in xrange(ncols):
        out[i,j] = tmp[i,j] * 3.0

you might try...

tmp = np.arange(500000).reshape(1000,500)
nrows, ncols = tmp.shape[0], tmp.shape[1]
out = np.zeros((nrows, ncols))
r = np.arange(nrows)
c = np.arange(ncols)
out[r[:,None],c] = tmp[r[:,None],c] * 3.0

Assuming your arrays are large you would get a speed bump


On Thursday, March 15, 2012 7:59:28 PM UTC+11, tyldurd wrote:
>
> Hello,
>
> I am a beginner at python and numpy and I need to compute the matrix 
> logarithm for each "pixel" (i.e. x,y position) of a matrix-valued image of 
> dimension MxNx3x3. 3x3 is the dimensions of the matrix at each pixel.
>
> The function I have written so far is the following:
>
> def logm_img(im):
>     from scipy import linalg
>     dimx = im.shape[0]
>     dimy = im.shape[1]
>     res = zeros_like(im)
>     for x in range(dimx):
>         for y in range(dimy):
>             res[x, y, :, :] = linalg.logm(asmatrix(im[x,y,:,:]))
>     return res
>
> Is it ok? Is there a way to avoid the two nested loops ?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120327/04f17919/attachment-0001.html 


More information about the SciPy-User mailing list