def trackmate(self):
        calibration = self.imp.getCalibration()
        model = Model()
        model.setLogger(Logger.IJ_LOGGER)
        settings = Settings()
        settings.setFrom(self.imp)
        # Configure detector - We use the Strings for the keys
        settings.detectorFactory = LogDetectorFactory()
        settings.detectorSettings = {
            'DO_SUBPIXEL_LOCALIZATION': True,
            'RADIUS': calibration.getX(self.trackmateSize),
            'TARGET_CHANNEL': 1,
            'THRESHOLD': self.trackmateThreashold,
            'DO_MEDIAN_FILTERING': True,
        }

        # Configure spot filters - Classical filter on quality
        filter1 = FeatureFilter('QUALITY', 0.01, True)
        settings.addSpotFilter(filter1)
        settings.addSpotAnalyzerFactory(SpotIntensityMultiCAnalyzerFactory())

        settings.initialSpotFilterValue = 1

        # Configure tracker - We want to allow merges and fusions
        settings.trackerFactory = SparseLAPTrackerFactory()
        settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()

        trackmate = TrackMate(model, settings)

        #--------
        # Process
        #--------

        ok = trackmate.checkInput()
        if not ok:
            print("NOT OK")

        ok = trackmate.process()
        if not ok:
            print("NOT OK")

        #----------------
        # Display results
        #----------------

        #selectionModel = SelectionModel(model)
        #displayer =  HyperStackDisplayer(model, selectionModel, self.imp)
        #displayer.render()
        #displayer.refresh()

        # Echo results with the logger we set at start:
        spots = model.getSpots()
        return spots.iterable(True)
filter2 = FeatureFilter('QUALITY', 10, True)
settings.addSpotFilter(filter2)
filter3 = FeatureFilter('MEDIAN_INTENSITY', 10, True)
settings.addSpotFilter(filter3)
filter4 = FeatureFilter('SNR', 0.5, True)
settings.addSpotFilter(filter4)

# Add an analyzer for some track features, such as the track mean speed.
settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())
settings.addTrackAnalyzer(TrackDurationAnalyzer())

filter5 = FeatureFilter('TRACK_DISPLACEMENT', 5, True)
settings.addTrackFilter(filter5)

settings.initialSpotFilterValue = 1

print(str(settings))

#----------------------
# Instantiate trackmate
#----------------------

trackmate = TrackMate(model, settings)

#------------
# Execute all
#------------

ok = trackmate.checkInput()
if not ok:
Example #3
0
  
# Add the analyzers for some spot features.
# You need to configure TrackMate with analyzers that will generate 
# the data you need. 
# Here we just add two analyzers for spot, one that computes generic
# pixel intensity statistics (mean, max, etc...) and one that computes
# an estimate of each spot's SNR. 
# The trick here is that the second one requires the first one to be in
# place. Be aware of this kind of gotchas, and read the docs. 
settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())
  
# Add an analyzer for some track features, such as the track mean speed.
settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())
  
settings.initialSpotFilterValue = 1
  
print(str(settings))
     
#----------------------
# Instantiate trackmate
#----------------------
  
trackmate = TrackMate(model, settings)
     
