【问题标题】:lapply to convert rasters to polygons using gdal_polygonizeRlapply 使用 gdal_polygonizeR 将栅格转换为多边形
【发布时间】:2019-03-21 08:42:21
【问题描述】:

我正在使用 John Baumgrtner 的 gdal_polygonizeR (https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) 将栅格转换为 R 中的多边形。除此之外 - 我尝试了 raster pkg rasterToPolygons 函数,但它花了很长时间; gdal_polygonizeR 更快。无论如何,我有一个要转换为多边形的 533 个栅格文件(不同范围)的列表。 gdal_polygonizeR 函数在调用单个列表元素时起作用,但我尝试使用 lapply 在所有列表元素上使用它并收到错误消息。见以下代码:

#path to folder containing all .tif raster files
dir <- "/path/to/raster/files"

#create a list of the files in the folder
files <- list.files(path = dir, pattern = ".tif$")

#use lapply to import/create list of all files in folder
rasterl_50 <- lapply(paste0(dir, files), raster)

#test gdal_polygonizeR function on single list element
gdal_polygonizeR(rasterl_50[[1]])     #works properly

#loop thru all elements in list
lapply(rasterl_50, gdal_polygonizeR)

输出 = 前六 (6) 个元素似乎运行正常,但我在 [[7]] 处收到以下错误消息:

wfp1

使用调试重新运行 readOGR(dirname(outshape), layer = basename(outshape), verbose = !quiet) 中的错误: 未找到任何功能

#

如果有人对使用 lapply 或 for 循环等的解决方案有想法,请回复。谢谢

【问题讨论】:

    标签: polygon lapply raster gdal rgdal


    【解决方案1】:

    解决方案:我不得不对每个单独的列表元素运行gdal_polygonizeR,发现列表中的几个光栅文件不包含任何值(这是由于reclassify 函数之前应用于光栅)。我从列表中删除了这些文件,lapply 工作。代码如下:

    #remove 'no value' elements from the list
    new_rastlist <- 
    rasterlist[c(-7,-14,-36,-89,-191,-310,-432,-436,-476,-493,-494,-501)]
    
    #then try again to use lapply
    polyl <- lapply(rastlist, gdal_polygonizeR)
    

    更新: 更好的是,首先删除所有 NA 的栅格:

    batch_reclass <- function(rastlist){
      for (i in 1:length(wfrastlist)) {
        #read in raster
        r <-raster(paste0("/path/to/rasterfiles/", rastlist[i]))
        #perform the reclassifcation
        rc <- reclassify(r, rclmat)
        #write each reclass to a new file 
        if (!is.na(minValue(rc))) {
        writeRaster(rc,  filename = paste0("/path/to/new/rasterfiles/", "rc_", 
        rastlist[i]), format="GTiff", overwrite=TRUE)
      }}
    }
    
    #run the function
    batch_reclass(rastlist)
    

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多