Exemplo n.º 1
0
#---------------------------------------

# 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.

# 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)

#Modiy core parameters

settings.trackerSettings['MAX_FRAME_GAP'] = MAX_FRAME_GAP
settings.trackerSettings['KALMAN_SEARCH_RADIUS'] = KALMAN_SEARCH_RADIUS
settings.trackerSettings['LINKING_MAX_DISTANCE'] = LINKING_MAX_DISTANCE
"""
settings.detectorSettings = { 
    'DO_SUBPIXEL_LOCALIZATION' :  DO_SUBPIXEL_LOCALIZATION,
    'RADIUS' : RADIUS,
Exemplo n.º 2
0
                # They offer automatic analyzer detection, so all the
                # available feature analyzers will be added.

                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))

                # Configure track filters - track should start before frame 5
                track_filter = FeatureFilter('TRACK_START', track_start, False)
                settings.addTrackFilter(track_filter)

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

                trackmate = TrackMate(model, settings)
Exemplo n.º 3
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
Exemplo n.º 4
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")))
Exemplo n.º 5
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
    # Add ALL the feature analyzers known to TrackMate, via
    # providers.
    # They offer automatic analyzer detection, so all the
    # available feature analyzers will be added.

    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))

    # Configure track filters - track should start before frame 5
    track_filter = FeatureFilter('TRACK_START', track_start, False)
    settings.addTrackFilter(track_filter)

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

    trackmate = TrackMate(model, settings)

    #--------
Exemplo n.º 7
0
def TrackMate_main(infile, outfile):
    file = File(infile)

    # We have to feed a logger to the reader.
    logger = Logger.IJ_LOGGER

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

    reader = TmXmlReader(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.setLogger(Logger.IJ_LOGGER)
    # model is a fiji.plugin.trackmate.Model

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

    # 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()

    reader.readSettings(settings, detectorProvider, trackerProvider,
                        spotAnalyzerProvider, edgeAnalyzerProvider,
                        trackAnalyzerProvider)

    #----------------
    # Save results
    #----------------

    # The feature model, that stores edge and track features.
    fm = model.getFeatureModel()

    f = open(outfile, 'wb')

    for id in model.getTrackModel().trackIDs(True):
        track = model.getTrackModel().trackSpots(id)
        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')

            semiaxislength_c = spot.getFeature('ELLIPSOIDFIT_SEMIAXISLENGTH_C')
            if semiaxislength_c is None:
                semiaxislength_c = 0

            semiaxislength_b = spot.getFeature('ELLIPSOIDFIT_SEMIAXISLENGTH_B')
            if semiaxislength_b is None:
                semiaxislength_b = 0

            phi_b = spot.getFeature('ELLIPSOIDFIT_AXISPHI_B')
            if phi_b is None:
                phi_b = 0

            data = Array.newInstance(Class.forName("java.lang.String"), 9)
            #String[] entries = "first#second#third".split("#");
            data[0] = str(sid)
            data[1] = str(id)
            data[2] = str(x)
            data[3] = str(y)
            data[4] = str(t)
            data[5] = str(semiaxislength_c)
            data[6] = str(semiaxislength_b)
            data[7] = str(phi_b)
            data[8] = str(mean)

            # create csv writer
            writer = csv.writer(f)

            row = [
                data[0], data[1], data[2], data[3], data[4], data[5], data[6],
                data[7], data[8]
            ]
            writer.writerow(row)

    f.close()
    print('Saved ' + str(model.getTrackModel().nTracks(True)) + ' tracks.')
def track_single_batch(path, filename):
    # Get currently selected image
    imp = WindowManager.getCurrentImage()
    # imp = IJ.openImage('https://fiji.sc/samples/FakeTracks.tif')
    imp.show()

    #----------------------------
    # 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.detectorFactory = BlockLogDetectorFactory()
    print
    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': True,
        'RADIUS': 7.5,
        'TARGET_CHANNEL': 1,
        'THRESHOLD': 0.25,
        'DO_MEDIAN_FILTERING': False,
        'NSPLIT': 3,
    }

    # Configure spot filters - Classical filter on quality
    filter1 = FeatureFilter('QUALITY', 0.1, True)  # in higher SNR;
    settings.addSpotFilter(filter1)

    # Configure tracker - We want to allow merges and fusions
    settings.trackerFactory = SparseLAPTrackerFactory()
    #settings.trackerFactory = LAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
    )  # almost good enough
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = True
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = True
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 15.0
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 15.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 5

    # feature

    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))

    #filter2 = FeatureFilter('TRACK_DISPLACEMENT', 3, True)
    #settings.addTrackFilter(filter2)

    # processing
    trackmate = TrackMate(model, settings)
    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    try:
        ok = trackmate.process()
    except:
        IJ.log("Nothing detected")
    else:
        selectionModel = SelectionModel(model)
        displayer = HyperStackDisplayer(model, selectionModel, imp)
        displayer.render()
        displayer.refresh()

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

    save_path = os.path.join(path, 'result')
    if not os.path.exists(save_path):
        os.mkdir(save_path, 0755)
    outFile = File(save_path, filename)
    ExportTracksToXML.export(model, settings, outFile)
    imp.close()