#------------
# Execute all
#------------
  
    
ok = trackmate.checkInput()
Example #4
0
def create_trackmate( imp, results_table ):
	"""
	Creates a TrackMate instance configured to operated on the specified
	ImagePlus imp with cell analysis stored in the specified ResultsTable
	results_table.
	"""

	cal = imp.getCalibration()

	# TrackMate.

	# Model.
	model = Model()
	model.setLogger( Logger.IJ_LOGGER )
	model.setPhysicalUnits( cal.getUnit(), cal.getTimeUnit() )

	# Settings.
	settings = Settings()
	settings.setFrom( imp )

	# Create the TrackMate instance.
	trackmate = TrackMate( model, settings )

	# Add ALL the feature analyzers known to TrackMate, via
	# providers.
	# They offer automatic analyzer detection, so all the
	# available feature analyzers will be added.
	# Some won't make sense on the binary image (e.g. contrast)
	# but nevermind.

	spotAnalyzerProvider = SpotAnalyzerProvider()
	for key in spotAnalyzerProvider.getKeys():
		print( key )
		settings.addSpotAnalyzerFactory( spotAnalyzerProvider.getFactory( key ) )

	edgeAnalyzerProvider = EdgeAnalyzerProvider()
	for  key in edgeAnalyzerProvider.getKeys():
		print( key )
		settings.addEdgeAnalyzer( edgeAnalyzerProvider.getFactory( key ) )

	trackAnalyzerProvider = TrackAnalyzerProvider()
	for key in trackAnalyzerProvider.getKeys():
		print( key )
		settings.addTrackAnalyzer( trackAnalyzerProvider.getFactory( key ) )

	trackmate.getModel().getLogger().log( settings.toStringFeatureAnalyzersInfo() )
	trackmate.computeSpotFeatures( True )
	trackmate.computeEdgeFeatures( True )
	trackmate.computeTrackFeatures( True )

	# Skip detection and get spots from results table.
	spots = spots_from_results_table( results_table, cal.frameInterval )
	model.setSpots( spots, False )

	# Configure detector. We put nothing here, since we already have the spots
	# from previous step.
	settings.detectorFactory = ManualDetectorFactory()
	settings.detectorSettings = {}
	settings.detectorSettings[ 'RADIUS' ] = 1.

	# Configure tracker
	settings.trackerFactory = SparseLAPTrackerFactory()
	settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
	settings.trackerSettings[ 'LINKING_MAX_DISTANCE' ] 		= 10.0
	settings.trackerSettings[ 'GAP_CLOSING_MAX_DISTANCE' ]	= 15.0
	settings.trackerSettings[ 'MAX_FRAME_GAP' ]				= 3
	settings.trackerSettings[ 'ALLOW_TRACK_SPLITTING' ]		= True
	settings.trackerSettings[ 'SPLITTING_MAX_DISTANCE' ]	= 7.0

	settings.trackerSettings

	settings.initialSpotFilterValue = -1.

	### print(model.getFeatureModel().getTrackFeatureNames())
	# TRACK_START: Track start,
	# TRACK_INDEX: Track index,
	# NUMBER_MERGES: Number of merge events,
	# TRACK_STD_SPEED: Velocity standard deviation,
	# TRACK_ID: Track ID,
	# TRACK_MEDIAN_QUALITY: Median quality,
	# TRACK_STD_QUALITY: Quality standard deviation,
	# TRACK_X_LOCATION: X Location (mean),
	# TRACK_MEDIAN_SPEED: Median velocity,
	# NUMBER_SPOTS: Number of spots in track,
	# TRACK_MIN_SPEED: Minimal velocity,
	# NUMBER_GAPS: Number of gaps,
	# TRACK_Z_LOCATION: Z Location (mean),
	# TRACK_STOP: Track stop,
	# TRACK_MEAN_SPEED: Mean velocity,
	# NUMBER_SPLITS: Number of split events,
	# TRACK_MAX_SPEED: Maximal velocity,
	# TRACK_Y_LOCATION: Y Location (mean),
	# TRACK_DISPLACEMENT: Track displacement,
	# NUMBER_COMPLEX: Complex points,
	# TRACK_MEAN_QUALITY: Mean quality,
	# TRACK_DURATION: Duration of track,
	# TRACK_MAX_QUALITY: Maximal quality,
	# LONGEST_GAP: Longest gap,
	# TRACK_MIN_QUALITY: Minimal quality

	settings.addTrackFilter(FeatureFilter('NUMBER_SPLITS', 0.9, True))

	return trackmate
