【问题标题】:How to improve efficiency in this numpy iterating?如何提高这个 numpy 迭代的效率?
【发布时间】:2011-09-29 18:13:30
【问题描述】:

我正在处理一项关于通过抖动将灰度图像转换为 1 位二进制图像的任务。我正在尝试一个简单的 4x4 矩阵,它将使图像比原始图像大 16 倍。

dithering_matrix = array([[ 0,  8,  2, 10],
                          [12,  4, 14,  6],
                          [ 3, 11,  1,  9],
                          [15,  7, 13,  5]], dtype=uint8)
split_num = dithering_matrix.size + 1

我向im ndarray 读取了一张 512x512 的图像并做了以下事情:

output = list()
for row in im:
    row_output = list()
    for pixel in row:
        pixel_matrix = ((pixel / (256 / split_num)) > dithering_matrix) * 255
        row_output.append(pixel_matrix)
    output.append( hstack( tuple(row_output) ) )
output_matrix = vstack( tuple(output) )

我发现输出需要 8-10 秒,我认为上面的 im 循环花费了很多时间。在某些软件中,相同的操作通常在 Flash 中完成。那么有没有可能提高效率呢?


更新: @Ignacio Vazquez-Abrams 我对 profiler 不是很熟悉:( 我试过 cProfile,结果很奇怪。

         1852971 function calls (1852778 primitive calls) in 9.127 seconds

   Ordered by: internal time
   List reduced from 561 to 20 due to restriction <20>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    6.404    6.404    9.128    9.128 a1.1.py:10(<module>)
      513    0.778    0.002    0.778    0.002 {numpy.core.multiarray.concatenate
}
   262144    0.616    0.000    1.243    0.000 D:\Python27\lib\site-packages\nump
y\core\shape_base.py:6(atleast_1d)
   262696    0.260    0.000    0.261    0.000 {numpy.core.multiarray.array}
   262656    0.228    0.000    0.487    0.000 D:\Python27\lib\site-packages\nump
y\core\numeric.py:237(asanyarray)
      515    0.174    0.000    1.419    0.003 {map}
   527019    0.145    0.000    0.145    0.000 {method 'append' of 'list' objects
}

a1.1.py 的第 10 行是第一行 from numpy import *(之前的所有 cmets),这让我很困惑。

【问题讨论】:

    标签: python image-processing numpy python-imaging-library


    【解决方案1】:

    如果您使用Kronecker product 将每个像素转换为 4x4 子矩阵,您就可以摆脱 Python 循环:

    im2 = np.kron(im, np.ones((4,4)))
    dm2 = np.tile(dithering_matrix,(512,512))
    out2 = ((im2 / (256 / split_num)) > dm2) * 255
    

    在我的机器上,这比你的版本快大约 20 倍。

    【讨论】:

    • im2 不用于后续计算。错别字?
    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多