Package 'crstools'

Title: Tools to Work with Projections
Description: Choose the appropriate map projection for a given application, visualise the resulting distortion, and georeference data from unknown projections. The full functionalities of the package are described in Pozzi et al. (2026) <doi:10.31223/X5K17P> (pre-print).
Authors: Andrea Manica [aut, cre] (ORCID: <https://orcid.org/0000-0003-1895-450X>), Andrea Pozzi [aut], Cecilia Padilla-Iglesias [aut], Evie Carter [aut], Michela Leonardi [aut], Aramish Fatima [aut], Ondrej Pelanek [aut], Nile Stephenson [aut], Margherita Colucci [aut], Dominik C Jud [aut], Cassandra Gunasekaram [aut]
Maintainer: Andrea Manica <[email protected]>
License: GPL (>= 3)
Version: 1.2.0
Built: 2026-11-19 18:39:50 UTC
Source: https://github.com/EvolEcolGroup/crstools

Help Index


Function to choose the Ground Control Point (GCP) on an image

Description

GCPs are used to georeference images by providing known coordinates for specific points in the image. This functions extracts the pixel coordinates (coded as the origin on the bottom left corner, see below) of the GCPs from the image, and allows the user to input their corresponding geographic coordinates (longitude and latitude).

Usage

choose_gcp(image_obj, gcp = NULL, col = "red")

Arguments

image_obj

An array representing the image (colour images are generally imported as an array of nx x ny x 3 colour channels), or a file path to the image (currently this can only be of type .jpg).

gcp

(optional) A dataframe of GCPs, containing columns id, x, y,longitude, latitude. This is used if we want to add additional GCP to an existing list (usually created by running this function multiple times).

col

The colour of the points to be plotted on the image. Default is "red".

Details

NOTE: There are two conventions on how to define pixel coordinates. In this function (and more generally throughout crstools), the origin is defined as the bottom left corner of the image, with x increasing to the right and y increasing upwards. This is consistent with the convention used in many image processing libraries. However, some libraries (like OpenCV and GDAL) define the origin at the top left corner, with y increasing downwards. Be sure to check which convention your image processing library uses when working with pixel coordinates.

Value

A dataframe with the GCPs, including the image coordinates and their corresponding geographic coordinates.

Examples

# Get the path to an example image included in the package and choose GCPs
  img_path <- system.file("extdata/europe_map.jpeg", package = "crstools")
  # this will open a new window where you can choose some points
  gcp_europe <- choose_gcp(img_path)
  # after the first set of points is chosen, we can add more points
  gcp_europe <- choose_gcp(img_path, gcp = gcp_europe)

Extract coordinates from a georeferenced image

Description

This function allows to extract coordinates from a georeferenced image by clicking on points of interest. Every time a point is clicked, its latitude and longitude are captured, and a unique ID is assigned to it. If a dataframe of coordinates is supplied, the new points will be added to it, and the IDs will be numbered sequentially.

Usage

extract_coords(georef_image, coords_df = NULL, col = "red")

Arguments

georef_image

A spatraster object representing the georeferenced image.

coords_df

An optional dataframe containing the coordinates of points previously extracted from the image. It has to consist of 3 columns, named: "id", "longitude" and "latitude". Default is NULL.

col

The colour of the points to be plotted on the image. Default is "red".

Value

A dataframe with ID and coordinates of the points extracted from the image.

Examples

# Load required packages
library(terra)
# Georeference the image using the created GCPs
# get the gcp coordinates
gcp_europe_coords <-
  readRDS(system.file("extdata/europe_gcp_georef.RDS",
    package = "crstools"
  ))
# get the path to the image
img_path <- system.file("extdata/europe_map.jpeg", package = "crstools")
georef_path <-
  georeference_img(
    image_obj = img_path,
    gcp = gcp_europe_coords,
    output_path = file.path(tempdir(), "europe_map_georef")
  )
# georeference the image using the GCPs
map_warp <- rast(georef_path)
# get the coordinates of the points
coords_df <- extract_coords(map_warp)
# if needed, extract additional points by supplying the coords_df argument
# and re run the function
coords_df <- extract_coords(map_warp, coords_df)
# dataframe with ID and coordinates of the points extracted from the image.
print(coords_df)

Find the coordinates (longitude and latitude) of the ground control points (GCPs) in a given image

Description

Find the coordinates (longitude and latitude) of the ground control points (GCPs) in a given image

Usage

find_gcp_coords(gcp, sf_obj)

Arguments

gcp

A data frame containing the GCPs with columns id, x, y, longitude, and latitude.

sf_obj

the reference map, as an sf object (already cut to the extend and if needed projected)

Details

NOTE: There are two conventions on how to define pixel coordinates. In this function (and more generally throughout crstools), the origin is defined as the bottom left corner of the image, with x increasing to the right and y increasing upwards. This is consistent with the convention used in many image processing libraries. However, some libraries (like OpenCV and GDAL) define the origin at the top left corner, with y increasing downwards. Be sure to check which convention your image processing library uses when working with pixel coordinates.

Value

A data frame with the GCPs, including their image coordinates and corresponding geographic coordinates.

Examples

# load required packages
library(sf)
library(rnaturalearth)
# get the path to an example image included in the package and choose GCPs
img_path <- system.file("extdata/europe_map.jpeg",
  package = "crstools"
)
# choose some points
gcp_europe <- choose_gcp(img_path)
# now get some more
gcp_europe <- choose_gcp(img_path, gcp = gcp_europe)
# create a map of europe to use to get the coordinates
world <- ne_countries(scale = "medium", returnclass = "sf")
# transform it to a suitable projection
world <- st_transform(world, crs = 4326)
# crop it to the extent of the image
europe <- st_crop(world, c(xmin = -25, ymin = 25, xmax = 45, ymax = 70))
# get the coordinates for these points
new_gcp_europe <- find_gcp_coords(gcp_europe, sf_obj = europe)
# data frame with the GCPs
print(new_gcp_europe)

Add Tissot's indicatrix to a map

Description

This function adds Tissot's indicatrix to a map. Tissot's indicatrix is a mathematical contrivance used in cartography to characterize local distortions due to map projection.

Usage

geom_tissot(
  mapping = ggplot2::aes(),
  data = NULL,
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE,
  centres = c(5, 5),
  radius = NULL,
  fill = "red",
  alpha = 0.7,
  ...
)

Arguments

mapping

Set of aesthetic mappings created by ggplot2::aes(). If specified and inherit.aes = TRUE (the default), it is combined with the default mapping at the top level of the plot. You must supply mapping if there is no plot mapping.

data

The data to be displayed in this layer: an sf, SpatRaster or SpatVector object. If NULL (the default), the data of the plot is used.

na.rm

If FALSE, the default, missing values are removed with a warning. If TRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends? NA, the default, includes if any aesthetics are mapped. FALSE never includes, and TRUE always includes. It can also be a named logical vector to finely select the aesthetics to display.

inherit.aes

If FALSE, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification, e.g. ggplot2::geom_point().

centres

Either a list with elements "lng" and "lat" giving the longitudes and latitudes of the grid of centres for the Tissot's indicatrix, or a vector of length 2 with the number of rows and columns to generate such a grid automatically. The latter is passed to pretty() to get pretty breaks, and the exact number of Tissot's circles might differ from the input numbers (see pretty() for details). It defaults to c(5,5).

radius

The radius of the circles (see sf::st_buffer() for an explanation of how units are created; we recommend that you explicitly state your units with units::as_units(), e.g. units::as_units(100, "km")). If NULL (the default), it is set to a quarter of the minimum distance between the centres.

fill

The fill colour of the circles

alpha

The transparency of the circles

...

Other arguments passed on to ggplot2::geom_sf()

Value

A ggplot2 object

Examples

# load required packages
library(rnaturalearth)
library(sf)
library(ggplot2)
s_america_sf <- ne_countries(continent = "South America", returnclass = "sf")
s_am_equal_area <- suggest_crs(s_america_sf, distortion = "equal_area")
ggplot(data = s_america_sf) +
  geom_sf() +
  geom_tissot() +
  coord_sf(crs = s_am_equal_area$proj4) +
  theme_minimal()

Georeference an Image using Ground Control Points (GCPs)

Description

This function warps a given image using a set of Ground Control Points (GCPs) to create a georeferenced version of the image. The function uses GDAL tools to first translate the image into a georeferenced TIFF format and then applies a warp operation to reproject the image into a spatial reference system (EPSG:4326). The warped image is saved as a new file with the suffix ⁠_warp.tif⁠.

Usage

georeference_img(
  image_obj,
  gcp,
  output_path = NULL,
  transform_method = c("auto", "poly_1", "poly_2", "poly_3", "tps")
)

Arguments

image_obj

A character string specifying the file path to the input image (JPEG format). The function reads this image and applies the GCPs for georeferencing.

gcp

A data frame containing the Ground Control Points (GCPs). This dataframe can be produced with the choose_gcp() and find_gcp_coords() functions. This data frame should have the following columns:

  • id: An identifier for each GCP (numeric).

  • x: The x-coordinate of the GCP (in pixel space).

  • y: The y-coordinate of the GCP (in pixel space).

  • longitude: The longitude of the GCP (georeferenced).

  • latitude: The latitude of the GCP (georeferenced).

output_path

A character string giving the path (without extension) used to name the output files: .tif is appended to it for the image with the GCPs, and ⁠_warp.tif⁠ for the warped image. If NULL (the default), the path of the input image without its extension is used if image_obj is a file path, and "map" (in the working directory) if it is an array.

transform_method

A character string specifying the transformation method to be used for warping the image. Options are "poly_1" (first order polynomial), "poly_2" (second order polynomial), "poly_3" (third order polynomial), "tps" (thin plate spline), or "auto" (the default, allowing GDAL to choose of a polynomial of the appropriate order based on the number of available GCP. Polynomials are best for standard maps directly captured from a publication (a first or second order polynomial is often sufficient), tps allows for scanning artefacts, but it is badly affected by any incorrect GCP.

Value

A character string representing the path to the newly created warped TIFF image file (⁠_warp.tif⁠). This file contains the georeferenced image.

Examples

# get the path to an example image included in the package
img_path <- system.file("extdata/europe_map.jpeg",
  package = "crstools"
)
# load a set of GCPs (or we could create them using the choose_gcp()
# and find_gcp_coords() functions)
gcp_df <- readRDS(system.file(
  "extdata/europe_gcp_georef.RDS",
  package = "crstools"
))
# Assuming you have a set of GCPs in gcp_df and an image file "image.jpg"
warped_img <- georeference_img(
  image_obj = img_path, gcp = gcp_df,
  output_path = tempfile(pattern = "georef_img_")
)

Extract projection-induced distortion metrics

Description

This function computes Tissot's indicatrix distortion metrics (Snyder 1987, pp. 20-26) for a grid of points across the extent of data, evaluated in the CRS of data.

Usage

get_distortion_metrics(
  data,
  centres = c(5, 5),
  radius = 100,
  method = c("sphere", "ellipsoid")
)

Arguments

data

An sf, SpatRaster, or SpatVector object. This has to be projected to the CRS intended to assess.

centres

Either a list with elements "lng" and "lat", or a vector of length 2 with the number of rows/columns for an automatic grid, as in geom_tissot(). Default is c(5, 5).

radius

The length of the probing step used to estimate local distortion, in metres, used only when method = "sphere". Unlike in geom_tissot(), it does not depend on the spacing of the grid, as it only sets the accuracy of the estimates (longer steps are less accurate). Default is 100.

method

The Earth model used to compute the distortion metrics, either "sphere" or "ellipsoid". "sphere" projects small steps north and east of each grid point, placed on a sphere, and estimates distortion from their displacement. "ellipsoid" uses PROJ::proj_factors(), which accounts for the flattening of the ellipsoid and requires the suggested package 'PROJ' (>= 0.7.0); if PROJ cannot compute the metrics, an error is raised (use "sphere" instead). Default is "sphere".

Details

Distortion metrics can be computed using two different method:

  • "sphere": for each grid point, the function takes a short step, of length radius, due north and due east on a sphere with fixed radius. Point and steps are then projected to the CRS of data, and the distortion metrics are computed. Because the Earth is not a perfect sphere, this method is less accurate than the "ellipsoid" method (differences in angular distortion are usually below 1°), but it does not require the PROJ library and the PROJ R package installed.

  • "ellipsoid": distortion metrics are computed using the PROJ R library via the PROJ::proj_factors() function, using the ellipsoid defined by the CRS and therefore being more accurate than the "sphere" method. This method requires the PROJ R package (>= 0.7.0) installed. Currently, the latter works from binary for Windows and Linux, but not for MacOS. The latter can be installed from source, but requires the PROJ library to be installed.

The following measures are returned per each grid point: areal_scale, the ratio of projected to true area (value of 1 means no area distortion, higher values indicate local inflation, while lower values indicate local shrinkage), angular_distortion, Snyder's maximum angular deformation in degrees (a value of 0 degrees means no shape distortion, a value of 180 degrees means complete shape distortion), the semi-major and semi-minor axes of the indicatrix, and the intersection angle between the projected meridian and parallel directions (90 degrees indicates no angular distortion).

Value

A data.frame with one row per grid point: lon, lat (centre of the point, in EPSG:4326), areal_scale, angular_distortion (degrees), intersection_angle (degrees), semi_major, and semi_minor.

References

Snyder, J.P. (1987) Map Projections: A Working Manual. U.S. Geological Survey Professional Paper 1395, pp. 20-26. Washington, D.C.: U.S. Government Printing Office. DOI: 10.3133/pp1395.

Sumner, M.D. (2026) PROJ: Generic Coordinate System Transformations Using 'PROJ'. R package version 0.7.0. https://CRAN.R-project.org/package=PROJ

Examples

# load required packages
library(rnaturalearth)
library(sf)
s_america_sf <- ne_countries(continent = "South America", returnclass = "sf")
s_am_equal_area <- suggest_crs(s_america_sf, distortion = "equal_area")
s_america_proj <- st_transform(s_america_sf, s_am_equal_area$proj4)
metrics <- get_distortion_metrics(s_america_proj)
summary(metrics[c("areal_scale", "angular_distortion")])

Residuals of the polynomial transformation fitted to Ground Control Points

Description

This function refits the polynomial transformation that GDAL uses in georeference_img() (pixel coordinates to longitude/latitude) and returns, for each Ground Control Point (GCP), the ordinary residuals and the leave-one-out (LOO) residuals. Ordinary residuals measure how well the transformation fits the GCPs used to estimate it. On the other hand, LOO residuals are obtained by predicting each GCP from a transformation fitted to all the other GCPs, and give a more "honest" measure of the error expected for points of the map that were not used as GCPs. The leverage of each GCP is also returned, which is a measure of how much influence each GCP has on the fitted transformation. Leverage values range from 0 to 1, with higher values indicating that the GCP has more influence on the fitted transformation.

Usage

get_gcp_residuals(
  gcp,
  transform_method = c("auto", "poly_1", "poly_2", "poly_3")
)

Arguments

gcp

A data frame containing the Ground Control Points (GCPs), with columns id, x, y, longitude and latitude (the same format used by georeference_img()).

transform_method

A character string specifying the polynomial used for the transformation. Options are "poly_1" (first order polynomial), "poly_2" (second order polynomial), "poly_3" (third order polynomial) or "auto" (the default), which mimics the choice made by GDAL in georeference_img(): a first order polynomial if fewer than 6 GCPs are available, and a second order polynomial otherwise.

Details

The transformation is a polynomial in pixel coordinates, fitted by ordinary least square separately for longitude and latitude, with all terms up to the specific order (3, 6, 10 coefficients for first, second and third order polynomials). This forward (pixel to lon/lat) transformation, is the same applied by GDAL in georeference_img() and get_pts_coords(). LOO residuals are computed without refitting as ei/(1−hii)e_i / (1 - h_{ii}), where eie_i is the ordinary residual and hiih_{ii} is the leverage of the i-th GCP.

Residuals are given in degrees (observed minus fitted) and as the great-circle distance (in km, on a sphere of radius 6371.0088 km) between the observed and the fitted position of each GCP. Note that, because the polynomial is fitted in degrees, residuals in longitude are not comparable across latitudes, whereas distances in km are.

Value

A data frame with one row per GCP, containing the original columns and:

  • fitted_lon, fitted_lat: the position predicted by the transformation.

  • res_lon, res_lat: the ordinary residuals, in degrees.

  • res_km: the distance between observed and fitted position, in km.

  • leverage: the leverage of each GCP. Values close to 1 indicate GCPs that strongly determine the transformation (typically points at the edges of the map, or isolated points).

  • loo_lon, loo_lat: the leave-one-out residuals, in degrees.

  • loo_km: the distance between observed and leave-one-out predicted position, in km.

The data frame has the attributes order (the order of the polynomial).

Examples

gcp_df <- readRDS(system.file(
  "extdata/europe_gcp_georef.RDS",
  package = "crstools"
))
res <- get_gcp_residuals(gcp_df, transform_method = "poly_1")
res
# mean error (km)
mean(res$res_km)
# root mean square error (km)
sqrt(mean(res$res_km^2))
# leave-one-out root mean square error (km), no GCPs with leverage 1 (NA)
sqrt(mean(res$loo_km^2, na.rm = TRUE))

Extract geographic coordinates from pixel coordinates

Description

Transform target point pixel coordinates into longitude/latitude coordinates using a set of Ground Control Points (GCPs). This function performs direct point-wise coordinate transformation without warping a raster.

Usage

get_pts_coords(gcp, target_pts, transform_method = "auto", lambda = 0)

Arguments

gcp

A data frame containing the Ground Control Points (GCPs). This dataframe can be produced with the choose_gcp() and find_gcp_coords() functions. This data frame should have the following columns:

  • id: An identifier for each GCP (numeric).

  • x: The x-coordinate of the GCP (in pixel space).

  • y: The y-coordinate of the GCP (in pixel space).

  • longitude: The longitude of the GCP (georeferenced).

  • latitude: The latitude of the GCP (georeferenced).

target_pts

A data frame containing the target points to transform. This dataframe must contain the following columns (any other column, such as an identifier for each point, is kept in the output):

  • x or cx: The x-coordinate of the point (in pixel space).

  • y or cy: The y-coordinate of the point (in pixel space).

transform_method

A character string specifying the transformation method to be used for warping the image. Options are "poly_1" (first order polynomial), "poly_2" (second order polynomial), "poly_3" (third order polynomial), "tps" (thin plate spline), or "auto" (the default, automatically selecting a polynomial order based on the number of GCPs available).

lambda

Numeric smoothing parameter used for thin plate spline transformations (transform_method = "tps"). The default, 0, interpolates exactly through the GCPs, matching the GDAL thin plate spline used by georeference_img(). Larger values introduce smoothing (the spline no longer passes exactly through the GCPs), which may improve robustness when GCPs contain noise or digitizing errors. As pixel coordinates are rescaled by the extent of the GCPs before fitting, the amount of smoothing for a given lambda does not depend on the resolution of the image.

Details

Polynomial transformations are implemented using native linear models, while thin plate spline transformations are implemented using fields::Tps(). For thin plate splines, the x and y pixel coordinates are rescaled by the same factor, so that distances between points are proportional to distances in pixels, as in the GDAL thin plate spline used by georeference_img().

Note that, when using tps as a method, fields::Tps() might print "Grid searches over lambda (nugget and sill variances) with minima at the endpoints". This is benign: fields::Tps() always searches for the best smoothing parameter and reports when the best value is at the edge of its search range, but the fit uses the value given in lambda.

Value

A data frame containing:

  • All the columns of target_pts (including the pixel coordinates).

  • longitude: Estimated longitude.

  • latitude: Estimated latitude.

Examples

pts_df <- readRDS(system.file(
  "extdata/europe_gcp_georef.RDS",
  package = "crstools"
))
target_df <- data.frame(pt_id = 1:2, x = c(477, 2014), y = c(554, 1311))
get_pts_coords(pts_df, target_df)

Function to plot the Ground Control Points (GCPs) on an raw image

Description

GCPs are used to georeference images by providing known coordinates for specific points in the image. This function plots GCPs onto the original map (i.e. using the pixel coordinates of the points on the original image before georeferencing). This can be helpful in thinking about here additional GCPs might be needed to improve the transformation.

Usage

plot_gcp(image_obj, gcp, col = "red")

Arguments

image_obj

An array representing the image (colour images are generally imported as an array of nx x ny x 3 colour channels), or a file path to the image (currently this can only be of type .jpg).

gcp

A dataframe of GCPs, containing at least columns id, x, y.

col

The colour of the points to be plotted on the image. Default is "red".

Value

A plot with the GCPs

Examples

# Get the path to an example image included in the package
img_path <- system.file("extdata/europe_map.jpeg", package = "crstools")
# load some previously captured GCPs
gcp_europe <- readRDS(system.file(
  "extdata/europe_gcp_georef.RDS",
  package = "crstools"
))
# plot
plot_gcp(img_path, gcp = gcp_europe)

Suggestions for map projections depending on the extent

Description

This function provides suggestions for map projections depending on the extent of the map. For SDMs, an equal area projection is generally favoured, but it is also possible to get suggestions for conformal, equidistant or compromise projections. The algorithm is a reimplementation in R of Projection Wizard (Bojan et al., 2016), version 2.1. (https://projectionwizard.org/)

Usage

suggest_crs(
  x,
  distortion = c("equal_area", "conformal", "equidistant", "compromise"),
  round_cm = FALSE,
  return_best = TRUE,
  datum = c("WGS84", "ETRS89", "NAD83"),
  unit = c("m", "ft"),
  lat_check = TRUE,
  world_equidist = NULL,
  quiet = FALSE
)

Arguments

x

A vector of four numeric values representing the extent of the map in longitude and latitude (xmin, xmax, ymin, ymax), or a SpatExtent object in longitude and latitude, or a SpatRaster or sf object in a geographic (lon/lat) CRS. Objects with no CRS are assumed to be in longitude and latitude.

distortion

The type of distortion to be minimized. Options are "equal_area", "conformal", "equidistant" and "compromise". Default is "equal_area".

round_cm

Logical. If TRUE, the central meridian is rounded to the nearest degree. Default is FALSE.

return_best

Logical. If TRUE, only the best projection is returned, otherwise, if there are multiple options, a list will be returned

datum

The datum to use. Options are "WGS84", "ETRS89" and "NAD83". Default is "WGS84".

unit

The unit to use. Options are "m" and "ft". Default is "m".

lat_check

Logical. If TRUE, the function will check if lat values are within range (-90,90). Default is TRUE.

world_equidist

if distortion="equidistant" for a whole world projection, then this parameter should be a list with one of the following sets of elements:

  • "Polar azimuthal equidistant": prj = "polar", pole, lng_central, where pole is either -90 or 90 for the South and North Pole, respectively, from or through which distances are correct, and lng_central is the central meridian. E.g. list(prj = "polar", pole = 90, lng_central = -180)

  • "Oblique azimuthal equidistant": prj = "oblique", lat_centre, lng_centre, where lat_centre and lng_centre are the latitude and longitude of the centre from or through which distances are correct. E.g. list(prj = "oblique", lat_centre = 39, lng_centre = 145)

  • "Two-point azimuthal": prj = "two_points", lat1, lng1, lat2, lng2, where lat1, lng1, lat2, lng2 are the latitude and longitude of two points on the map from which distances are correct. E.g. list(prj = "two_points", lat1 = 34, lng1 = -117, lat2 = 46, lng2 = 16)

quiet

Logical. If TRUE, suppresses messages. Default is FALSE.

Value

Either a list of two strings (proj4 and WKT) for a single projection (if either only one projection is available or return_best is TRUE), or a list of lists, each containing two strings (proj4 and WKT) for a single projection (if multiple projections are available and return_best is FALSE).

References

Bojan, S, Bernhard, J, & Helen, J (2016) Projection Wizard - An Online Map Projection Selection Tool. The Cartographic Journal 53(2):177-185 DOI: 10.1080/00087041.2015.1131938

Examples

# Whole map
suggest_crs(c(-180, 180, -90, 90))
# Northen Hemisphere
suggest_crs(c(-180, 180, 21, 70))
# Hemisphere showing the tropics
suggest_crs(c(-180, 180, -7, 21))
# Regional map for EW extent
suggest_crs(c(-60, 20, 40, 70))