I have two raster layers for same area. I need to find the Euclidean distance between cell of coarse resolution raster and cell of fine resolution raster that fall within each cell of the pixels from my coarse resolution raster. For example:
The red square is the pixel of coarse resolution raster while the blue squares are the pixels of fine resolution raster. The black dot is the centroid of coarse resolution raster and the blue dots are the centroids of fine resolution raster.
There are similar questions posted, but the difference with my question is that I don't want to compute the nearest distances between raster cells.
My coarse resolution raster has a pixel size of 460m and my fine resolution raster of 100m. What I have done so far is to create point symbols from the centroids of the raster cells for both rasters. How can I compute the Euclidean distance between each coarse pixel and its corresponding fine pixels?
library(terra)
fr = rast("path/fine_image.tif") # fine resolution raster
cr = rast("path/coarse_image.tif") # coarse resolution raster
fr_p = as.points(fr,
values = T,
na.rm = T,
na.all = F) # fine resolution points
cr_p = as.points(cr,
values = T,
na.rm = T,
na.all = F) # coarse resolution points
I am not sure how to proceed from here. Any recommendations?
Here are my rasters:
fr = rast(ncols=108, nrows=203, nlyrs=1, xmin=583400, xmax=594200, ymin=1005700, ymax=1026000, names=c('B10_median'), crs='EPSG:7767')
cr = rast(ncols=23, nrows=43, nlyrs=1, xmin=583280, xmax=593860, ymin=1006020, ymax=1025800, names=c('coarse_image'), crs='EPSG:7767')
The solution came from the @michael answer and the output raster (after cropping and masking with a polygon shp) looks like this:
where the yellow squares are the cells from the coarse raster and the raster underneath it's the output from the code in the answer section.
This is a bit hacky but I think it might do what you want...
# Raster at fine resolution where values are cell indices
fr_cells <- fr
values(fr_cells) <- 1:ncell(fr)
# Second raster at fine resolution where values are indices of
# the surrounding coarse res cell (if there is one)
fr_cr <- fr
fr_xy <- xyFromCell(fr, 1:ncell(fr))
values(fr_cr) <- extract(cr, fr_xy, cells = TRUE)[, "cell"]
# Function to calculate distance given a pair of cell indices
fn <- function(x) {
fr_xy <- xyFromCell(fr, x[1])
cr_xy <- xyFromCell(cr, x[2])
sqrt( sum( (fr_xy - cr_xy)^2 ) )
}
fr_dist <- app(c(fr_cells, fr_cr), fun = fn)