0

My question is based upon this. Answers on that page solved the problem that i was facing at that time. My new question is -

Below code plots two square on my image. For each square, I want to count how many black color pixels are within it.

My original questions answers suggests that I can flatten a RGB using flat <- sum(x * c(0.2989, 0.5870, 0.1140)). In such case, I want to count pixels that have color value below 25.

I tried to leverage the answer suggested by the earlier post but couldnt figure out how to look within an extent.

library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
plot(extent(c(0,20,0,20)), lwd=2, col="red", add=TRUE)
plot(extent(c(21,35,0,10)), lwd=2, col="Green", add=TRUE)
Community
  • 1
  • 1
user2543622
  • 5,760
  • 25
  • 91
  • 159

1 Answers1

1
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
flat <- sum(x * c(0.2989, 0.5870, 0.1140))
plot(flat, col=gray(seq(0,1,0.1)))
e1 <- extent(c(0,20,0,20))
e2 <- extent(c(21,35,0,10))
plot(e1, col='red', add=TRUE)
plot(e2, col='blue', add=TRUE)


# I am using a cut-off of 100 to get some cells below that threshold.
sum(extract(flat, e1) < 100)
sum(extract(flat, e2) < 100)

# for _very_ large files/extents this could be done to avoid RAM limitations
x <- crop(flat, e2)
y <- reclassify(x, matrix(c(-Inf, 100, 1, 100, Inf, 0), byrow=TRUE)) 
freq(y, value=1)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63