Questions about Segment Optimizer

49 views
Skip to first unread message

Alexander Quevedo Chacón

unread,
May 20, 2019, 6:09:39 PM5/20/19
to SegOptim user group
Dear All ,

I'm writing to ask for your help with some doubts. I'm currently trying to use the segment optimizer but I can't understand how to enter the parameters into the x-vector for the genetic algorithm to work.

using the data from the example available at https://segoptim.bitbucket.io I'm trying this:

segmObj <- segmentation_RSGISLib_Shep(x=c(10,21,1000),
                                      inputRstPath=inputSegFeat.path,
                             
        outputSegmRst=outSegmRst.path,
                             
        #NumClust=10,
                             
        #MinSize=100,
                             
        #SpectralThresh=1000,
                             
        pythonPath=pyPath,
                             
        verbose=T)



Which gives me the same result as if I tried it this way:
          
 segmObj <- segmentation_RSGISLib_Shep(inputRstPath=inputSegFeat.path,
                                      outputSegmRst=outSegmRst.path,
                             
        NumClust=10,
                             
        MinSize=21,
                             
        SpectralThresh=1000,
                             
        pythonPath=pyPath,
                             
        verbose=TRUE)



Additionally I can't understand how to enter the optimal segmentation parameters in the segmObj list.

I would greatly appreciate if you can help me with these questions beforehand, thank you.

best wishes
Alex




João Gonçalves

unread,
May 21, 2019, 10:52:28 AM5/21/19
to SegOptim user group
Dear Alex,

Thanks for your message.
For running the optimization you need to use the function "gaOptimizeSegmentationParams". Please check the help files to know how to run it in detail.
In short, there are two main steps:

1) Run the gaOptimizeSegmentationParams to optimize the parameters, and,
2) Using the optimized parameters, run a final round to segment, train and predict class labels to the whole image.

Check out the script below and have a good read on the code comments. For RSGISLib specifically, SegOptim only supports the < 3.5 version of this software.

In addition, for SegOptim setting the parameters correctly is crucial to obtain good results. Also, keep in mind that it may take a while to run (depending on inputs) but using parallelization and reducing the size of the inputs may help a lot to make things faster. Don't forget to change the input data in the script according to your case study. In case you want to check it, use this link to download the script test data. 



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)                            



Let me know if this works for you.

Cheers,
João

Reply all
Reply to author
Forward
0 new messages