Numpy:避免嵌套循环对矩阵值图像进行操作

时间:2012-03-14 16:33:17

标签: python image matrix numpy nested-loops

我是python和numpy的初学者,我需要为每个"像素"计算矩阵对数。尺寸为N×M×3×3的矩阵值图像(即x,y位置)。 3x3是每个像素的矩阵尺寸。

到目前为止我写的函数如下:

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

可以吗? 有没有办法避免两个嵌套循环?

1 个答案:

答案 0 :(得分:-2)

Numpy可以做到这一点。只需致电numpy.log

>>> import numpy
>>> a = numpy.array(range(100)).reshape(10, 10)
>>> b = numpy.log(a)
__main__:1: RuntimeWarning: divide by zero encountered in log
>>> b
array([[       -inf,  0.        ,  0.69314718,  1.09861229,  1.38629436,
         1.60943791,  1.79175947,  1.94591015,  2.07944154,  2.19722458],
       [ 2.30258509,  2.39789527,  2.48490665,  2.56494936,  2.63905733,
         2.7080502 ,  2.77258872,  2.83321334,  2.89037176,  2.94443898],
       [ 2.99573227,  3.04452244,  3.09104245,  3.13549422,  3.17805383,
         3.21887582,  3.25809654,  3.29583687,  3.33220451,  3.36729583],
       [ 3.40119738,  3.4339872 ,  3.4657359 ,  3.49650756,  3.52636052,
         3.55534806,  3.58351894,  3.61091791,  3.63758616,  3.66356165],
       [ 3.68887945,  3.71357207,  3.73766962,  3.76120012,  3.78418963,
         3.80666249,  3.8286414 ,  3.8501476 ,  3.87120101,  3.8918203 ],
       [ 3.91202301,  3.93182563,  3.95124372,  3.97029191,  3.98898405,
         4.00733319,  4.02535169,  4.04305127,  4.06044301,  4.07753744],
       [ 4.09434456,  4.11087386,  4.12713439,  4.14313473,  4.15888308,
         4.17438727,  4.18965474,  4.20469262,  4.21950771,  4.2341065 ],
       [ 4.24849524,  4.26267988,  4.27666612,  4.29045944,  4.30406509,
         4.31748811,  4.33073334,  4.34380542,  4.35670883,  4.36944785],
       [ 4.38202663,  4.39444915,  4.40671925,  4.41884061,  4.4308168 ,
         4.44265126,  4.4543473 ,  4.46590812,  4.47733681,  4.48863637],
       [ 4.49980967,  4.51085951,  4.52178858,  4.53259949,  4.54329478,
         4.55387689,  4.56434819,  4.57471098,  4.58496748,  4.59511985]])