【问题标题】:Maintaining SpatialPolygonDataFrame Column when using extract function to extract pixel values from a Raster in R?使用提取函数从R中的栅格中提取像素值时维护SpatialPolygonDataFrame列?
【发布时间】:2020-09-06 19:30:11
【问题描述】:

我的目标是对多光谱高分辨率无人机图像执行随机森林分类。

目前我正在为算法准备训练数据。我开始编写一个 for 循环来使用训练区域多边形 (SpatialPolygonsDataFrame) 提取我的栅格 (RasterBrick) 的像素值。但是,一位同事向我指出了 Rs 提取功能,它可能更容易并且看起来不那么混乱。

###Rast1B is a RasterBrick and contains pixel value info on 4 Bands (B1-B4)
> print(Rast1B)
class      : RasterBrick 
dimensions : 10000, 10000, 1e+08, 4  (nrow, ncol, ncell, nlayers)
resolution : 0.1, 0.1  (x, y)
extent     : 361000, 362000, 5619000, 5620000  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=32 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
source     : C:/Users/foofoo
names      :  B1,  B2,  B3,  B4 
min values :   0,   0,   0,   0 
max values : 255, 255, 255, 255 

###Shape1B is a SpatialPolygonDataframes and contains ROI polygons as well as a class id column (1 or 2, there are only two classes)
> print(Shape1B)
class       : SpatialPolygonsDataFrame 
features    : 104 
extent      : 361420.1, 361607.7, 5619007, 5619334  (xmin, xmax, ymin, ymax)
crs         : +proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs 
variables   : 1
names       : id 
min values  :  1 
max values  :  2 

提取返回一个包含 5 列的 DF。但是,SpatialPolygonsDF 中的类 id 列丢失并被多边形 id 替换。

trainingDF <- extract(Rast1B, Shape1B, df=TRUE)
    ###Just the first three rows to give an overview
    > print(bar2)
        ID  B1  B2  B3  B4
    1    1 105 123 145 116
    2    1 112 131 154 123
    3    1 116 135 153 126

我正在寻找一种方法来使用提取,同时维护每个像素的类 ID,因为这是创建训练和测试数据所必需的。它也可能在提取后基于多边形 id 手动添加列,但我不确定如何处理这个问题,因为我对 R 很陌生。

感谢任何输入!

【问题讨论】:

    标签: r dataframe classification extract raster


    【解决方案1】:

    ID 指的是多边形的(顺序);因此您可以使用这些多边形的属性(在您的情况下为字段id)来建立连接。以下应该做到这一点

    trainingDF <- data.frame(trainingDF)
    trainingDF$id <-  Shape1B$id[trainingDF$ID]
    

    【讨论】:

    • 我是新用户,无法投票,但非常感谢。通过 id 连接对我有用,看起来比我的 for 循环干净得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多