2015-10-21 129 views
-2

我有一個非常大的二維數組,並且想過濾掉一些小特徵。因此我想計算中心像素周圍區域的平均值。如果此值低於某個閾值,則將掩膜中的中心像素值設置爲零。有沒有現成的Python函數呢?爲了簡單起見,我們假設輸入是一個5乘9的整數條目數組,並且平均值應該在閾值7的2乘2掩碼上完成。計算蟒蛇中心像素周圍區域的平均值

+0

SciPy的和numpy的http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html#scipy.signal .convolve2d – lingxiao

回答

0

請嘗試以下代碼(閾值設置爲7,平均集到一個2×2區域):

Python 3.5.0 (default, Sep 27 2015, 12:06:50) 
[GCC 4.9.2] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import numpy as np 
>>> from scipy import signal 
>>> a = np.array([[2,3,2,3,5,7,3,6,1],[2,3,2,7,3,1,3,6,2],[345,1345,45,2,6,1,0,1,1],[2,3,2,456,5,7,3,1,1],[2,789,2,8,5,7,3,6,1]]) 
>>> b = np.array([[0.25,0.25],[0.25,0.25]]) 
>>> c = signal.convolve2d(a,b,boundary='symm',mode='same') 
>>> threshold = 7. 
>>> a[c<np.ones([5,9])*threshold]=0 
>>> a 
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    [ 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    [ 345, 1345, 45, 2, 0, 0, 0, 0, 0], 
    [ 2, 3, 2, 456, 5, 0, 0, 0, 0], 
    [ 0, 789, 2, 8, 5, 0, 0, 0, 0]]) 
>>>