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

Dan Lussier dtlussier@gmail....
Thu Mar 15 15:23:49 CDT 2012

Have you tried numpy.frompyfunc?


With this approach you may be able create a function which acts elementwise over your array to compute the matrix logarithm at each entry using Numpy's ufuncs.  This would avoid the explicit iteration over the array using the for loops.

As a rough outline try:

from scipy import linalg
import numpy as np

# Assume im is the container array containing a 3x3 matrix at each pixel.

# Composite function so get matrix log of array A as a matrix in one step
def log_matrix(A):
    return linalg.logm(np.asmatrix(A))

# Creating function to operate over container array.  Takes one argument and returns the result.
log_ufunc = np.frompyfunc(log_matrix, 1, 1)

# Using log_ufunc on container array, im
res = log_ufunc(im)


On 2012-03-15, at 1:59 AM, 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 ?
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120315/92ac84db/attachment-0001.html 

More information about the SciPy-User mailing list