对某个值的像素应用中值滤波器?

时间:2016-06-24 15:03:28

标签: python list numpy filter

我有一个带有int的矩阵。

如果任何邻居111,我需要将111替换为其直接4邻域的中位数,然后忽略它们。

例如: -

matrix = 1   2   3   4   5   6
         101 111 1   3   44  3
         111  3  4   4   5   6
          1    2 4   5   7   7

after replacing expected op 
1   2   3  4  5  6
101 2.5 1  3  44 3
3  3  4   4   5   6
1    2 4   5   7   7

我的代码非常糟糕,可能非常慢。任何帮助赞赏

def median_fil_mat(matrix):
    rows,columns= np.where(matrix==111)
    r,c=np.shape(matrix)
    for each_row in rows:
        for each_colmn in columns:
            if each_row==r-1:
                r1=[each_row-1]
            elif each_row>0 & each_row!=r-1:
                r1= [each_row-1,each_row+1]
            else:
                r1=[each_row+1]

            if each_colmn ==c-1:
                c1=[each_colmn-1]
            elif each_colmn >0 & each_colmn!=c-1:
                c1=[each_colmn-1,each_colmn+1]
            else:
                c1=[each_colmn+1]
            med_lis=list()
            for rr in r1:
                for cc in c1:
                    med_lis.append(matrix[rr,cc])
            med_lis=[x for x in med_lis if x!=111 ]
            matrix[each_row,each_colmn]= np.median(med_lis)
    return matrix

1 个答案:

答案 0 :(得分:0)

def func(array):
     if array[2]==111:
         return np.median(array[array!=111])
     else:
         return array[2]
fp = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
a = np.fromstring("""1   2   3   4   5   6
         101 111 1   3   44  3
         111  3  4   4   5   6
          1    2 4   5   7   7""", sep=" ").reshape((4, 6))
generic_filter(a, func, footprint=fp, mode='nearest')

返回

array([[   1. ,    2. ,    3. ,    4. ,    5. ,    6. ],
       [ 101. ,    2.5,    1. ,    3. ,   44. ,    3. ],
       [   3. ,    3. ,    4. ,    4. ,    5. ,    6. ],
       [   1. ,    2. ,    4. ,    5. ,    7. ,    7. ]])