Example #5
0
def magic(file):
    # We have to feed a logger to the reader.
    logger = Logger.IJ_LOGGER

    #-------------------
    # Instantiate reader
    #-------------------

    reader = TmXmlReader(File(file))
    if not reader.isReadingOk():
        sys.exit(reader.getErrorMessage())
    #-----------------
    # Get a full model
    #-----------------

    # This will return a fully working model, with everything
    # stored in the file. Missing fields (e.g. tracks) will be
    # null or None in python
    model = reader.getModel()
    # model is a fiji.plugin.trackmate.Model

    #model = Model()
    #model.setSpots(model2.getSpots(), True)

    #----------------
    # Display results
    #----------------

    # We can now plainly display the model. It will be shown on an
    # empty image with default magnification.
    sm = SelectionModel(model)
    #displayer = HyperStackDisplayer(model, sm)
    #displayer.render()

    #---------------------------------------------
    # Get only part of the data stored in the file
    #---------------------------------------------

    # You might want to access only separate parts of the
    # model.

    spots = model.getSpots()
    # spots is a fiji.plugin.trackmate.SpotCollection

    logger.log(str(spots))

    # If you want to get the tracks, it is a bit trickier.
    # Internally, the tracks are stored as a huge mathematical
    # simple graph, which is what you retrieve from the file.
    # There are methods to rebuild the actual tracks, taking
    # into account for everything, but frankly, if you want to
    # do that it is simpler to go through the model:

    #---------------------------------------
    # Building a settings object from a file
    #---------------------------------------

    # Reading the Settings object is actually currently complicated. The
    # reader wants to initialize properly everything you saved in the file,
    # including the spot, edge, track analyzers, the filters, the detector,
    # the tracker, etc...
    # It can do that, but you must provide the reader with providers, that
    # are able to instantiate the correct TrackMate Java classes from
    # the XML data.

    # We start by creating an empty settings object
    settings = Settings()

    # Then we create all the providers, and point them to the target model:
    detectorProvider        = DetectorProvider()
    trackerProvider         = TrackerProvider()
    spotAnalyzerProvider    = SpotAnalyzerProvider()
    edgeAnalyzerProvider    = EdgeAnalyzerProvider()
    trackAnalyzerProvider   = TrackAnalyzerProvider()

    # Ouf! now we can flesh out our settings object:
    reader.readSettings(settings, detectorProvider, trackerProvider, spotAnalyzerProvider, edgeAnalyzerProvider, trackAnalyzerProvider)
    settings.detectorFactory = ManualDetectorFactory()


    # Configure tracker - We want to allow merges and fusions
    settings.initialSpotFilterValue = 0
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()  # almost good enough
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = True
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = False
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 40.0
    settings.trackerSettings['ALLOW_GAP_CLOSING'] = True
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = True
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 30.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 4

    # Configure track analyzers - Later on we want to filter out tracks
    # based on their displacement, so we need to state that we want
    # track displacement to be calculated. By default, out of the GUI,
    # not features are calculated.

    # The displacement feature is provided by the TrackDurationAnalyzer.

    settings.addTrackAnalyzer(TrackDurationAnalyzer())
    settings.addTrackAnalyzer(TrackBranchingAnalyzer())
    settings.addTrackAnalyzer(TrackIndexAnalyzer())
    settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())
    settings.addTrackAnalyzer(LinearTrackDescriptor())
    # Configure track filters - We want to get rid of the two immobile spots at
    # the bottom right of the image. Track displacement must be above 10 pixels.

    filter2 = FeatureFilter('NUMBER_SPOTS', 31, True)
    settings.addTrackFilter(filter2)
    #filter3 = FeatureFilter('NUMBER_GAPS', 2, False)
    #settings.addTrackFilter(filter3)
    filter4 = FeatureFilter('NUMBER_SPLITS', 0.5, False)
    settings.addTrackFilter(filter4)


    settings.addEdgeAnalyzer(EdgeTargetAnalyzer())
    settings.addEdgeAnalyzer(EdgeTimeLocationAnalyzer())
    settings.addEdgeAnalyzer(EdgeVelocityAnalyzer())
    settings.addEdgeAnalyzer(LinearTrackEdgeStatistics())

    #-------------------
    # Instantiate plugin
    #-------------------
    logger.log(str('\n\nSETTINGS:'))
    logger.log(unicode(settings))
    print("tracking")
    spots = model.getSpots()
    # spots is a fiji.plugin.trackmate.SpotCollection

    logger.log(str(spots))
    logger.log(str(spots.keySet()))


    # The settings object is also instantiated with the target image.
    # Note that the XML file only stores a link to the image.
    # If the link is not valid, the image will not be found.
    #imp = settings.imp
    #imp.show()

    # With this, we can overlay the model and the source image:

    trackmate = TrackMate(model, settings)

    #--------
    # Process
    #--------

    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    trackmate.execInitialSpotFiltering()
    trackmate.execSpotFiltering(True)
    trackmate.execTracking()
    trackmate.computeTrackFeatures(True)
    trackmate.execTrackFiltering(True)
    trackmate.computeEdgeFeatures(True)

    outfile = TmXmlWriter(File(str(file[:-4] + ".trackmate.xml")))
    outfile.appendSettings(settings)
    outfile.appendModel(model)
    outfile.writeToFile()

    ISBIChallengeExporter.exportToFile(model, settings, File(str(file[:-4] + ".ISBI.xml")))
