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)
Пример #2
0
def runTrackMate(imp, targetChannel, dt, radius, threshold, frameGap,
                 linkingMax, closingMax):
    # Get the number of channels
    nChannels = imp.getNChannels()
    IJ.log("->Detection threshold used: " + str(threshold))
    IJ.log("->Number of frames is: " + str(imp.getStackSize()))
    IJ.log("->Target channel is: " + str(targetChannel))
    IJ.log('->Number of channels to measure %d' % nChannels)
    # Setup settings for TrackMate
    settings = Settings()
    settings.setFrom(imp)
    settings.dt = dt

    # Spot analyzer: we want the multi-C intensity analyzer.
    settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory())

    # Spot detector.
    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = settings.detectorFactory.getDefaultSettings()
    settings.detectorSettings['RADIUS'] = radius
    settings.detectorSettings['THRESHOLD'] = threshold
    settings.detectorSettings['TARGET_CHANNEL'] = targetChannel

    # Spot tracker.
    #settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerFactory = LAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
    settings.trackerSettings['MAX_FRAME_GAP'] = frameGap
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = linkingMax
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = closingMax
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = False

    settings.trackerSettings['ALLOW_GAP_CLOSING'] = False
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = False
    settings.trackerSettings['ALTERNATIVE_LINKING_COST_FACTOR'] = 0.5
    settings.trackerSettings['BLOCKING_VALUE'] = 1.0
    settings.trackerSettings['CUTOFF_PERCENTILE'] = 1.0

    #settings.trackerSettings['SPLITTING_MAX_DISTANCE'] = 16.0
    # Run TrackMate and store data into Model.

    model = Model()
    trackmate = TrackMate(model, settings)

    if not trackmate.checkInput() or not trackmate.process():
        IJ.log('Could not execute TrackMate: ' +
               str(trackmate.getErrorMessage()))
    else:
        return model, nChannels
Пример #3
0
# 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': True,
    'RADIUS': 2.5,
    'TARGET_CHANNEL': 1,
    'THRESHOLD': 0.,
    'DO_MEDIAN_FILTERING': False,
}

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

# Configure tracker - We want to allow merges and fusions
settings.trackerFactory = SparseLAPTrackerFactory()
settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
Пример #4
0
def track(imp):

    from fiji.plugin.trackmate import Model
    from fiji.plugin.trackmate import Settings
    from fiji.plugin.trackmate import TrackMate
    from fiji.plugin.trackmate import SelectionModel
    from fiji.plugin.trackmate import Logger
    from fiji.plugin.trackmate.detection import LogDetectorFactory
    from fiji.plugin.trackmate.tracking.sparselap import SparseLAPTrackerFactory
    from fiji.plugin.trackmate.tracking import LAPUtils
    from ij import IJ
    import fiji.plugin.trackmate.visualization.hyperstack.HyperStackDisplayer as HyperStackDisplayer
    import fiji.plugin.trackmate.features.FeatureFilter as FeatureFilter
    import sys
    import fiji.plugin.trackmate.features.track.TrackDurationAnalyzer as TrackDurationAnalyzer

    # Get currently selected image
    #imp = WindowManager.getCurrentImage()
    #imp = IJ.openImage('http://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.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': True,
        'RADIUS': 3.0,
        'TARGET_CHANNEL': 1,
        'THRESHOLD': 1.,
        'DO_MEDIAN_FILTERING': False,
    }

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

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

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

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

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

    fm = model.getFeatureModel()
    norm_x = []
    norm_y = []
    for id in model.getTrackModel().trackIDs(True):
        track = model.getTrackModel().trackSpots(id)
        for spot in track:
            t = spot.getFeature('FRAME')

            if (t == 0.0):
                min_x = spot.getFeature('POSITION_X')
                min_y = spot.getFeature('POSITION_Y')
        for spot in track:

            norm_x.append(spot.getFeature('POSITION_X') - min_x)
            norm_y.append(spot.getFeature('POSITION_Y') - min_y)

    max_x = abs(max(norm_x, key=abs))
    max_y = abs(max(norm_y, key=abs))

    return max_x, max_y
