Skip to content
Subhadip Datta edited this page Jun 22, 2020 · 6 revisions

ExtractTrainData 9.1.5 : Extract Values from Raster

Author: Subhadip Datta

This package is build for _Extract pixel values_ of any _spatial raster by corresponding Point, Line or Polygon_.
One can use this package to generate _training/ testing datasets_ to build _Statistical models for Classification, Regression or Prediction_.

To install this package from R-Gui or R Studio run those codes:

Cran: install.packages("ExtractTrainData")

Github: install.packages("devtools")
devtools::install_github("SubhadipDatta/ExtractTrainData")

A guide with codes:

# import Packages
library(raster)
library(ExtractTrainData)

#Import Dataset
img<-brick(system.file("extdata","ras.tif",package = "ExtractTrainData")) #import image from help file
point.shp<-shapefile(system.file("extdata","poin.shp",package = "ExtractTrainData")) #import point shapefile from help file
line.shp<-shapefile(system.file("extdata","lines.shp",package = "ExtractTrainData")) #import line shapefile from help file
poly.shp<-shapefile(system.file("extdata","poly_shp.shp",package = "ExtractTrainData")) #import polygon shapefile from help file

#plot datasets
plotRGB(img,3,2,1,stretch="lin")
plot(poly.shp,add=T,lwd=2,col="NA")
plot(line.shp,add=T,lwd=2,col="red")
plot(point.shp,pch=21,col="white",add=T)


Plot of Image and shapefiles


#Name of input and output Columns
In.colName<-"Id" # column name of shapefile attribute where class values are available.
Out.colName<-"Class ID" # column name of data frame to store shape file attribute class values.

#Extract data from image
trdPoly<-ExtractByPoly(img,poly.shp,In.colName,Out.colName)
trdPoint<-ExtractByPoint(img,point.shp,In.colName,Out.colName)
trdline<-ExtractByLine(img,line.shp,In.colName,Out.colName)

It show you some general Information, at the time of execution.
trdPoly<-ExtractByPoly(img,poly.shp,In.colName,Out.colName)
No. of bands - 9
No. of classes - 3
.....33% .....67% .....100%
Extraction Completed

It is a Example of output from ExtractByPoly:

This data frame contained Class ID and corresponding value of the raster within a polygon.

head(trdPoly)
ras.1 ras.2 ras.3 ras.4 ras.5 ras.6 ras.7 ras.8 ras.9 Class ID
1 0.0057 0.0334 0.0171 0.2488 0.1176 0.0429 0.8713802 -0.4300000 -0.1980824 1
2 0.0097 0.0334 0.0171 0.2684 0.1295 0.0487 0.8802101 -0.4802431 -0.2130634 1
3 0.0057 0.0334 0.0228 0.2749 0.1256 0.0487 0.8468257 -0.3622378 -0.2149528 1
4 0.0016 0.0409 0.0284 0.2880 0.1335 0.0545 0.8204803 -0.3148371 -0.2194559 1
5 0.0097 0.0409 0.0228 0.3010 0.1454 0.0545 0.8591723 -0.4100906 -0.2362104 1
6 0.0057 0.0409 0.0228 0.2945 0.1454 0.0545 0.8562874 -0.4100906 -0.2299291 1