在使用提取功能从R中的栅格提取像素值时,维护SpatialPolygonDataFrame列吗?

时间:2020-05-20 12:19:31

标签: r dataframe classification extract raster

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

目前,我正在为算法准备训练数据。我开始编写一个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还是很陌生,所以我不确定该如何处理。

感谢任何输入!

1 个答案:

答案 0 :(得分:0)

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

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