how to create an extent which is not parallel to X and Y axis R raster

166 views Asked by At

I have below code which creates an extent that is parallel to X and Y axis.

Is there a way to create an extent which is not straight - for example I would like to create 2 lines that are parallel to to one diagonal. But one line is below that diagonal by 10 pixels and the other line is above the diagonal by 10 pixels. Create 2 more lines in similar manner but around the other diagonal and use those 4 lines as edges of my extent

library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)

png("aaa.png",width=20,height=20)
par(mai=c(0,0,0,0))
image(crop(x,extent(c(0,30,0,30))))
dev.off()
2

There are 2 answers

1
vitalina On

I suggest trying select() with use="pol" parameter. This will allow for an interactive selection of a region on a plot, although the resulting region might not be as precise as you want it.

Edit with a code:

Here is how I would go about it: x1 <- select(x, use = "pol")

This will open x as an image in a new window (in Plots tab if you use RStudio). Now you can use your mouse to select a region: just click on points which surround the region you want to have. After you are done clicking hit Esc and the new image will be saved as x1 object. You can print/save it then.

1
Robert Hijmans On

An extent is by definition rectangular (at least in the raster package). But you can define a polygon and use that to crop & mask your raster data.

library(raster)
r <- brick(system.file("external/rlogo.grd", package="raster"))
plotRGB(r)
p <- spPolygons(rbind(c(20, 20), c(30, 50), c(70, 50), c(60, 20)))
plot(p, add=TRUE, lwd=4, border='red')

x <- crop(r, p)
m <- mask(x, p)
plotRGB(m)
plot(p, add=TRUE, lwd=4, border='red')