繁体   English   中英

R 光栅 package 将图像分割成多个

[英]R raster package split image into multiples

我有一个图像如下。 它是 2579*2388 像素。 假设它的左下角位于 0,0。 从该图像我想创建多个图像如下并将它们保存在工作文件夹中。 每张图片的大小为 100*100 像素。 每个图像都将按其左下角坐标保存。

  1. 第一张图片的左下角为 0,0。 右上角为 100,100,图像将保存为 0-0.jpg
  2. second 的左下角位于 10,0。 右上角将位于 110,100,图像将保存为 10-0.jpg
  3. 一旦底行完成,Y 坐标将移动 10。如果是第二行,第一张图像将位于 0,10,该图像将保存为 0-10.jpg

最快的方法是什么? 有没有 R package 可以很快做到的?

我知道在当前图像的情况下,它将把它分成大约 257*238 个图像。 但是我有足够的磁盘空间,我需要每个图像来执行文本检测。

在此处输入图像描述

这里使用“光栅”包的另一种方法。 该函数在空间上聚合要切割的栅格,聚合后的栅格单元变成多边形,然后使用每个多边形的范围来裁剪输入栅格。

我确信有复杂而紧凑的方法可以做到这一点,但这种方法对我有用,而且我发现它也很直观。 我希望你也觉得它有用。 注意下面的第 4 和 5 部分仅用于测试,它们不是功能的一部分。

在此处输入图片说明

第 1 部分:加载和绘制样本栅格数据

logo <- raster(system.file("external/rlogo.grd", package="raster"))
plot(logo,axes=F,legend=F,bty="n",box=FALSE)

第 2 部分:函数本身:

# The function spatially aggregates the original raster
# it turns each aggregated cell into a polygon
# then the extent of each polygon is used to crop
# the original raster.
# The function returns a list with all the pieces
# in case you want to keep them in the memory. 
# it saves and plots each piece
# The arguments are:
# raster = raster to be chopped            (raster object)
# ppside = pieces per side                 (integer)
# save   = write raster                    (TRUE or FALSE)
# plot   = do you want to plot the output? (TRUE or FALSE)
SplitRas <- function(raster,ppside,save,plot){
  h        <- ceiling(ncol(raster)/ppside)
  v        <- ceiling(nrow(raster)/ppside)
  agg      <- aggregate(raster,fact=c(h,v))
  agg[]    <- 1:ncell(agg)
  agg_poly <- rasterToPolygons(agg)
  names(agg_poly) <- "polis"
  r_list <- list()
  for(i in 1:ncell(agg)){
    e1          <- extent(agg_poly[agg_poly$polis==i,])
    r_list[[i]] <- crop(raster,e1)
  }
  if(save==T){
    for(i in 1:length(r_list)){
      writeRaster(r_list[[i]],filename=paste("SplitRas",i,sep=""),
                  format="GTiff",datatype="FLT4S",overwrite=TRUE)  
    }
  }
  if(plot==T){
    par(mfrow=c(ppside,ppside))
    for(i in 1:length(r_list)){
      plot(r_list[[i]],axes=F,legend=F,bty="n",box=FALSE)  
    }
  }
  return(r_list)
}

第 3 部分:测试功能

SplitRas(raster=logo,ppside=3,save=TRUE,plot=TRUE)
# in this example we chopped the raster in 3 pieces per side
# so 9 pieces in total
# now the raster pieces should be ready 
# to be processed in the default directory
# A feature I like about this function is that it plots
# the pieces in the original order. 

第 4 部分:在每个片段上运行代码并将它们保存回目录

# notice if you cropped a rasterbrick 
# use "brick" instead of "raster" to read
# the piece back in R
list2 <- list()
for(i in 1:9){ # change this 9 depending on your number of pieces
  rx <- raster(paste("SplitRas",i,".tif",sep=""))
  # piece_processed <- HERE YOU RUN YOUR CODE
  writeRaster(piece_processed,filename=paste("SplitRas",i,sep=""),
              format="GTiff",datatype="FLT4S",overwrite=TRUE)
}
# once a code has been ran on those pieces
# we save them back in the directory 
# with the same name for convenience

第 5 部分:让我们将这些碎片重新组合在一起

# read each piece back in R
list2 <- list()
for(i in 1:9){ # change this 9 depending on your number of pieces
  rx <- raster(paste("SplitRas",i,".tif",sep=""))
  list2[[i]] <- rx
}
# mosaic them, plot mosaic & save output
list2$fun   <- max
rast.mosaic <- do.call(mosaic,list2)
plot(rast.mosaic,axes=F,legend=F,bty="n",box=FALSE)
writeRaster(rast.mosaic,filename=paste("Mosaicked_ras",sep=""),
            format="GTiff",datatype="FLT4S",overwrite=TRUE)

这是一种方法,通过gdalUtils使用 GDAL,并根据需要进行并行化。

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))
}

将该函数应用于单个窗口的示例:

split_rast('R1fqE.jpg', xy$nm[1], xy$llx[1], xy$lly[1], 100, 100)

将其应用于前 10 个窗口的示例:

mapply(split_rast, 'R1fqE.jpg', xy$nm[1:10], xy$llx[1:10], xy$lly[1:10], 100, 100)

