Home > Software design >  Counting pixels of same value in R
Counting pixels of same value in R

Time:05-15

I need help with counting pixels of the same value in R. I'm doing a master thesis and part of it is calculating the NDWI of an area before and after floods so I can calculate the surface under water. From the results of NDWI after the flood values that are above 0 are under water and those under 0 are not. So I'm kinda stuck here bcs I can't figure out how to calculate all pixels above value 0.

CodePudding user response:

Using your dropbox data:

library(terra)
ndwi <- rast('Clip_ndwi_poslije1.tif')
ndwi_vec <- values(ndwi, mat = FALSE)
> length(which(ndwi_vec > 0))
[1] 21157
> length(which(ndwi_vec <= 0))
[1] 13217
> dim(ndwi)[1]
[1] 220
> dim(ndwi)[1]*dim(ndwi)[2]
[1] 58300
> sum(length(which(ndwi_vec > 0)), length(which(ndwi_vec <= 0)))
[1] 34374
> table(is.na(ndwi[])) #  see below

FALSE  TRUE 
34374 23926 

Table approach is from SOF-GIS ?s, and get you started.

CodePudding user response:

Your data

library(terra)
r <- rast("Clip_ndwi_poslije1.tif")

You could count the cells with values that are larger than zero (or not) like this:

freq(r > 0)
#     layer value count
#[1,]     1     0 13217
#[2,]     1     1 21157

TRUE == 1, so you have 21,157 cells with a value larger than zero.

But to accurately compute the area covered by these cells, you need to first get the area of each cell:

a <- cellSize(r)

And then sum these areas

b <- ifel(r > 0, a, NA)
# or the equivalent
# b <- mask(a, r>0, maskvalue=0)

global(b, "sum", na.rm=TRUE)
#            sum
#ndwiii 19013036

In this case, that is similar to (incorrectly) assuming that the nominal spatial resolution is valid for each grid cell.

global(r > 0, "sum", na.rm=TRUE) * prod(res(r))
#             sum
#ndwiii 19041300
  • Related