Example #6
0
def create_trackmate(imp, results_table):
    """
    Creates a TrackMate instance configured to operated on the specified
    ImagePlus imp with cell analysis stored in the specified ResultsTable
    results_table.
    """

    cal = imp.getCalibration()

    # TrackMate.

    # Model.
    model = Model()
    model.setLogger(Logger.IJ_LOGGER)
    model.setPhysicalUnits(cal.getUnit(), cal.getTimeUnit())

    # Settings.
    settings = Settings()
    settings.setFrom(imp)

    # Create the TrackMate instance.
    trackmate = TrackMate(model, settings)

    # Add ALL the feature analyzers known to TrackMate, via
    # providers.
    # They offer automatic analyzer detection, so all the
    # available feature analyzers will be added.
    # Some won't make sense on the binary image (e.g. contrast)
    # but nevermind.

    spotAnalyzerProvider = SpotAnalyzerProvider()
    for key in spotAnalyzerProvider.getKeys():
        print(key)
        settings.addSpotAnalyzerFactory(spotAnalyzerProvider.getFactory(key))

    edgeAnalyzerProvider = EdgeAnalyzerProvider()
    for key in edgeAnalyzerProvider.getKeys():
        print(key)
        settings.addEdgeAnalyzer(edgeAnalyzerProvider.getFactory(key))

    trackAnalyzerProvider = TrackAnalyzerProvider()
    for key in trackAnalyzerProvider.getKeys():
        print(key)
        settings.addTrackAnalyzer(trackAnalyzerProvider.getFactory(key))

    trackmate.getModel().getLogger().log(
        settings.toStringFeatureAnalyzersInfo())
    trackmate.computeSpotFeatures(True)
    trackmate.computeEdgeFeatures(True)
    trackmate.computeTrackFeatures(True)

    # Skip detection and get spots from results table.
    spots = spots_from_results_table(results_table, cal.frameInterval)
    model.setSpots(spots, False)

    # Configure detector. We put nothing here, since we already have the spots
    # from previous step.
    settings.detectorFactory = ManualDetectorFactory()
    settings.detectorSettings = {}
    settings.detectorSettings['RADIUS'] = 1.

    # Configure tracker
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 20.0
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 20.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 3

    settings.initialSpotFilterValue = -1.

    return trackmate