使用 parLapply 并行运行的示例:

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)

这来得有点晚,但可能对遇到这个问题的其他人有用。 SpaDES包有一个名为splitRaster()的方便函数,它可以完成您的任务。

一个例子:

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

这给了你这个: 在此处输入图片说明 现在使用SpaDES 包进行拆分。 根据您想要沿 x 和 y 轴的图块数量设置nxny - 如果我们想要 4 个图块,请将它们设置为nx=2ny=2 如果您没有设置path ,它应该将文件写入您的当前目录。 还有其他的东西也提供缓冲 - 见?splitRaster

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

变量sections是一个栅格列表,一个用于the_grid每个部分 - 访问它们:

split_1=sections[[1]]

如果您想专门保存它们,只需使用writeRaster()

要再次创建组合栅格,请使用mergeRaster()

您可以使用 gdal 和 r,如此链接中所示。

然后,您将修改第 23 行以进行适当的偏移,以允许生成的图块之间重叠。

没有找到专门使用的直接实现,我使用以下方法使用操作,这对其他人可能很有趣。 它生成范围并为它们裁剪原始栅格。 希望这可以帮助!

## 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)

我认为您需要为您的处理部分创建一个函数(我们称之为“fnc”)和一个列出您制作的瓷砖数量的表格(我们称之为“tile.tbl”),并且我们假设您的地理大数据称为“obj”

    obj=GDALinfo("/pathtodata.tif")
    tile.tbl <- getSpatialTiles(obj, block.x= your size of interest, return.SpatialPolygons=FALSE)        

然后使用降雪包对其进行并行化。 下面是一个例子:

    library(snowfall)
    sfInit(parallel=TRUE, cpus=parallel::detectCores())
    sfExport("tile.tbl", "fnc")
    sfLibrary(rgdal)
    sfLibrary(raster)
    out.lst <- sfClusterApplyLB(1:nrow(tile.tbl), function(x){ fnc(x, tile.tbl) })
    sfStop()

有关详细说明,请参阅此处

@Shepherd 提出的方法有效,但是您需要预先定义图像将被划分的块数( ppside参数)。 我们经常需要获得相同大小的补丁(例如训练 CNN)。 此外,将 @Shepherd 方法应用于具有不同尺寸的图像列表可能会出现问题。

这是一种使用raster package 将图像划分为相等块的方法。

我们将创建一些玩具数据。 35x64 光栅。 我们想将栅格分成 10x10 块。 patch_size = 10

my_img = raster(nrow=64, ncol=35)
values(my_img) = 1:ncell(my_img)

我们定义将执行以下操作的patchifyR function:

patchifyR <- function(img, patch_size){
  # load raster 
  if (!require("raster")) install.packages("raster")
  suppressPackageStartupMessages({library(raster)})
  # create image divisible by the patch_size
  message(paste0("Cropping original image. ", "Making it divisible by ", patch_size, "."))
  x_max <- patch_size*trunc(nrow(img)/patch_size)
  y_max <- patch_size*trunc(ncol(img)/patch_size)
  img <- crop(img, extent(img, 1, x_max, 1, y_max))
  # initializers
  lx = 1; ly = 1; p = 1
  ls.patches <- list()
  ls.coordinates <- list()
  # extract patches
  for(i in 1:(nrow(img)/patch_size)){
    for(j in 1:(ncol(img)/patch_size)){
      ls.patches[[p]] <- crop(img, extent(img, lx, (lx+patch_size)-1, ly, (ly+patch_size)-1))
      ls.coordinates[[p]] <- as.character(paste0("P_", p, "_X0_", lx, "_X1_", (lx+patch_size)-1, "_Y0_", ly, "_Y1_", (ly+patch_size)-1))
      message(paste0("Patch ", p, " created. Coordinates: ", "X0_", lx, "_X1_", (lx+patch_size)-1, "_Y0_", ly, "_Y1_", (ly+patch_size)-1))
      p = p + 1
      ly = ly + patch_size
    }
    ly = 1
    lx = lx + patch_size
  }
  # merge results: $patches and $names
  message("Matching results ... ")
  patchify <- list("patches"=ls.patches, "names"=ls.coordinates)
  # return
  message("Successfully completed.")
  return(patchify)
}

首先,我们将裁剪光栅以创建可被patch_size整除的图像。 如果我们的图块重叠大于patch_size ,我们将不会丢失信息。

然后我们使用crop function 和一个双for循环来循环遍历坐标来创建不同的补丁。

patchifyR function 接收两个参数: img:输入图像。 RasterLayer 或 RasterStack。 patch_size:路径大小。 10 创建 10x10 像素块。

patchifyR function 返回两个列表: patchify$patches:包含所有补丁(RasterLayer 或 RasterStack)的列表patchify$names:包含每个补丁的名称及其坐标。

让我们测试一下 function:

my_patches <- patchifyR(img=my_img, patch_size=10)

最后我们可以使用以下方法将结果保存到磁盘:

output_directory <- "D:/my_output/"

for(i in 1:length(my_patches$patches)){
  writeRaster(my_patches$patches[[i]], paste0(output_directory, my_patches$names[[i]], ".tif"), drivername="Gtiff", overwrite=TRUE)
}

暂无
暂无

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

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