【问题标题】:Numpy: Avoiding nested loops to operate on matrix-valued imagesNumpy:避免嵌套循环对矩阵值图像进行操作
【发布时间】:2012-03-14 16:33:16
【问题描述】:

我是 python 和 numpy 的初学者,我需要计算维度为 NxMx3x3 的矩阵值图像的每个“像素”(即 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

没事吧? 有没有办法避免两个嵌套循环?

【问题讨论】:

    标签: python image matrix numpy nested-loops


    【解决方案1】:

    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]])
    

    【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2016-06-03
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多