Example #7
0
 model = Model()  # set tracking model factories
 settings = Settings()
 settings.setFrom(imp)
 settings.detectorFactory = DogDetectorFactory()
 settings.detectorSettings[
     'DO_SUBPIXEL_LOCALIZATION'] = True  # do subpixel localization
 settings.detectorSettings['RADIUS'] = radius  # set blob radius
 settings.detectorSettings['TARGET_CHANNEL'] = 1  # set target channel
 settings.detectorSettings[
     'THRESHOLD'] = 1.0  # set detection threshold to one to exclude region outside mask
 settings.detectorSettings[
     'DO_MEDIAN_FILTERING'] = True  # do median filtering
 settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
 settings.addSpotAnalyzerFactory(SpotRadiusEstimatorFactory())
 settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())
 settings.initialSpotFilterValue = quality
 settings.addSpotFilter(FeatureFilter('QUALITY', quality, True))
 settings.trackerFactory = SparseLAPTrackerFactory()
 settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
 settings.addEdgeAnalyzer(EdgeTargetAnalyzer())
 settings.addEdgeAnalyzer(EdgeVelocityAnalyzer())
 settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())
 settings.addTrackAnalyzer(TrackDurationAnalyzer())
 settings.addTrackAnalyzer(TrackIndexAnalyzer())
 settings.addTrackAnalyzer(TrackLocationAnalyzer())
 settings.trackerSettings[
     'LINKING_MAX_DISTANCE'] = distL  # set maximum linkage
 settings.trackerSettings[
     'GAP_CLOSING_MAX_DISTANCE'] = distF  # maximum gap-closing distance in pixels
 settings.trackerSettings[
     'MAX_FRAME_GAP'] = distG  # maximum frame gap number in pixels
