Use TrainableSegmentation with python

how do I import trainableSegmentation for python scripting?

Hi @Achintha_Iroshan,

The Scripting the Trainable Weka Segmentation page should give you what you need, at least in beanshell which can be readily translated to python.

Here’s a python snippet from one of my own scripts, it won’t run out of context but you can see some of the commands from the scripting wiki:

from trainableSegmentation import WekaSegmentation

 def Weka_Segm(dirs):
	""" Loads trained classifier and segments cells """ 
	"""	in aligned images according to training.    """
	
	# Define reference image for segmentation (default is timepoint000).
	w_train = os.path.join(dirs["Composites_Aligned"], "Timepoint000.tif")
	trainer = IJ.openImage(w_train)
	weka = WekaSegmentation()
	weka.setTrainingImage(trainer)
	
	# Select classifier model.
	weka.loadClassifier(str(classifier))
     
	weka.applyClassifier(False)
	segmentation = weka.getClassifiedImage()
	segmentation.show()

Hi @Sverre,

Thanks a lot for you reply to my issue. I managed to classify the image pixel using a pre-trained model. But still there is a issue with output image. show() method out puts a 8bit file but the values in it are only 1’s and 0’s.

So we have to correct the image by mapping all 1s to 255.
Or is there an easier way?

Thanks

As I understand it Trainable Weka Segm gives an 8-bit image for a maximum of 255 segmented classes. If you select just two classes, say one for background and one for object, the result is an 8-bit image where background is 0 and your object is 1.

If you just have two classes and you want to create a binary mask, sure. I’ve used a set treshold for each of my various objects, but there’s no need to do this if you only have two classes. There might be an easier way, but if it works…

You can also apply the lut that is enabled in the GUI (beanshell, from scripting wiki):

import trainableSegmentation.utils.Utils;
// apply classifier and get results as labels (same as before)
result = segmentator.applyClassifier( image, 0, false );
 
// assign same LUT as in GUI
result.setLut( Utils.getGoldenAngleLUT() );   

Hi, is it possible to use it within a routine python IDE?