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?
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.
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")
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.
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)
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)
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With