Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image smoothing in R

How can I smooth this picture in R, so that only two peaks remain?

If this would be 1d data, I would do a running mean or fit a regression function to it. But I did not find very specific information about applying these methods on a 2d matrix. For example I tried to use filter() from the stats package.

I also thought about kriging, but this is more about interpolation, is it?

spectrogram

like image 412
nnn Avatar asked Jun 10 '13 11:06

nnn


3 Answers

The package spatstat holds a function blur() that applicates a gaussian blur. This smothes the picture in a way, that most of the noise disappears and the two main peaks are clearly distinctable.

The effect can be seen in the following picture and is quite remarkable, especially in the 3d plot.

effects of blurring

The code to generate the picture was:

library(jpeg)
library(fields)
library(spatstat)

picture <- readJPEG("~/Downloads/spectrogram.png.jpeg")
picture2 <- as.matrix(blur(as.im(picture), sigma=6))

layout(matrix(c(1:4), nrow=2))
image.plot(picture, col=gray.colors(50), main="original image", asp=1)
image.plot(picture2, col=gray.colors(50), main="blurred with sigma = 6", asp=1)
drape.plot(1:nrow(picture), 1:ncol(picture), picture, border=NA, theta=0, phi=45, main="original spectrogram")
drape.plot(1:nrow(picture), 1:ncol(picture), picture2, border=NA, theta=0, phi=45, main="blurred with sigma = 6")
like image 174
nnn Avatar answered Nov 14 '22 12:11

nnn


I think you should have a look at the focal function in the raster package. For example (copied from the raster documentation):

r <- raster(ncols=36, nrows=18, xmn=0)
r[] <- runif(ncell(r))
# 3x3 mean filter
r3 <- focal(r, w=matrix(1/9,nrow=3,ncol=3))

The documentation include more details.

like image 24
Paul Hiemstra Avatar answered Nov 14 '22 12:11

Paul Hiemstra


You definitely want to take a look at the EBImage package. There are multiple functions for smoothing your image.

For example, a median filter:

# Load EBImage up
require(EBImage)
# Read in your image
im = readImage('/path/to/your/image')
# Apply a median filter with window size of 7
im.med = medianFilter(im, size=7)
# Display image
display(im.med)

Median filter applied with 7x7

or you could try a gaussian blur:

# Apply a gaussian blur with sigma=4
im.gaus = gblur(im, sigma=4)
# Display image
display(im.gaus)

enter image description here

Hope this helps!

like image 8
Omar Wagih Avatar answered Nov 14 '22 11:11

Omar Wagih