R raster package split image into multiples

后端 未结 6 1759
闹比i
闹比i 2021-02-03 14:18

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

6条回答
  •  借酒劲吻你
    2021-02-03 14:55

    This comes a bit late but may be useful to others coming across this question. The SpaDES package has a handy function called splitRaster() which does what you're after.

    An example:

    library(raster)
    library(SpaDES)
    
    # Create grid
    the_grid=raster(xmn=0, xmx=100, ymn=0, ymx=100, resolution=1)
    
    # Set some values
    the_grid[0:50,0:50] <- 1
    the_grid[51:100,51:100] <- 2
    the_grid[51:100,0:50] <- 3
    the_grid[0:50,51:100] <- 4
    

    Which gives you this: Now do the splitting using the SpaDES package. Set nx and ny according to the number of tiles you want along the x and y axis - if we want 4 tiles, set them as nx=2 and ny=2. If you don't set path, it should write the files to your current directory. There are other things on offer too like buffering - see ?splitRaster:

    # Split into sections - saves automatically to path
    sections=splitRaster(the_grid, nx=2, ny=2, path="/your_output_path/")
    

    The variable sections is a list of rasters, one for each section of the_grid - access them as:

    split_1=sections[[1]]
    

    If you want to save them specifically, just use writeRaster().

    To create a combined raster again, use mergeRaster().

提交回复
热议问题