library(raster)
library(SegOptim)
# Set the working directory
# This will be used by SegOptim to place temporary files
# Change this according to your system
setwd("D:/MyDocs/temp/SegmOptim/SA/E3_VilarDaVeiga")
# SegOptim can optimize the following RSGISLib parameters:
#
# [1] Number of clusters for running the k-means algorithm (integer)
#
# [2] Minimum segment size, if smaller it will be merged to neighbouring segments (in pixels; integer)
#
# [3] Spectral threshold used to merge objects (float), is a value providing the maximum (Euclidean distance)
# spectral separation for which to merge clumps. Set to a large value to ignore spectral separation and
# always merge.
# Therefore you need to provide valid minimum and maximum values for each parameter
#
# These values obviously depend on the target, objectives and the spatial resolution of the inputs
# so please define them with care
#
RSGISLib_Shep_min <- c(5, 10, 3)
RSGISLib_Shep_max <- c(12, 60, 40)
# Other inputs ------------------------------------------------------------------------------------------------ #
# Classification features (a RasterStack object)
rstClassifFeatures <- stack("./CLASSIF_FEAT/WV2_VilarVeiga_smallTestSite.tif")
# Train data (a RasterLayer object)
rstTrainData <- raster("./TRAIN_AREAS/trainAreas_Adealbata_VVeiga_WV2_v1.tif")
# A path to the multiband image file used for image segmentation
# This will be used by the external software for image segmentation purposes
segmFeatures <- "./SEGM_FEAT/WV2_b532_VilarVeiga_smallTestSite.tif"
#
# Don't forget to modify pythonPath containing RSGISLib
pyPath <- "C:/Anaconda3/envs/py35"
# Run the optimization procedure ----------------------------------------------------------------------------- #
gaOptim <- gaOptimizeSegmentationParams( rstFeatures = rstClassifFeatures,
trainData = rstTrainData,
# // Segmentation parameters ---
segmentMethod = "RSGISLib_Shep",
inputRstPath = segmFeatures,
pythonPath = pyPath,
verbose = FALSE,
# // End segmentation parameters ---
trainThresh = 0.5,
segmStatsFuns = c("mean"),
classificationMethod = "RF",
classificationMethodParams = NULL,
balanceTrainData = FALSE,
balanceMethod = "ubOver",
evalMethod = "5FCV",
evalMetric = "Kappa",
minTrainCases = 30,
minCasesByClassTrain = 10,
minCasesByClassTest = 10,
minImgSegm = 30,
lower = RSGISLib_Shep_min,
upper = RSGISLib_Shep_max,
popSize = 20,
pcrossover = 0.8,
pmutation = 0.2,
maxiter = 100,
run = 20,
keepBest = TRUE,
parallel = 2) # use 2 cores (change according to available resources)
# Value of evalMetric for the optimal set of parameters found by the genetic algorithm
#
print(gaOptim@fitnessValue)
# Optimized parameters (for RSGISLib) containing three values:
# number of clusters, min segment size, and, spectral threshold
#
print(gaOptim@solution)
# ------------------------------------------------------------------------------------------------------------ #
# Now you can use the optimizaed parameters to run a final classification and export results ----------------- #
segmObj <- segmentation_RSGISLib_Shep(x = gaOptim@solution, # Use optimized parameters
inputRstPath = segmFeatures,
outputSegmRst = "segm_raster.tif", # Output segmented raster (change this!)
pythonPath = pyPath,
verbose = TRUE)
rstSeg <- raster(segmObj$segm)
# Prepare data before classification
# This will populate each segment with statistics of each one of the layers in rstClassifFeatures ------------- #
#
calDataPrep <- prepareCalData(rstSegm = rstSeg,
trainData = rstTrainData,
rstFeatures = rstClassifFeatures,
thresh = 0.5,
funs = "mean",
verbose = TRUE)
# Run the final classification -------------------------------------------------------------------------------- #
#
RFclassif <- calibrateClassifier(calData = calDataPrep,
classificationMethod = "RF",
classificationMethodParams = NULL,
balanceTrainData = FALSE,
balanceMethod = "ubOver",
evalMethod = "5FCV",
evalMetric = "Kappa",
minTrainCases = 30,
minCasesByClassTrain = 10,
minCasesByClassTest = 10,
runFullCalibration = TRUE) # This is mandatory - see help files!
# Average performance for evalMetric and using test data only (i.e., data not used for training)
RFclassif$AvgPerf
# Performance stats for evalMetric across test rounds
RFclassif$PerfStats
# Calculate other performance scores for the classification (PSS, GSS, and AUC)
# see ?evalPerformanceClassifier
#
evalPerformanceClassifier(RFclassif)
# Confusion matrix for the full dataset
RFclassif$ConfMat$FULL
# Predict the label/class of each object --------------------------------------------------------------------- #
#
predictSegments(classifierObj = RFclassif,
calData = calDataPrep,
rstSegm = rstSeg,
predictFor = "all",
filename = "segm_classified.tif", # The output file with class labels for each object
verbose = TRUE,
na.rm = TRUE)