Snapping a point on the raster based on condition

210 views Asked by At

I have a raster and some points. I want to snap the points closest to the raster based on some general conditions.

library(raster)
##create a diagonal matrix
xy = diag(1, 100, 100)
# Turn the matrix into a raster
rast <- raster(xy)
# Give it lat/lon coords 
extent(rast) <- c(-180,180,-90,90)
# ... and assign a projection
projection(rast) <- CRS("+proj=longlat +datum=WGS84")

##create two points just for reference
lonlat <- data.frame(x = c(50,130), y = c(75,-50))
coordinates(lonlat)<-~x+y
crs(lonlat)<- CRS("+proj=longlat +datum=WGS84")
plot(rast)
plot(lonlat,add=T)

It results in

enter image description here

Now I want to snap the points(+) on the green diagonal line. Here, I have provided a diagonal matrix to make it easy but it could be of any shape (for instance curved shape like rivers).

I have found some methods which only snaps the closest raster grid to the points.

##snap raster grid closest to point
Idx = sapply(lonlat$x,function(i) which.min(abs(unique(rasterToPoints(rast, spatial = TRUE)@coords[,1])-i)))
Idy = sapply(lonlat$y,function(i) which.min(abs(unique(rasterToPoints(rast, spatial = TRUE)@coords[,2])-i)))

I basically want two things (a) snap the closest point based on some simple condition ( rast == 1 ). (b) snap the points based on some search radius (lets say neighboring some points).

0

There are 0 answers