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
Here's one way to do it, using GDAL via gdalUtils
, and parallelizing if desired.
library(gdalUtils)
# Get the dimensions of the jpg
dims <- as.numeric(
strsplit(gsub('Size is|\\s+', '', grep('Size is', gdalinfo('R1fqE.jpg'), value=TRUE)),
',')[[1]]
)
# Set the window increment, width and height
incr <- 10
win_width <- 100
win_height <- 100
# Create a data.frame containing coordinates of the lower-left
# corners of the windows, and the corresponding output filenames.
xy <- setNames(expand.grid(seq(0, dims[1], incr), seq(dims[2], 0, -incr)),
c('llx', 'lly'))
xy$nm <- paste0(xy$llx, '-', dims[2] - xy$lly, '.png')
# Create a function to split the raster using gdalUtils::gdal_translate
split_rast <- function(infile, outfile, llx, lly, win_width, win_height) {
library(gdalUtils)
gdal_translate(infile, outfile,
srcwin=c(llx, lly - win_height, win_width, win_height))
}
Example applying the function to a single window:
split_rast('R1fqE.jpg', xy$nm[1], xy$llx[1], xy$lly[1], 100, 100)
Example applying it to the first 10 windows:
mapply(split_rast, 'R1fqE.jpg', xy$nm[1:10], xy$llx[1:10], xy$lly[1:10], 100, 100)
Example using parLapply to run in parallel:
library(parallel)
cl <- makeCluster(4) # e.g. use 4 cores
clusterExport(cl, c('split_rast', 'xy'))
system.time({
parLapply(cl, seq_len(nrow(xy)), function(i) {
split_rast('R1fqE.jpg', xy$nm[i], xy$llx[i], xy$lly[i], 100, 100)
})
})
stopCluster(cl)