[R] Asking Favor For the Script of Median Filter

David Winsemius dwinsemius at comcast.net
Mon Mar 28 00:30:48 CEST 2011


On Mar 27, 2011, at 1:07 PM, Mike Marchywka wrote:

> You obviously want to delegate inner loops to R packages that
> execute as native, hopefully optimized, code.
> Generally a google search that starts with "R CRAN" will help.
> In this case it looks like a few packages available,
>>
> http://www.google.com/search?sclient=psy&hl=en&q=R+cran+median+filter

Did you find any that include a 2D median filter? All the ones I  
looked at were for univariate data.

-- 
David.


>>
>> ----------------------------------------
>>> Date: Sun, 27 Mar 2011 07:56:11 -0700
>>> From: chuan_zl at hotmail.com
>>> To: r-help at r-project.org
>>> Subject: [R] Asking Favor For the Script of Median Filter
>>>
>>> Hello,everybody. My name is Chuan Zun Liang. I come from Malaysia.  
>>> I am just
>>> a beginner for R. Kindly to ask favor about median filter. The  
>>> problem I
>>> facing as below:
>>>
>>>
>>>> x<-matrix(sample(1:30,25),5,5)
>>>> x
>>> [,1] [,2] [,3] [,4] [,5]
>>> [1,] 7 8 30 29 13
>>> [2,] 4 6 12 5 9
>>> [3,] 25 3 22 14 24
>>> [4,] 2 15 26 23 19
>>> [5,] 28 18 10 11 20
>>>
>>> This is example original matrices of an image. I want apply with  
>>> median
>>> filter with window size 3X# to remove salt and pepper noise in my  
>>> matric.
>>> Here are the script I attend to writing.The script and output  
>>> shown as
>>> below:
>>>
>>>> MedFilter<-function(mat,sz)
>>> + {out<-matrix(0,nrow(mat),ncol(mat))
>>> + for(p in 1:(nrow(mat)-(sz-1)))
>>> + {for(q in 1:(ncol(mat)-(sz-1)))
>>> + {outrow<-median(as.vector(mat[p:(p+(sz-1)),q:(q+(sz-1))]))
>>> + out[(p+p+(sz-1))/2,(q+q+(sz-1))/2]<-outrow}}
>>> + out}
>>>
>>>> MedFilter(x,3)
>>> [,1] [,2] [,3] [,4] [,5]
>>> [1,] 0 0 0 0 0
>>> [2,] 0 8 12 14 0
>>> [3,] 0 12 14 19 0
>>> [4,] 0 18 15 20 0
>>> [5,] 0 0 0 0 0
>>>
>>> Example to getting value 8 and 12 as below:
>>>
>>> 7 8 30 8 30 29
>>> 4 6 12 (median=8) 6 12 5 (median=12)
>>> 25 3 22 3 22 14
>>>
>>> Even the script can give output. However, it is too slow. My image  
>>> size is
>>> 364*364. It is time consumption. Is it get other ways to improving  
>>> it?
>>>
>>> Best Wishes
>>> Chuan


-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list