def segmentChannel_Weka(image, **kwargs):
	""" SegmentChannel using a Weka Classification"""
	ch = kwargs['channel']
	if ch > len(image): 
		raise Exception('Expecting at least ' + str(ch) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
	imp = image[ch-1].duplicate()
	ws = WekaSegmentation(imp)	# create an instance
	ws.loadClassifier(kwargs['clspath']) # load classifier
	impProb  = ws.applyClassifier(imp, 0, True)
	impMetaProb = extractChannel(impProb,1,1)
	impMetaProb.setTitle("MetaProb")
	# segmentation
	impBW = threshold(impMetaProb, kwargs['probThr'])
	impMetaProb.show()
	IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
	
	# particle analysis
	IJ.run(impBW, "Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
	rt = Analyzer.getResultsTable()
	validParticles = []
	roim = RoiManager.getInstance()
	if roim == None:
		raise Exception('Fiji error segmentNuclei.py: no RoiManager!')
	if roim.getCount() > 0:
		rois = roim.getRoisAsArray()
	else:
		IJ.log("# particles = 0")
		return impMetaProb, impBW, None, None
	X = rt.getColumn(rt.getColumnIndex("XM"))
	Y = rt.getColumn(rt.getColumnIndex("YM"))
	Mean = rt.getColumn(rt.getColumnIndex("Mean"))
	Circ = rt.getColumn(rt.getColumnIndex("Circ."))
	Area = rt.getColumn(rt.getColumnIndex("Area"))
	print "# particles = " + str(len(Mean))
	nValid = 0
	for i in range(len(Mean)):
		valid = (Mean[i]>kwargs['minProb']) and (Circ[i]<kwargs['maxCirc']) # filter particles post detection
		if(valid):
			validParticles.append([i, X[i], Y[i], Mean[i]])
	print validParticles
	IJ.log("# valid particles = %d " % len(validParticles))
	# sort particles according to Mean
	validParticlesSorted = sorted(validParticles, key=itemgetter(3))
	# only keep the three with the largest Mean
	validParticles = validParticlesSorted[-int(kwargs["nrPart"]):]
    #random.shuffle(validParticles)
	IJ.log("# valid particles = %d " % len(validParticles))
	if len(validParticles) == 0:
		validParticles = None
	return impMetaProb, impBW, validParticles, rois
# Set the options.
options = ['size=%s' % size]
circularity_str = '%.3f-%.3f' % (circularity_min, circularity_max)
options.append('circularity=%s' % circularity_str)
if show.find('_') >= 0:
    show_str = '[%s]' % show.replace('_', ' ')
else:
    show_str = show
options.append('show=%s' % show_str)
if display_results:
    options.append('display')
    if not all_results:
        options.append('summarize')
if exclude_edges:
    options.append('exclude')
if include_holes:
    options.append('include')
# Always run "in_situ".
options.append('in_situ')

# Run the command.
IJ.run(input_image_plus_copy, "Analyze Particles...", " ".join(options))

# Save outputs.
if len(output_filename) > 0:
    # Save the ImagePlus object as a new image.
    IJ.saveAs(input_image_plus_copy, output_datatype, output_filename)
if display_results and len(results_path) > 0:
    results_table = analyzer.getResultsTable()
    results_table.saveAs(results_path)
ws = WekaSegmentation(imp)  # create an instance
ws.loadClassifier(classifierPath) # load classifier
impProb = ws.applyClassifier(imp, 0, True)
#impProb.show()
impMetaProb = extractChannel(impProb,1,1)
impMetaProb.setTitle("MetaProb")

# segmentation
impBW = threshold(impMetaProb,0.6)
impMetaProb.show()
IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
impBW.show()

# particle analysis
IJ.run("Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
rt = Analyzer.getResultsTable()
validParticles = []
if(rt.getColumnIndex("XM")==-1):
  print "# particles = 0"
else:
  X = rt.getColumn(rt.getColumnIndex("XM"))
  Y = rt.getColumn(rt.getColumnIndex("YM"))
  Mean = rt.getColumn(rt.getColumnIndex("Mean"))
  Circ = rt.getColumn(rt.getColumnIndex("Circ."))
  Area = rt.getColumn(rt.getColumnIndex("Area"))
  print "# particles = " + str(len(Mean))
  for i in range(len(Mean)):
    valid = (Mean[i]>0.8) and (Circ[i]<0.8)   # filter particles post detection
    if(valid):
      validParticles.append(i)
    circularity_str = '%.3f-%.3f' % ( circularity_min, circularity_max )
    options.append( 'circularity=%s' % circularity_str )
    if show.find( '_' ) >= 0:
        show_str = '[%s]' % show.replace( '_', ' ' )
    else:
        show_str = show
    options.append( 'show=%s' % show_str )
    if display_results:
        options.append( 'display' )
        if not all_results:
            options.append( 'summarize' )
    if exclude_edges:
        options.append( 'exclude' )
    if include_holes:
        options.append( 'include' )
    # Always run "in_situ".
    options.append( 'in_situ' )

    # Run the command.
    IJ.run( input_image_plus_copy, "Analyze Particles...", " ".join( options ) )

    # Save outputs.
    if tmp_output_path not in [ None, 'None' ]:
        # Save the ImagePlus object as a new image.
        IJ.saveAs( input_image_plus_copy, output_datatype, tmp_output_path )
    if display_results and results_path not in [ None, 'None' ]:
        results_table = analyzer.getResultsTable()
        results_table.saveAs( results_path )
except Exception, e:
    jython_utils.handle_error( error_log, str( e ) )
Ejemplo n.º 5
0
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager
from ij.plugin.filter import Analyzer
from ij.measure import Measurements, ResultsTable

imp = IJ.getImage()  
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists 
 
bright_roi = OvalRoi(118,94,12,12); # define and add ROI
imp.setRoi(bright_roi)  # make active on image
rm.addRoi(bright_roi)  # add
#rm.select(0) # select the ROI

dark_roi = OvalRoi(138,144,12,12)
imp.setRoi(dark_roi)  # make active on image
rm.addRoi(dark_roi)  # add

rm.runCommand(imp,"Measure")		# this will create a new results table
rm.runCommand(imp,"Show All")		# show all ROI
rt = Analyzer.getResultsTable()		

bright_mean = rt.getValueAsDouble(rt.getColumnIndex("Max"),0)
dark_mean = rt.getValueAsDouble(rt.getColumnIndex("Mean"),1)
print "Bright :" + str(bright_mean) + " Dark: " + str(dark_mean) +  "the contrast value is :" + str(bright_mean/dark_mean) #access table by col and row