2011-09-29 34 views
2

我正在處理有關通過抖動將灰度圖像轉換爲1位二進制圖像的任務。我正在嘗試一個簡單的4x4矩陣,它將使圖像比原始圖像大16倍。如何提高這種numpy迭代的效率?

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 

我讀了512 * 512的圖像im ndarray並做以下幾件事:

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-10s輸出和我想的im上面花了很多時間循環。在某些軟件中,同樣的操作通常是在閃存中完成的。那麼是否有可能提高效率?


UPDATE: @Ignacio巴斯克斯 - 艾布拉姆斯 我不跟探查用vert fimiliar :(我試過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的第10行。 py是第一行from numpy import *(之前的所有評論),這讓我非常困惑。

+0

你的分析器說什麼? –

回答

7

如果您使用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倍。

+0

im2未在隨後的計算中使用。錯字? – unutbu

+0

@unutbu:很好。固定。 – NPE