Mask and crop a raster from shapefile in R

Mask and crop

  • 单景
    • Mask
    • Crop
  • 多景

单景

Mask and crop a raster from shapefile in R_第1张图片
Mask and crop a raster from shapefile in R_第2张图片

Mask

raster_mask <- mask(raster,shp)
plotRGB(raster_mask,stretch="lin")
writeRaster(raster_mask,
            "G:/Rdata/neon_data/NEONDSLandsatNDVI/NEON-DS-Landsat-NDVI/mask/197_HARV_landRGB_mask.tif")

Mask and crop a raster from shapefile in R_第3张图片

Crop

raster_mask_crop <-crop(raster,extent(shp))
plotRGB(raster_mask_crop,stretch = "lin")
writeRaster(raster_mask_crop,
            "G:/Rdata/neon_data/NEONDSLandsatNDVI/NEON-DS-Landsat-NDVI/mask/197_HARV_landRGB_mask_crop.tif")

Mask and crop a raster from shapefile in R_第4张图片

多景

library(pacman)
p_load(raster, sf, rgdal)
wd <- "G:/Rdata/neon_data/NEONDSLandsatNDVI/NEON-DS-Landsat-NDVI/HARV/2011/RGB/"
setwd(wd)

shp <- st_read("G:/Rdata/neon_data/NEONDSLandsatNDVI/NEON-DS-Landsat-NDVI/Mask.shp")
all_RGB <-list.files(paste0(wd),full.names = TRUE,pattern = ".tif$")
all_RGB

for (afile in all_RGB){
     
  rgb <- stack(afile)
  a1 <- substr(afile,73,85)
  rgb_crop<-crop(rgb, extent(shp))
  writeRaster(rgb_crop,paste0("G:/Rdata/neon_data/NEONDSLandsatNDVI/NEON-DS-Landsat-NDVI/HARV/2011/RGB/1/",a1),format="GTiff")
}

Mask and crop a raster from shapefile in R_第5张图片

你可能感兴趣的:(R)