I have an image as below. It is 2579*2388 pixels. Lets assume that it\'s bottom left corner is at 0,0. From that image I want to create multiple images as follows and save them
Not finding a straight-forward implementation using exclusively r I used the following approach using raster operations which may be interesting for others. It generates extents and crops the original raster to them. Hope this helps!
## create dummy raster
n <- 50
r <- raster(ncol=n, nrow=n, xmn=4, xmx=10, ymn=52, ymx=54)
projection(r) <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
values(r) <- 1:n^2+rnorm(n^2)
n.side <- 2 # number of tiles per side
dx <- (extent(r)[2]- extent(r)[1])/ n.side # extent of one tile in x direction
dy <- (extent(r)[4]- extent(r)[3])/ n.side # extent of one tile in y direction
xs <- seq(extent(r)[1], by= dx, length= n.side) #lower left x-coordinates
ys <- seq(extent(r)[3], by= dy, length= n.side) #lower left y-coordinates
cS <- expand.grid(x= xs, y= ys)
## loop over extents and crop
for(i in 1:nrow(cS)) {
ex1 <- c(cS[i,1], cS[i,1]+dx, cS[i,2], cS[i,2]+dy) # create extents for cropping raster
cl1 <- crop(r, ex1) # crop raster by extent
writeRaster(x = cl1, filename=paste("test",i,".tif", sep=""), format="GTiff", overwrite=T) # write to file
}
## check functionality...
test <- raster(paste("test1.tif", sep=""))
plot(test)