Пример #5
0
def track():
    imp = IJ.getImage()
    nChannels = imp.getNChannels()  # Get the number of channels 
    orgtitle = imp.getTitle()
    IJ.run("Subtract Background...", "rolling=50 sliding stack")
    IJ.run("Enhance Contrast...", "saturated=0.3")
    IJ.run("Multiply...", "value=10 stack")
    IJ.run("Subtract Background...", "rolling=50 sliding stack")
    IJ.run("Set Scale...", "distance=0")
    
    channels = ChannelSplitter.split(imp)
    imp_GFP = channels[0]
    imp_RFP = channels[1]
    IJ.selectWindow(orgtitle)
    IJ.run("Close")
    ic = ImageCalculator()
    imp_merge = ic.run("Add create stack", imp_GFP, imp_RFP)
    imp_merge.setTitle("add_channels")
    imp_merge.show()
    imp_RFP.show()
    imp_GFP.show()
    
    imp5 = ImagePlus()
    IJ.run(imp5, "Merge Channels...", "c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create")
    print("c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create")
    imp5.show()
    imp5 = IJ.getImage()
    
    nChannels = imp5.getNChannels()
    # Setup settings for TrackMate
    settings = Settings()
    settings.setFrom(imp5)
    
    # Spot analyzer: we want the multi-C intensity analyzer.
    settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory())   

    # Spot detector.
    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = settings.detectorFactory.getDefaultSettings()
    settings.detectorSettings['TARGET_CHANNEL'] = 1
    settings.detectorSettings['RADIUS'] = 24.0
    settings.detectorSettings['THRESHOLD'] = 0.0
    
    # Spot tracker.
    # Configure tracker - We don't want to allow merges or splits
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() # almost good enough
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = False
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 8.0
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 8.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 1
    
    # Configure track filters
    settings.addTrackAnalyzer(TrackDurationAnalyzer())
    settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer())
    
    filter1 = FeatureFilter('TRACK_DURATION', 20, True)
    settings.addTrackFilter(filter1)
    
    # Run TrackMate and store data into Model.
    model = Model()
    trackmate = TrackMate(model, settings)
    
    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))
            
    ok = trackmate.process()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))
    
    selectionModel = SelectionModel(model)
    displayer =  HyperStackDisplayer(model, selectionModel, imp5)
    displayer.render()
    displayer.refresh()
    
    IJ.log('TrackMate completed successfully.')
    IJ.log('Found %d spots in %d tracks.' % (model.getSpots().getNSpots(True) , model.getTrackModel().nTracks(True)))
    
    # Print results in the console.
    headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z')
    rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f'
    for i in range( nChannels ):
        headerStr += (' %10s' % ( 'C' + str(i+1) ) )
        rowStr += ( ' %10.1f' )
    
    #open a file to save results
    myfile = open('/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMECBMELVA_20X_01122019/data/'+orgtitle.split('.')[0]+'.csv', 'wb')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(['Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z', 'Channel_1', 'Channel_2'])
    
    IJ.log('\n')
    IJ.log(headerStr)
    tm = model.getTrackModel()
    trackIDs = tm.trackIDs(True)
    for trackID in trackIDs:
        spots = tm.trackSpots(trackID)
    
        # Let's sort them by frame.
        ls = ArrayList(spots)
        
        for spot in ls:
            values = [spot.ID(), trackID, spot.getFeature('FRAME'), \
                spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')]
            for i in range(nChannels):
                values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1)))
                
            IJ.log(rowStr % tuple(values))
            l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8])
            wr.writerow(l1)
    
    myfile.close()
    IJ.selectWindow("Merged")
    IJ.run("Close")
Пример #6
0
 
import fiji.plugin.trackmate.action.ExportTracksToXML
 
 
# Swap Z and T dimensions if T=1
dims = imp.getDimensions() # default order: XYCZT
if (dims[4] == 1) {
    imp.setDimensions( dims[2,4,3] )
}
 
# Setup settings for TrackMate
settings = new Settings()
settings.setFrom(imp)
settings.dt = 0.05
 
settings.detectorFactory = new LogDetectorFactory()
settings.detectorSettings = settings.detectorFactory.getDefaultSettings()
println settings.detectorSettings
 
settings.detectorSettings['RADIUS'] = radius
settings.detectorSettings['THRESHOLD'] = threshold
println settings.detectorSettings
 
