Search code examples
rgispolygonrasterspatial

How to check if raster and polygon are overlapping?


i have a raster and i want to check if the cells with values are overlapping my area of Interest, which is a spatialpolygon file.

Is there a fast way to do this?

My raster look like this:

enter image description here

what i tried:

r <- raster("C:/user/test.jp2")
studyarea <- readOGR("C:/user/boundary.shp")
dummi <- as(extent(r), "SpatialPolygons")
if (gContainsProperly(studyarea, dummi)) {
  print("Raster extent is fully within the Area of interest")
} 
else if (gIntersects(studyarea, dummi)) {
  print("Raster extent is not fully within the Area of interest")
} else {
  print("Raster extent is fully outside the Area of interest")
}

as(extent(r), "SpatialPolygons") creates a polygon within the values and also the NAs. But i only want to check if the value part and the studyarea are overlapping

Data example for the raster and studyarea:

matrix <- matrix(c(NA,NA,NA,1,NA,NA,2,1,NA,1,3,4,2,3,4,1), nrow=4)
r <- raster(matrix)
extent(r) <- c(399960, 509760, 5290200, 5400000)
crs(r) <- "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs" 
writeRaster(r, paste(getwd(),"filename.jp2"))
                 
matrix <- matrix(c(1,1,NA,NA,1,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA), nrow=4)
rpoly<- raster(matrix)
extent(rpoly) <- c(399960, 509760, 5290200, 5400000)
crs(rpoly) <- "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs" 
studyarea <- rasterToPolygons(rpoly)

thanks


Solution

  • I found a quicker solution. It is possible to crop the raster by the polygon and than mask the raster by the polygon. If there are no raster Values in the area of the Polygon. The Raster will have min values = 0 and max value = 0.

    Create Data

    matrix <- matrix(c(NA,NA,NA,1,NA,NA,2,1,NA,1,3,4,2,3,4,1), nrow=4)
    r <- raster(matrix)
    extent(r) <- c(399960, 509760, 5290200, 5400000)
    crs(r) <- "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs" 
    writeRaster(r, paste(getwd(),"filename.jp2"))
                     
    matrix <- matrix(c(1,1,NA,NA,1,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA), nrow=4)
    rpoly<- raster(matrix)
    extent(rpoly) <- c(399960, 509760, 5290200, 5400000)
    crs(rpoly) <- "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs" 
    studyarea <- rasterToPolygons(rpoly)
    

    Solution

    # Reproject. Make sure both have the same projection
    studyarea <-  spTransform(studyarea, projection(r))
      
    # Crop and clip raster with study area polygon
    r_crop <- crop(r, studyarea)
    r_mask <- mask(r_crop, studyarea, updatevalue = NA, updateNA= TRUE)
    
    if (r_mask@data@min == 0 && r_mask@data@max == 0){
      print("raster and studyarea do not overlap))
      }
    else {
      print("Raster and studyarea do overlap")
    }