Apply Classifier - Weka Segmentation

weka
segmentation
trainable-weka
classifier
#1

Hi Everyone!

I’m trying to use the “apply classifier” option in an image and repeat this template in several images, however every time this generates an error and the program hangs, would it be possible to have the same classifier for several similar images?

#2

@Carlos_Alberto

For me… there are some great sample scripts on this page: Scripting the Trainable Weka Segmentation.

In particular … this script:

#@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.io.FileSaver;
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;
            System.gc();
        }
    }
}
// print elapsed time
estimatedTime = System.currentTimeMillis() - startTime;
IJ.log( "** Finished processing folder in " + estimatedTime + " ms **" );

So…

  1. Copy that BeanShell code
  2. Open the Script Editor (File > New > Script or just click the left bracket key ‘[’)
  3. Paste in the code and select Language > BeanShell
  4. Then click ‘run’ and off you go!

Let us know if this works for you.