简体   繁体   English

R中的裁切(子集)栅格图像(矩阵)

[英]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. 我想将其“裁剪”到6个单独的单元格中,并将每个单元格保存为自己的矩阵。 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. 然后知道我的单元格分别是x尺寸的1/3乘以y尺寸的1/2,然后循环查找并保存每个单元格。

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. 我实际尝试使用的数据有48个单元格,每个单元格周围都有一条淡淡的线,创建了一个大小相等的矩形。 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. 如果R中有一种方法可以找到边界并冲压出理想的单个单元格,但是使用尺寸似乎是一个可行的解决方案。

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: 但是我认为, raster包是以一种非常通用,易于理解的方式完成您想要的事情的最佳解决方案:

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 )

重构图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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