我的目标是对多光谱、高分辨率的无人机图像进行随机森林分类。
目前我正在准备算法的训练数据。我开始写一个for-loop来使用训练区域多边形(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
我正在寻找一种方法来使用extract,同时保持每个像素的类id,因为这是创建训练和测试数据所需要的。它可能也可以在提取后根据多边形id手动添加列,但我不确定如何处理,因为我是R的新手。
任何投入都是感激的
ID
指的是(多边形的)顺序,所以你可以使用这些多边形的一个属性,在你的例子中,字段是 id
,以建立连接。下面的步骤应该可以做到
trainingDF <- data.frame(trainingDF)
trainingDF$id <- Shape1B$id[trainingDF$ID]