Example #8
0
def runTrackMate(imp):
    import fiji.plugin.trackmate.Settings as Settings
    import fiji.plugin.trackmate.Model as Model
    import fiji.plugin.trackmate.SelectionModel as SelectionModel
    import fiji.plugin.trackmate.TrackMate as TrackMate
    import fiji.plugin.trackmate.Logger as Logger
    import fiji.plugin.trackmate.detection.DetectorKeys as DetectorKeys
    import fiji.plugin.trackmate.detection.DogDetectorFactory as DogDetectorFactory
    import fiji.plugin.trackmate.tracking.sparselap.SparseLAPTrackerFactory as SparseLAPTrackerFactory
    import fiji.plugin.trackmate.tracking.LAPUtils as LAPUtils
    import fiji.plugin.trackmate.visualization.hyperstack.HyperStackDisplayer as HyperStackDisplayer
    import fiji.plugin.trackmate.features.FeatureFilter as FeatureFilter
    import fiji.plugin.trackmate.features.FeatureAnalyzer as FeatureAnalyzer
    import fiji.plugin.trackmate.features.spot.SpotContrastAndSNRAnalyzerFactory as SpotContrastAndSNRAnalyzerFactory
    import fiji.plugin.trackmate.action.ExportStatsToIJAction as ExportStatsToIJAction
    import fiji.plugin.trackmate.io.TmXmlReader as TmXmlReader
    import fiji.plugin.trackmate.action.ExportTracksToXML as ExportTracksToXML
    import fiji.plugin.trackmate.io.TmXmlWriter as TmXmlWriter
    import fiji.plugin.trackmate.features.ModelFeatureUpdater as ModelFeatureUpdater
    import fiji.plugin.trackmate.features.SpotFeatureCalculator as SpotFeatureCalculator
    import fiji.plugin.trackmate.features.spot.SpotContrastAndSNRAnalyzer as SpotContrastAndSNRAnalyzer
    import fiji.plugin.trackmate.features.spot.SpotIntensityAnalyzerFactory as SpotIntensityAnalyzerFactory
    import fiji.plugin.trackmate.features.track.TrackSpeedStatisticsAnalyzer as TrackSpeedStatisticsAnalyzer
    import fiji.plugin.trackmate.util.TMUtils as TMUtils
    import fiji.plugin.trackmate.visualization.trackscheme.TrackScheme as TrackScheme
    import fiji.plugin.trackmate.visualization.PerTrackFeatureColorGenerator as PerTrackFeatureColorGenerator

    #-------------------------
    # Instantiate model object
    #-------------------------

    nFrames = imp.getNFrames()
    model = Model()

    # Set logger
    #model.setLogger(Logger.IJ_LOGGER)

    #------------------------
    # Prepare settings object
    #------------------------

    settings = Settings()
    settings.setFrom(imp)

    # Configure detector
    settings.detectorFactory = DogDetectorFactory()
    settings.detectorSettings = {
        DetectorKeys.KEY_DO_SUBPIXEL_LOCALIZATION: True,
        DetectorKeys.KEY_RADIUS: 12.30,
        DetectorKeys.KEY_TARGET_CHANNEL: 1,
        DetectorKeys.KEY_THRESHOLD: 100.,
        DetectorKeys.KEY_DO_MEDIAN_FILTERING: False,
    }

    # Configure tracker
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 10.0
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 10.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 3

    # Add the analyzers for some spot features.
    # You need to configure TrackMate with analyzers that will generate
    # the data you need.
    # Here we just add two analyzers for spot, one that computes generic
    # pixel intensity statistics (mean, max, etc...) and one that computes
    # an estimate of each spot's SNR.
    # The trick here is that the second one requires the first one to be in
    # place. Be aware of this kind of gotchas, and read the docs.
    settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())

    # Add an analyzer for some track features, such as the track mean speed.
    settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())

    settings.initialSpotFilterValue = 1

    print(str(settings))

    #----------------------
    # Instantiate trackmate
    #----------------------

    trackmate = TrackMate(model, settings)

    #------------
    # Execute all
    #------------

    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    ok = trackmate.process()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    #----------------
    # Display results
    #----------------

    selectionModel = SelectionModel(model)
    displayer = HyperStackDisplayer(model, selectionModel, imp)
    displayer.render()
    displayer.refresh()

    #---------------------
    # Select correct spots
    #---------------------

    # Prepare display.
    sm = SelectionModel(model)
    color = PerTrackFeatureColorGenerator(model, 'TRACK_INDEX')

    # launch TrackScheme to select spots and tracks
    trackscheme = TrackScheme(model, sm)
    trackscheme.setDisplaySettings('TrackColoring', color)
    trackscheme.render()

    # Update image with TrackScheme commands
    view = HyperStackDisplayer(model, sm, imp)
    view.setDisplaySettings('TrackColoring', color)
    view.render()

    # Wait for the user to select correct spots and tracks before collecting data
    dialog = WaitForUserDialog(
        "Spots",
        "Delete incorrect spots and edit tracks if necessary. (Press ESC to cancel analysis)"
    )
    dialog.show()
    if dialog.escPressed():
        IJ.run("Remove Overlay", "")
        imp.close()
        return ([], nFrames)

    # The feature model, that stores edge and track features.
    #model.getLogger().log('Found ' + str(model.getTrackModel().nTracks(True)) + ' tracks.')
    fm = model.getFeatureModel()
    crds_perSpot = []
    for id in model.getTrackModel().trackIDs(True):

        # Fetch the track feature from the feature model.(remove """ to enable)
        """v = fm.getTrackFeature(id, 'TRACK_MEAN_SPEED')
	    model.getLogger().log('')
	    model.getLogger().log('Track ' + str(id) + ': mean velocity = ' + str(v) + ' ' + model.getSpaceUnits() + '/' + model.getTimeUnits())"""
        trackID = str(id)
        track = model.getTrackModel().trackSpots(id)

        spot_track = {}
        for spot in track:
            sid = spot.ID()
            # Fetch spot features directly from spot.
            x = spot.getFeature('POSITION_X')
            y = spot.getFeature('POSITION_Y')
            t = spot.getFeature('FRAME')
            q = spot.getFeature('QUALITY')
            snr = spot.getFeature('SNR')
            mean = spot.getFeature('MEAN_INTENSITY')
            #model.getLogger().log('\tspot ID = ' + str(sid) + ', x='+str(x)+', y='+str(y)+', t='+str(t)+', q='+str(q) + ', snr='+str(snr) + ', mean = ' + str(mean))
            spot_track[t] = (x, y)
        crds_perSpot.append(spot_track)
        #print ("Spot", crds_perSpot.index(spot_track),"has the following coordinates:", crds_perSpot[crds_perSpot.index(spot_track)])
    return (crds_perSpot, nFrames)
