简体   繁体   中英

cropping (subsetting) raster image (matrix) in r

I'm looking to be able to split a raster image composed from a matrix into separate matrix/images so I can compare them.

For an example, say I have this raster image-

library(grid)      
m = matrix(c( .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7), nrow = 6, ncol=9)
grid.raster(m)

I would like to "crop" it into the 6 individual cells, saving each as it's own matrix. I've been thinking this may be possible based on the dimensions.

d <- dim(m)

And then knowing that my cells are each 1/3 the x dimension by 1/2 the y dimension then looping to find and save each cell.

The data that I'm actually trying to work with has 48 cells and has a faint line around each cell, creating a rectangles of equal size. If there is a way in R to have it find the border and punch out the individual cells that would be ideal, but using the dimensions seemed like a workable solution.

Thank you!

If you always knew that your sub-tiles were regularly shaped and square there are other ways/packages to create these. But I think the raster package is the best solution for getting done what you'd like in a very general, easily understandable manner:

m <- matrix(c( .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7), nrow = 6, ncol=9)


library(raster)

##  Construct a raster object from your matrix:
r <- raster(m)

##  Build index locations for upper left corners of grid:
i <- seq(1, ncol(r), ncol(r)/3)
j <- seq(1, nrow(r), nrow(r)/2)
indices <- expand.grid(i, j)

##  Crop to these grid locations, storing individual cropped
##    areas in a list object:
r_out <- lapply(1:nrow(indices), function(x){ 
  crop(r, 
    extent(r,
      indices[x,2], indices[x,2]+nrow(r)/2 - 1,
      indices[x,1], indices[x,1]+ncol(r)/3 - 1
    )
  )
})


##  Plot all individual rasters:
par(mfrow=c(2,3))
lapply(r_out, plot)

在此处输入图片说明

##  Re-mosaic raster objects:
args <- r_out
args['fun'] <- 'mean'
r_out_mos <- do.call(mosaic, args)
par(mfrow=c(1,1))
plot( r_out_mos )

重构图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM