These are alternatives to EBImage::filter2() and EBImage::medianFilter() for smooth and median filtering respectively. These functions have many options for dealing with NA values which EBImage's functions lack.

median_filter(mat, size = 1L, na_rm = FALSE, na_count = FALSE)

smooth_filter(mat, size = 1L, na_rm = FALSE, na_count = FALSE)

Arguments

mat

A matrix (representing an image).

size

An integer; the median filter radius.

na_rm

Should NAs be ignored?

na_count

If this is TRUE, in each median calculation, if the majority of arguments are NAs, NA is returned but if the NAs are in the minority, they are ignored as in median(x, na.rm = TRUE).

Value

A matrix (the median filtered image).

Details

The behavior at image boundaries is such as the source image has been padded with pixels whose values equal the nearest border pixel value.

Examples

m <- matrix(1:9, nrow = 3) m[2:3, 2:3] <- NA print(m)
#> [,1] [,2] [,3] #> [1,] 1 4 7 #> [2,] 2 NA NA #> [3,] 3 NA NA
median_filter(m)
#> [,1] [,2] [,3] #> [1,] NA NA NA #> [2,] NA NA NA #> [3,] NA NA NA
median_filter(m, na_rm = TRUE)
#> [,1] [,2] [,3] #> [1,] 1.5 4 7 #> [2,] 2.0 3 7 #> [3,] 3.0 3 NA
median_filter(m, na_count = TRUE)
#> [,1] [,2] [,3] #> [1,] 1.5 4 7 #> [2,] 2.0 3 NA #> [3,] 3.0 NA NA
smooth_filter(m)
#> [,1] [,2] [,3] #> [1,] NA NA NA #> [2,] NA NA NA #> [3,] NA NA NA
smooth_filter(m, na_rm = TRUE)
#> [,1] [,2] [,3] #> [1,] 2.000000 3.714286 6 #> [2,] 2.285714 3.400000 6 #> [3,] 2.666667 2.666667 NaN
smooth_filter(m, na_count = TRUE)
#> [,1] [,2] [,3] #> [1,] 2.000000 3.714286 6 #> [2,] 2.285714 3.400000 NA #> [3,] 2.666667 NA NA