【问题标题】:Changing a single cell value in a large raster更改大型栅格中的单个像元值
【发布时间】:2015-08-17 13:07:56
【问题描述】:

我有一个栅格砖,上面有岛屿的气候数据层,周围环绕着 NA 海洋细胞。我想将一些海洋单元格设置为附近海岸的值。这样做有很多麻烦。在我看来,代码应该如下所示,但我的内存不足。栅格大小约为 2500x2500。

# dummy stack with three layers
slogo <- stack(system.file("external/rlogo.grd", package="raster")) 
# let's say cell 5 is the one I want to change
newvals <- 1000*(1:3)
for(i in 1:nlayers(slogo)) slogo[[i]][5] <- newvals[i]

随后的步骤是将栅格写入单独的 ascii 文件;因此,另一种 hacky 解决方案可能是剪切到文本文件中并替换单个值...

编辑: 也许有人可以通过重置内存分配限制来推荐解决方案?这是我在大型栅格上运行后显示的错误消息。 Error: cannot allocate vector of size 504.1 Mb In addition: Warning messages: 1: In readBin(raster@file@con, what = dtype, n = nc, dsize, dsign, : Reached total allocation of 3979Mb: see help(memory.size) 2: In readBin(raster@file@con, what = dtype, n = nc, dsize, dsign, : Reached total allocation of 3979Mb: see help(memory.size) 3: closing unused connection 4 (C:\Users\jcw\AppData\Local\Temp\R_raster_jcw\r_tmp_2015-08-16_130255_2000_11926.gri) 4: In getBilData(object, r = startrow, nrows = nrows, c = startcol, : Reached total allocation of 3979Mb: see help(memory.size) 5: In getBilData(object, r = startrow, nrows = nrows, c = startcol, : Reached total allocation of 3979Mb: see help(memory.size) 6: In getBilData(object, r = startrow, nrows = nrows, c = startcol, : Reached total allocation of 3979Mb: see help(memory.size) 7: In getBilData(object, r = startrow, nrows = nrows, c = startcol, : Reached total allocation of 3979Mb: see help(memory.size)

【问题讨论】:

    标签: r raster


    【解决方案1】:

    你已经很接近了,这只是一个索引问题:

    library(raster)
    
    # dummy stack with three layers
    slogo <- brick(system.file("external/rlogo.grd", package="raster")) 
    
    ##  Check values of all three bands at cell 5:
    slogo[5]
    

    产量:

         red green blue
    [1,] 255   255  255
    
    ##  Set values of all three bands to zero:
    slogo[5][1:3] <- 0
    
    slogo[5]
    

    产量:

         red green blue
    [1,]   0     0    0
    

    一种可能使 OP 克服一次处理所有波段的内存问题的替代方法:

    ##  Alternatively, load each band into memory separately, do the
    ##    replacement and write each band back to disk as a separate GeoTiff:
    for (i in 1:nbands(slogo)) {
        r <- raster(slogo, layer=i)
        r[5] <- 0
        writeRaster(r, file=paste0("band_", i, ".tif"), format="GTiff")
    }
    

    【讨论】:

    • 这在示例中有效,但不能解决我的大栅格中的内存问题:Error: cannot allocate vector of size 504.1 Mb
    • 嗯,我从您的编辑中看到您只有 4GB 的 RAM。这将严重限制您使用栅格的风格,尤其是在 Windows 机器上,总体 RAM 使用量往往会减少 R 使用的空间。如果您最终还是要将这些值写入磁盘,您可以尝试我上面的编辑,但根据您正在处理的栅格的整体大小,您可能会被困在做一些更复杂的事情。
    【解决方案2】:

    您可以使用raster::update 函数来更改磁盘上光栅文件中的值(请务必进行备份!)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2016-05-22
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多