Scripting Trainable Weka Segmentation

I am trying to use Trainable Weka Segmentation to segment a lot of images. I came across the beanshell script for TWS, but it states that it only processes folders and doesn’t go into sub-folders. I need it to go into the sub-folders. Does anyone know how to write a script that will go into the sub-folders? I have a lot of folders to process and would really like to figure out how to script it.

// @File(label="Input directory", description="Select the directory with input images", style="directory") inputDir
// @File(label="Output directory", description="Select the output directory", style="directory") outputDir
// @File(label="Weka model", description="Select the Weka model to apply") modelPath
// @String(label="Result mode",choices={"Labels","Probabilities"}) resultMode
import trainableSegmentation.WekaSegmentation;
import trainableSegmentation.utils.Utils;
import ij.IJ;
import ij.ImagePlus;
// starting time
startTime = System.currentTimeMillis();
// caculate probabilities?
getProbs = resultMode.equals( "Probabilities" );
// create segmentator
segmentator = new WekaSegmentation();
// load classifier
segmentator.loadClassifier( modelPath.getCanonicalPath() );
// get list of input images
listOfFiles = inputDir.listFiles();
for ( i = 0; i < listOfFiles.length; i++ )
    // process only files (do not go into sub-folders)
    if( listOfFiles[ i ].isFile() )
        // try to read file as image
        image = IJ.openImage( listOfFiles[i].getCanonicalPath() );
        if( image != null )
            // apply classifier and get results (0 indicates number of threads is auto-detected)
            result = segmentator.applyClassifier( image, 0, getProbs );
            if( !getProbs )
                // assign same LUT as in GUI
                result.setLut( Utils.getGoldenAngleLUT() );
            // save result as TIFF in output folder
            outputFileName = listOfFiles[ i ].getName().replaceFirst("[.][^.]+$", "") + ".tif";
            new FileSaver( result ).saveAsTiff( outputDir.getPath() + File.separator + outputFileName );
            // force garbage collection (important for large images)
            result = null; 
            image = null;
// print elapsed time
estimatedTime = System.currentTimeMillis() - startTime;
IJ.log( "** Finished processing folder in " + estimatedTime + " ms **" );


You can use the same logic that is in the code example at Templates :arrow_forward: ImageJ 1.x :arrow_forward: Examples :arrow_forward: Process Folder (IJ1 Macro). That script scans folders and subfolders… so just adapt the code above, modeling after that.