Skip to contents

This function allows cropping of a raster mosaic interactively or programmatically:

  • Interactive Mode: If neither shapefile nor mosaic2 is provided, an interactive map is shown via mosaic_view(), allowing users to draw a rectangle to define the cropping area.

  • Shapefile Mode: If a SpatVector is provided in shapefile, cropping or masking is performed based on its extent or exact shape, optionally with a buffer.

  • Raster Mode: If mosaic2 is provided, mosaic will be cropped to match the extent of mosaic2.

For disk-based mosaics, cropping with shapefiles uses GDAL (sf::gdal_utils()) to improve efficiency.

Usage

mosaic_crop(
  mosaic,
  r = 3,
  g = 2,
  b = 1,
  re = 4,
  nir = 5,
  shapefile = NULL,
  in_memory = FALSE,
  mosaic2 = NULL,
  buffer = 0,
  show = c("rgb", "index"),
  index = "R",
  max_pixels = 5e+05,
  downsample = NULL,
  type = c("crop", "mask"),
  ...
)

Arguments

mosaic

A SpatRaster object to be cropped.

r, g, b, re, nir

Integer indices representing the red, green, blue, red-edge, and near-infrared bands of the input mosaic. Default assumes BGR format (b = 1, g = 2, r = 3).

shapefile

An optional SpatVector (or sf object) to use as cropping/masking geometry. Can be created interactively with shapefile_input().

in_memory

Logical. If TRUE, raster processing will occur entirely in memory using terra. If FALSE (default), disk-based processing with GDAL will be used when appropriate.

mosaic2

A second SpatRaster whose extent will be used to crop mosaic.

buffer

A numeric value indicating a buffer (in CRS units) to apply around the shapefile geometry.

show

A character value indicating what to display in the interactive viewer. Either "rgb" or "index".

index

The index to show if show = "index". Default is "R".

max_pixels

Maximum number of pixels to render in the interactive viewer.

downsample

Optional downsampling factor for display purposes.

type

Either "crop" (default) or "mask":

  • "crop" crops the mosaic to the bounding box of the shapefile.

  • "mask" sets pixels outside the shapefile geometry to NA (recommended when using exact shapes).

...

Additional arguments passed to mosaic_view().

Value

A cropped or masked SpatRaster object.

Details

Crop or mask a SpatRaster object (mosaic) based on user input from an interactive map or by using a provided shapefile or another raster.

Examples

if (interactive() && requireNamespace("EBImage")) {
  library(pliman)
  # Load a sample raster
  mosaic <- mosaic_input(system.file("ex/elev.tif", package = "terra"))

  # Interactive cropping with drawn rectangle
  cropped <- mosaic_crop(mosaic)

  # View result
  mosaic_view(cropped)
}