Arihant
Arihant

Reputation: 589

Auto Thresholding on R raster object

Is there an auto-thresholding algorithm such as 'Otsu' available for R raster object. I have tried using the "authothresholder" package, however it is inefficient as it works on matrix and doesn't work with 32 bit tif files. I am trying to convert an NDWI image into a binary layer.

Upvotes: 0

Views: 1776

Answers (1)

Eric
Eric

Reputation: 3473

This is implemented in the EBImage package available from Bioconductor. Here is an example use:

library(EBImage)
img <- readImage(system.file("images", "sample.png", package = "EBImage"))
thr <- img > otsu(img)
display(img)
display(thr)

The implementation is essentially the following (pulled from the function definition of EBImage::otsu i.e. not my work), so you should be able to adapt the following for whatever image analysis toolset you are using:

img  # assuming img is a numeric matrix or vector

range = c(0, 1)  # assuming values in the matrix range from 0 to 1
levels = 256L
breaks = seq(range[1], range[2], length.out = levels + 1)

h = hist.default(img, breaks = breaks, plot = FALSE)
counts = as.double(h$counts)
mids = as.double(h$mids)
len = length(counts)
w1 = cumsum(counts)
w2 = w1[len] + counts - w1
cm = counts * mids
m1 = cumsum(cm)
m2 = m1[len] + cm - m1
var = w1 * w2 * (m2/w2 - m1/w1)^2
maxi = which(var == max(var, na.rm = TRUE))
(mids[maxi[1]] + mids[maxi[length(maxi)]])/2

Upvotes: 3

Related Questions