settings.trackerFactory = new SparseLAPTrackerFactory()
settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
 


settings.trackerSettings['MAX_FRAME_GAP']  = frameGap
settings.trackerSettings['LINKING_MAX_DISTANCE']  = linkingMax
settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE']  = closingMax
Пример #7
0
def run_trackmate(
    imp, path_out="./", detector="log", radius=2.5, threshold=0.0, median_filter=False
):
    """Log Trackmate detection run with given parameters.
    Saves spots in a csv file in the given path_out with encoded parameters.

    Args:
        imp: ImagePlus to be processed
        path_out: Output directory to save files.
        detector: Type of detection method. Options are 'log', 'dog'.
        radius: Radius of spots in pixels.
        threshold: Threshold value to filter spots.
        median_filter: True if median_filtering should be used.
    """
    if imp.dimensions[2] != 1:
        raise ValueError(
            "Imp's dimensions must be [n, n, 1] but are " + imp.dimensions[2]
        )

    # Create the model object now
    model = Model()
    model.setLogger(Logger.VOID_LOGGER)

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

    # Configure detector
    settings.detectorFactory = (
        DogDetectorFactory() if detector == "dog" else LogDetectorFactory()
    )
    settings.detectorSettings = {
        "DO_SUBPIXEL_LOCALIZATION": True,
        "RADIUS": radius,
        "TARGET_CHANNEL": 1,
        "THRESHOLD": threshold,
        "DO_MEDIAN_FILTERING": median_filter,
    }

    # Instantiate plugin
    trackmate = TrackMate(model, settings)

    # Process
    # output = trackmate.process()
    output = trackmate.execDetection()
    if not output:
        print("error process")
        return None

    # Get output from a single image
    fname = str(imp.title)
    spots = [["fname", "detector", "radius", "threshold", "median", "x", "y", "q"]]
    for spot in model.spots.iterator(0):
        x = spot.getFeature("POSITION_X")
        y = spot.getFeature("POSITION_Y")
        q = spot.getFeature("QUALITY")
        spots.append([fname, detector, radius, threshold, median_filter, x, y, q])

    # Save output
    outname = os.path.splitext(os.path.basename(fname))[0] + "_" + str(radius) + ".csv"
    with open(os.path.join(path_out, outname), "wb") as f:
        wr = csv.writer(f)
        for row in spots:
            wr.writerow(row)
