Bryan Alemán
Bryan Alemán

Reputation: 37

How to quantify the number of pixels surrounded by an specific pixel value in r?

we are trying to estimate the leaf area index of a plant, but our pictures (rasters) have pixels out of the screen area. We need to know how to quantify the number of pixels of the leaves included only in the screen area without the noise of the borders (out of the screen). For that we assigned a value of 8 to the screen area that is surrounding the leaves. We are using the raster package for it. Thanks in advance for your help

here is an example file

Upvotes: 0

Views: 194

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47401

That is a rather complicated problem. Below is a start of a possible approach. The real solution is to not put the leaves so close to the edge of the screen, and only take a picture of the screen area.

library(raster)
p <- raster("prueba.tif")
p <- reclassify(p, cbind(8, NA))
m <- as.matrix(p)
nc <- ncol(m)
c1 <- 1:200
c2 <- (nc-200):nc
nr <- nrow(m)
r1 <- 1:200
r2 <- (nr-200):nr

for (r in 1:nr) {
    i <- which(is.na(m[r,c1]))[1]
    if (!is.na(i)) m[r,1:i] <- NA
    i <- nc - which(is.na(rev(m[r,c2])))[1]
    if (!is.na(i)) m[r,i:nc] <- NA
}
for (c in 1:nc) {
    i <- which(is.na(m[r1,c]))[1]
    if (!is.na(i)) m[1:i, c] <- NA
    i <- nr - which(is.na(rev(m[r2,c])))[1]
    if (!is.na(i)) m[i:nr, c] <- NA
}

x <- setValues(p, as.vector(t(m)))

Upvotes: 1

Related Questions