Example #9
0
def track_cells(folder_w, filename, imp, correction):
    #imp = IJ.openImage(os.path.join(folder,filename))
    #imp.show()

    #get image dimensions, set ROI remove part of flouresncent ring
    x_size = ImagePlus.getDimensions(imp)[0]
    y_size = ImagePlus.getDimensions(imp)[1]
    x_start = 0
    y_start = 0
    #calculate alternative ROI
    if crop_ring:
        x_start = 170 / 2
        y_start = 170 / 2
        x_size = x_size - 170
        y_size = y_size - 170
    print(
        str(x_start) + ", " + str(y_start) + ", " + str(x_size) + ", " +
        str(y_size))
    imp.setRoi(OvalRoi(x_start, y_start, x_size, y_size))
    #imp_dup = imp.duplicate()
    #imp_dup.show()
    #red_corrected_img.show()

    IJ.run(imp, "Make Inverse", "")
    IJ.setForegroundColor(0, 0, 0)
    IJ.run(imp, "Fill", "stack")
    imp.killRoi()

    #imp.show()
    #sys.exit()

    #img_filename = filename+"_corrected_red_stack.tif"
    #folder_filename= os.path.join(well_folder,img_filename)
    #IJ.save(imp, folder_filename)

    #----------------------------
    # Create the model object now
    #----------------------------

    # Some of the parameters we configure below need to have
    # a reference to the model at creation. So we create an
    # empty model now.

    model = Model()

    # Send all messages to ImageJ log window.
    model.setLogger(Logger.IJ_LOGGER)

    #------------------------
    # Prepare settings object
    #------------------------

    settings = Settings()
    settings.setFrom(imp)

    # Configure detector - We use the Strings for the keys
    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': SUBPIXEL_LOCALIZATION,
        'RADIUS': RADIUS,
        'TARGET_CHANNEL': TARGET_CHANNEL,
        'THRESHOLD': THRESHOLD,
        'DO_MEDIAN_FILTERING': MEDIAN_FILTERING,
    }

    # Configure spot filters - Classical filter on quality
    settings.initialSpotFilterValue = SPOT_FILTER
    settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotMorphologyAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotRadiusEstimatorFactory())

    filter1 = FeatureFilter('QUALITY', QUALITY, True)
    filter2 = FeatureFilter('CONTRAST', CONTRAST, True)
    filter2a = FeatureFilter('ESTIMATED_DIAMETER', MAX_ESTIMATED_DIAMETER,
                             False)
    filter2b = FeatureFilter('MEDIAN_INTENSITY', MAX_MEDIAN_INTENSITY, False)

    settings.addSpotFilter(filter1)
    settings.addSpotFilter(filter2)
    settings.addSpotFilter(filter2a)
    settings.addSpotFilter(filter2b)
    print(settings.spotFilters)

    # Configure tracker - We want to allow merges and fusions
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
    )  # almost good enough

    ##adapted from https://forum.image.sc/t/trackmate-scripting-automatically-exporting-spots-in-tracks-links-in-tracks-tracks-statistics-and-branching-analysis-to-csv/6256
    #linking settings
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = LINKING_MAX_DISTANCE
    if LINKING_FEATURE_PENALTIES == True:
        settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = {
            LINKING_FEATURE_PENALTIES_TYPE: LINKING_FEATURE_PENALTIES_VALUE
        }
    else:
        settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = {}

    #gap closing settings
    settings.trackerSettings['ALLOW_GAP_CLOSING'] = ALLOW_GAP_CLOSING
    if ALLOW_GAP_CLOSING == True:
        settings.trackerSettings[
            'GAP_CLOSING_MAX_DISTANCE'] = GAP_CLOSING_MAX_DISTANCE
        settings.trackerSettings['MAX_FRAME_GAP'] = MAX_FRAME_GAP
        if GAP_CLOSING_FEATURE_PENALTIES == True:
            settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = {
                GAP_CLOSING_FEATURE_PENALTIES_TYPE:
                GAP_CLOSING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = {}

    #splitting settings
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = ALLOW_TRACK_SPLITTING
    if ALLOW_TRACK_SPLITTING == True:
        settings.trackerSettings[
            'SPLITTING_MAX_DISTANCE'] = SPLITTING_MAX_DISTANCE
        if SPLITTING_FEATURE_PENALTIES == True:
            settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = {
                SPLITTING_FEATURE_PENALTIES_TYPE:
                SPLITTING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = {}

    #merging settings
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = ALLOW_TRACK_MERGING
    if ALLOW_TRACK_MERGING == True:
        settings.trackerSettings['MERGING_MAX_DISTANCE'] = MERGING_MAX_DISTANCE
        if MERGING_FEATURE_PENALTIES == True:
            settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = {
                MERGING_FEATURE_PENALTIES_TYPE: MERGING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = {}

    print(settings.trackerSettings)

    # Configure track analyzers - Later on we want to filter out tracks
    # based on their displacement, so we need to state that we want
    # track displacement to be calculated. By default, out of the GUI,
    # not features are calculated.

    # The displacement feature is provided by the TrackDurationAnalyzer.

    settings.addTrackAnalyzer(TrackDurationAnalyzer())
    settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer())

    # Configure track filters - We want to get rid of the two immobile spots at
    # the bottom right of the image. Track displacement must be above 10 pixels.

    filter3 = FeatureFilter('TRACK_DISPLACEMENT', TRACK_DISPLACEMENT, True)
    filter4 = FeatureFilter('TRACK_START', TRACK_START, False)
    #filter5 = FeatureFilter('TRACK_STOP', float(imp.getStack().getSize())-1.1, True)

    settings.addTrackFilter(filter3)
    settings.addTrackFilter(filter4)
    #settings.addTrackFilter(filter5)

    #-------------------
    # Instantiate plugin
    #-------------------

    trackmate = TrackMate(model, settings)

    #--------
    # Process
    #--------

    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    ok = trackmate.process()

    #	if not ok:
    #sys.exit(str(trackmate.getErrorMessage()))

    #----------------
    # Display results
    #----------------

    #Set output folder and filename and create output folder
    well_folder = os.path.join(folder_w, filename)
    output_folder = os.path.join(well_folder, "Tracking")
    create_folder(output_folder)
    xml_file_name = filename + "_" + correction + "_trackmate_analysis.xml"
    folder_filename_xml = os.path.join(output_folder, xml_file_name)

    #ExportTracksToXML.export(model, settings, File(folder_filename_xml))
    outfile = TmXmlWriter(File(folder_filename_xml))
    outfile.appendSettings(settings)
    outfile.appendModel(model)
    outfile.writeToFile()

    # Echo results with the logger we set at start:
    #model.getLogger().log(str(model))

    #create araray of timepoint length with filled 0
    cell_counts = zerolistmaker(imp.getStack().getSize())
    if ok:
        for id in model.getTrackModel().trackIDs(True):
            # Fetch the track feature from the feature model.
            track = model.getTrackModel().trackSpots(id)
            for spot in track:
                # Fetch spot features directly from spot.
                t = spot.getFeature('FRAME')
                print(t)
                cell_counts[int(t)] = cell_counts[int(t)] + 1
    else:
        print("No spots detected!")

    if HEADLESS == False:
        selectionModel = SelectionModel(model)
        displayer = HyperStackDisplayer(model, selectionModel, imp)
        displayer.render()
        displayer.refresh()
    del imp
    return (cell_counts + [len(model.getTrackModel().trackIDs(True))])