Пример #8
0
def run_process(input_path, output_path):

    IJ.run("Image Sequence...", "open=[" + input_path + "] convert sort")
    imp = WindowManager.getCurrentImage()
    dims = imp.getDimensions()
    imp.setDimensions(dims[2], dims[4], dims[3])
    dims = imp.getDimensions()
    ImageConverter(imp).convertToGray8()

    model = Model()
    model.setLogger(Logger.IJ_LOGGER)

    settings = Settings()
    settings.setFrom(imp)

    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': True,
        'RADIUS': float(11.0),
        'THRESHOLD': float(0.0),
        'DO_MEDIAN_FILTERING': True
    }

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

    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
    )  #this sets tens of madatory settings
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = 15.0
    settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 15.0
    settings.trackerSettings['MAX_FRAME_GAP'] = 2
    #	print(LAPUtils.getDefaultLAPSettingsMap())

    #
    #	settings.trackerFactory = SimpleLAPTrackerFactory()
    ##	settings.trackerSettings = LAPUtils.SimpleLAPTrackerFactory() #this sets tens of madatory settings
    #	settings.trackerSettings['LINKING_MAX_DISTANCE'] = 15.0
    #	settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE']=15.0
    #	settings.trackerSettings['MAX_FRAME_GAP']= 2
    #	settings.trackerSettings['ALLOW_GAP_CLOSING']= True
    #	settings.trackerSettings['ALLOW_TRACK_SPLITTING']= False
    #	settings.trackerSettings['ALLOW_TRACK_MERGING']= False
    #	settings.trackerSettings['SPLITTING_MAX_DISTANCE']= 1000.0
    #	settings.trackerSettings['MERGING_MAX_DISTANCE']= 1000.0
    #	settings.trackerSettings['ALTERNATIVE_LINKING_COST_FACTOR']= 1000.0
    #	# ?
    #	settings.trackerSettings['CUTOFF_PERCENTILE']= 1000.0
    #	settings.trackerSettings['BLOCKING_VALUE']= 1000.0
    #
    #	filter2 = FeatureFilter('NUMBER_OF_SPOTS_IN_TRACK', 6.86, True)
    #	settings.addTrackFilter(filter2)

    trackmate = TrackMate(model, settings)

    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))
        raise Exception("trackmate: checkInput failed")

    # if ok:
    # 	print("Input ok")

    ok = trackmate.process()
    if not ok:
        raise Exception("trackmate: process failed")

    # if ok:
    # 	print("Process ok")
    #----------------
    # Display results
    #----------------

    model.getLogger().log('Found ' + str(model.getTrackModel().nTracks(True)) +
                          ' tracks.')

    selectionModel = SelectionModel(model)

    displayer = HyperStackDisplayer(model, selectionModel, imp)

    #	displayer.render()

    # The feature model, that stores edge and track features.
    fm = model.getFeatureModel()
    # print(fm)
    labels_row = [
        'id', 'spot_id', 'x', 'y', 'frame', 'quality', 'type', 'length'
    ]
    #'qualitiy','visability', 'track_length']
    #rows = []
    track_ids = model.getTrackModel().trackIDs(True)
    with open(output_path, 'w') as file:
        writer = csv.writer(file)
        writer.writerow(labels_row)
        for id in track_ids:
            # Fetch the track feature from the feature model.
            #			model.getLogger().log('')
            #			model.getLogger().log('Track ' + str(id) + ': mean velocity = ' + str(v) + ' ' + model.getSpaceUnits() + '/' + model.getTimeUnits())
            track = model.getTrackModel().trackSpots(id)
            num_spots = track.size()
            for spot in track:
                #				print(spot.getFeatures())
                row = []
                row.append(id)
                sid = spot.ID()
                row.append(sid)
                # Fetch spot features directly from spot.
                x = spot.getFeature('POSITION_X')
                row.append(x)
                y = spot.getFeature('POSITION_Y')
                row.append(y)
                t = spot.getFeature('FRAME')
                row.append(int(t))
                #			print("x: {} y: {} t: {}".format(x, y, t))
                q = spot.getFeature('QUALITY')
                row.append(q)
                #				snr=spot.getFeature('SNR')
                #				row.append(snr)
                #				mean=spot.getFeature('MEAN_INTENSITY')
                #				row.append(mean)
                # visibility=spot.getFeature('VISIBILITY')
                #				print(visibility)
                #				break
                #				row.append(visability)
                #				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))
                row.append(1)
                row.append(num_spots)
                writer.writerow(row)


#			rows.append(row)
        file.close()
        return IJ
Пример #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))])
Пример #10
0
def run_trackmate(imp, path, filename, params, batch_mode=False):
    # initialize trackmate model
    model = Model()

    # Set logger - use to see outputs, not needed in batch mode
    model.setLogger(Logger.IJ_LOGGER)

    # Create setting object from image
    settings = Settings()
    settings.setFrom(imp)

    cal = imp.getCalibration()
    model.setPhysicalUnits("micron", "sec")

    # Configure detector
    settings.detectorFactory = LogDetectorFactory()
    #    settings.detectorFactory = DogDetectorFactory()

    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': params.do_subpixel_localization,
        'RADIUS': params.radius,
        'TARGET_CHANNEL': 0,
        'THRESHOLD': params.threshold,
        'DO_MEDIAN_FILTERING': params.do_median_filtering,
    }

    #    print(params)

    # Add spot filters
    filter_quality = FeatureFilter('QUALITY', params.quality, True)
    settings.addSpotFilter(filter_quality)
    filter_snr = FeatureFilter('SNR', params.snr, True)
    settings.addSpotFilter(filter_snr)

    # Compute spot features
    settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())

    # Compute track features
    settings.addTrackAnalyzer(TrackBranchingAnalyzer())
    settings.addTrackAnalyzer(TrackDurationAnalyzer())
    settings.addTrackAnalyzer(TrackIndexAnalyzer())
    settings.addTrackAnalyzer(TrackLocationAnalyzer())
    settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())
    settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer())

    # Update model
    ModelFeatureUpdater(model, settings)

    # Configure tracker
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
    settings.trackerSettings[
        'LINKING_MAX_DISTANCE'] = params.linking_max_distance
    settings.trackerSettings[
        'GAP_CLOSING_MAX_DISTANCE'] = params.gap_closing_max_distance
    settings.trackerSettings['MAX_FRAME_GAP'] = params.max_frame_gap

    # Add track filters
    filter_T1 = FeatureFilter('TRACK_DURATION', params.track_duration, True)
    filter_MTD = FeatureFilter('TRACK_DISPLACEMENT', params.track_displacement,
                               True)

    settings.addTrackFilter(filter_T1)
    settings.addTrackFilter(filter_MTD)

    # Instantiate trackmate
    trackmate = TrackMate(model, settings)

    # Execute all

    ok = trackmate.checkInput()
    if not ok:
        IJ.showMessage("No spots found... Adjust detection parameter.\n" +
                       str(trackmate.getErrorMessage()))
        sys.exit(str(trackmate.getErrorMessage()))

    ok = trackmate.process()
    if not ok:
        IJ.showMessage("No spots found... Adjust detection parameter.\n" +
                       str(trackmate.getErrorMessage()))
        sys.exit(str(trackmate.getErrorMessage()))

    filename = os.path.splitext(filename)[0]  #filename without extension
    outFile = File(os.path.join(path, filename + "_Tracks.xml"))
    ExportTracksToXML.export(model, settings, outFile)
    #imp.close()

    tm_writer = TmXmlWriter(File(os.path.join(path, filename + "_TM.xml")))
    tm_writer.appendModel(model)
    tm_writer.appendSettings(settings)
    tm_writer.writeToFile()

    if not batch_mode:
        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))
Пример #11
0
def getSpots(imp,
             channel,
             detector_type,
             radius,
             threshold,
             overlay,
             roi_type="large",
             roi_color=ColorRGB("blue")):
    """ Performs the detection, adding spots to the image overlay
    :imp:           The image (ImagePlus) being analyzed
    :channel:       The target channel
    :detector_type: A string describing the detector: "LoG" or "DoG"
    :radius:        Spot radius (NB: trackmate GUI accepts diameter)
    :threshold:     Quality cutoff value
    :overlay:       The image overlay to store spot (MultiPoint) ROIs
    :roi_type:      A string describing how spot ROIs should be displayed
    :returns:       The n. of detected spots
    """
    settings = Settings()
    settings.setFrom(imp)
    settings.detectorFactory = (LogDetectorFactory() if "LoG" in detector_type
                                else DogDetectorFactory())
    settings.detectorSettings = {
        DK.KEY_DO_SUBPIXEL_LOCALIZATION: False,
        DK.KEY_DO_MEDIAN_FILTERING: True,
        DK.KEY_TARGET_CHANNEL: channel,
        DK.KEY_RADIUS: radius,
        DK.KEY_THRESHOLD: threshold,
    }
    trackmate = TrackMate(settings)
    if not trackmate.execDetection():
        lservice.error(str(trackmate.getErrorMessage()))
        return 0
    model = trackmate.model
    spots = model.getSpots()
    count = spots.getNSpots(False)
    ch_id = "Spots Ch%d" % channel
    if count > 0:
        roi = None
        cal = imp.getCalibration()
        t_pos = imp.getT()
        if (t_pos > 1):
            lservice.warn("Only frame %d was considered..." % t_pos)
        for spot in spots.iterable(False):
            x = cal.getRawX(spot.getFeature(spot.POSITION_X))
            y = cal.getRawY(spot.getFeature(spot.POSITION_Y))
            z = spot.getFeature(spot.POSITION_Z)
            if z == 0 or not cal.pixelDepth or cal.pixelDepth == 0:
                z = 1
            else:
                z = int(z // cal.pixelDepth)
            imp.setPosition(channel, z, t_pos)
            if roi is None:
                roi = PointRoi(int(x), int(y), imp)
            else:
                roi.addPoint(imp, x, y)
        roi.setStrokeColor(colorRGBtoColor(roi_color))
        if "large" in roi_type:
            roi.setPointType(3)
            roi.setSize(4)
        else:
            roi.setPointType(2)
            roi.setSize(1)
        overlay.add(roi, ch_id)
    return count