def new_Table():
    """Creates a new ResultsTable padded with float("nan"), ie, all
       empty cells will be filled with Java's String.valueOf(Double.NaN)
    """
    new_rt = RT()
    new_rt.setNaNEmptyCells(True);
    new_rt.showRowNumbers(False);
    return new_rt
Esempio n. 2
0
    def measure(self):
        imp = IJ.openImage(self.filename)
        IJ.log("Input file: %s" % self.filename)

        ImageConverter(imp).convertToGray8()

        res = Auto_Threshold().exec(imp, self.myMethod, self.noWhite, self.noBlack, self.doIwhite, self.doIset, self.doIlog, self.doIstackHistogram)

        rt = ResultsTable()
        rt.showRowNumbers(False)
        pa = PA(self.options, PA.AREA + PA.PERIMETER + PA.CIRCULARITY, rt, self.MINSIZE, self.MAXSIZE)
        pa.analyze(imp)
        self.result = self.rtToResult(rt)
        self.mask = imp
Esempio n. 3
0
def measure(stack, cells, nuclei):
    time = [ (t-1)*cal.frameInterval for t in range(T+1) ]
    cellValues0 = [ 0.0 for t in range(T+1) ]
    cellValues1 = [ 0.0 for t in range(T+1) ]
    cellAreas0 = [ 0.0 for t in range(T+1) ]
    cellAreas1 = [ 0.0 for t in range(T+1) ]
    nucleusValues0 = [ 0.0 for t in range(T+1) ]
    nucleusValues1 = [ 0.0 for t in range(T+1) ]
    nucleusAreas0 = [ 0.0 for t in range(T+1) ]
    nucleusAreas1 = [ 0.0 for t in range(T+1) ]
    nonNucleusValues0 = [ 0.0 for t in range(T+1) ]
    nonNucleusValues1 = [ 0.0 for t in range(T+1) ]

    for t in range(1,T+1):
        ip = stack.getProcessor(t)

        if cells[t] is None:
            continue


        #subtract background Z from all intensity Z measurements
        if cells [t] is None:
            print("Nocellsfound" + str(t))
        bothCells = ShapeRoi(cells[t][0]).or(ShapeRoi(cells[t][1]))
        backRoi = ShapeRoi(Rectangle(0,0,imp.getWidth(),imp.getHeight())).not( bothCells )


        ip.setRoi(backRoi)
        backMean = ip.getStatistics().mean

        ip.setRoi( cells[t][0] )
        stats0 = ip.getStatistics()
        cellValues0[t] = stats0.mean - backMean
        cellAreas0[t] = stats0.area * cal.pixelWidth * cal.pixelHeight
        nuc0 = None
        for nuc in nuclei[t]:
            rect = nuc.getBounds()
            nx = int(rect.x+(rect.width/2.0))
            ny = int(rect.y+(rect.height/2.0))
            if cells[t][0].contains(nx,ny):
                nuc0 = nuc
                break
        if nuc0 is not None:
            ip.setRoi( nuc0 )
            nucStats0 = ip.getStatistics()
            nucleusValues0[t] = nucStats0.mean - backMean
            nucleusAreas0[t] = nucStats0.area * cal.pixelWidth * cal.pixelHeight
            nuc0.setPosition(0,0,t)
            nuc0.setStrokeColor(Color.CYAN)
            ol.add(nuc0)
            nonnucRoi0 = ShapeRoi(cells[t][0]).not( ShapeRoi(nuc0) )
            ip.setRoi( nonnucRoi0 )
            nonNucleusValues0[t] = ip.getStatistics().mean - backMean

        ip.setRoi( cells[t][1] )
        stats1 = ip.getStatistics()
        cellValues1[t] = stats1.mean - backMean
        cellAreas1[t] = stats1.area * cal.pixelWidth * cal.pixelHeight
        nuc1 = None
        for nuc in nuclei[t]:
            rect = nuc.getBounds()
            nx = int(rect.x+(rect.width/2.0))
            ny = int(rect.y+(rect.height/2.0))
            if cells[t][1].contains(nx,ny):
                nuc1 = nuc
                break
        if nuc1 is not None:
            ip.setRoi( nuc1 )
            nucStats1 = ip.getStatistics()
            nucleusValues1[t] = nucStats1.mean - backMean
            nucleusAreas1[t] = nucStats1.area * cal.pixelWidth * cal.pixelHeight
            nuc1.setPosition(0,0,t)
            nuc1.setStrokeColor(Color.CYAN)
            ol.add(nuc1)
            nonnucRoi1 = ShapeRoi(cells[t][1]).not( ShapeRoi(nuc1) )
            ip.setRoi( nonnucRoi1 )
            nonNucleusValues1[t] = ip.getStatistics().mean - backMean

    rt = ResultsTable()
    rt.showRowNumbers(False)
    for t in range(1,T+1):
        rt.setValue("Time ("+cal.getTimeUnit()+")", t-1, IJ.d2s(time[t],1))
        areaRatio = cellAreas0[t] / cellAreas1[t] if cellAreas0[t]>0 and cellAreas1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Area Ratio", t-1, areaRatio)

        nucleusRatio = nucleusValues0[t] / nucleusValues1[t] if nucleusValues0[t]>0 and nucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Nucleus Ratio", t-1, nucleusRatio)
        nonNucleusRatio = nonNucleusValues0[t] / nonNucleusValues1[t] if nonNucleusValues0[t]>0 and nonNucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 0:Cell 1 Non-Nucleus Ratio", t-1, nonNucleusRatio)

        nnnRatio0 = nucleusValues0[t] / nonNucleusValues0[t] if nucleusValues0[t]>0 and nonNucleusValues0[t]>0 else 0.0
        rt.setValue("Cell 0 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio0)
        nnnRatio1 = nucleusValues1[t] / nonNucleusValues1[t] if nucleusValues1[t]>0 and nonNucleusValues1[t]>0 else 0.0
        rt.setValue("Cell 1 Nucleus:Non-Nucleus Ratio", t-1, nnnRatio1)

        rt.setValue("Cell 0 (red) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas0[t])
        rt.setValue("Cell 0 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas0[t])
        rt.setValue("Cell 0 All", t-1, cellValues0[t])
        rt.setValue("Cell 0 Nucleus", t-1, nucleusValues0[t])
        rt.setValue("Cell 0 Non-Nucleus", t-1, nonNucleusValues0[t])
        rt.setValue("Cell 1 (green) Area ("+cal.getUnit()+u"\u00b2"+")", t-1, cellAreas1[t])
        rt.setValue("Cell 1 Nucleus Area ("+cal.getUnit()+u"\u00b2"+")", t-1, nucleusAreas1[t])
        rt.setValue("Cell 1 All", t-1, cellValues1[t])
        rt.setValue("Cell 1 Nucleus", t-1, nucleusValues1[t])
        rt.setValue("Cell 1 Non-Nucleus", t-1, nonNucleusValues1[t])
    rt.show(imp.getTitle()+"-Results")

    dataset = DefaultXYDataset()
    dataset.addSeries( "Cell 0", [time[1:], cellValues0[1:]] )
    dataset.addSeries( "Cell 1", [time[1:], cellValues1[1:]] )
    dataset.addSeries( "Nucleus 0", [time[1:], nucleusValues0[1:]] )
    dataset.addSeries( "Nucleus 1", [time[1:], nucleusValues1[1:]] )
    dataset.addSeries( "Non-Nucleus 0", [time[1:], nonNucleusValues0[1:]] )
    dataset.addSeries( "Non-Nucleus 1", [time[1:], nonNucleusValues1[1:]] )

    chart = ChartFactory.createScatterPlot( imp.getTitle(), "Time ("+cal.getTimeUnit()+")", "Intensity Z", dataset, PlotOrientation.VERTICAL, True,True,False )
    plot = chart.getPlot()

    plot.setBackgroundPaint(Color(64, 128, 255))
    plot.setDomainGridlinePaint(Color.BLACK)
    plot.setRangeGridlinePaint(Color.BLACK)

    renderer = plot.getRenderer()
    legend = LegendItemCollection()
    shapeR = 2.0
    nucShape = Ellipse2D.Float(-shapeR,-shapeR,shapeR*2,shapeR*2)
    nonNucShape = Path2D.Float()
    nonNucShape.moveTo(-shapeR,-shapeR)
    nonNucShape.lineTo(shapeR,shapeR)
    nonNucShape.moveTo(shapeR,-shapeR)
    nonNucShape.lineTo(-shapeR,shapeR)
    for s in range(dataset.getSeriesCount()):

        if s == 0:
            renderer.setSeriesLinesVisible(s, True)
            renderer.setSeriesShapesVisible(s, False)
            renderer.setSeriesStroke(s, BasicStroke(1))
            renderer.setSeriesPaint(s, Color.RED)
            legend.add( LegendItem("Cell 0", Color.RED) )
        elif s == 1:
            renderer.setSeriesLinesVisible(s, True)
            renderer.setSeriesShapesVisible(s, False)
            renderer.setSeriesStroke(s, BasicStroke(1))
            renderer.setSeriesPaint(s, Color.GREEN)
            legend.add( LegendItem("Cell 1", Color.GREEN) )
        elif s == 2:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nucShape)
            renderer.setSeriesPaint(s, Color.RED)
        elif s == 3:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nucShape)
            renderer.setSeriesPaint(s, Color.GREEN)
        elif s == 4:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nonNucShape)
            renderer.setSeriesPaint(s, Color.RED)
        elif s == 5:
            renderer.setSeriesLinesVisible(s, False)
            renderer.setSeriesShapesVisible(s, True)
            renderer.setSeriesShape(s, nonNucShape)
            renderer.setSeriesPaint(s, Color.GREEN)


    plot.setFixedLegendItems(legend)

    frame = ChartFrame(imp.getTitle()+" Z-Normalised Intensity", chart)
    frame.pack()
    frame.setSize( Dimension(800, 800) )
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)
Esempio n. 4
0
	try:
		image = IJ.openImage(options['inputFile'])
	except Exception:
		images = BF.openImagePlus(options['inputFile'])
		image = images[0]
	
	if options['oneShot']:
		results.append(runSimulation(options, image))
	else:
		parameters = makeParameters(options)
		for index in range(0, len(parameters)):
			options.update(parameters[index])
			results.append(runSimulation(options, image))
	
	resultsTable = ResultsTable()
	resultsTable.showRowNumbers(False)

	for i in range(0, len(results)):
		if options['oneShot']:
			localBackground = options['localBackground']
			seedRadius = options['seedRadius']
			gaussXY = options['gaussXY']
			gaussZ = options['gaussZ']
		else:
			localBackground = parameters[i]['localBackground']
			seedRadius = parameters[i]['seedRadius']
			gaussXY = parameters[i]['gaussXY']
			gaussZ = parameters[i]['gaussZ']
		
		resultsTable.incrementCounter()
		resultsTable.addValue("Threshold", localBackground)
Esempio n. 5
0
def main():
    rt = RT.open2(table_file.getAbsolutePath())
    if not rt: return

    log(" --- --- --- ")
    log("Loaded %s" % table_file.getAbsolutePath())
    log("Loading column lists...")

    # Get column indices from imported file
    headings = getColumnHeadings(rt)
    id_col = getColumnIndex(headings, "TID")
    t_col = getColumnIndex(headings, "t [")
    d2p_col = getColumnIndex(headings, "D2P [")
    angle_col = getColumnIndex(headings, u'\u03B1 [deg]')
    delta_col = getColumnIndex(headings, u'\u0394\u03B1 [deg]')
    if angle_col == RT.COLUMN_NOT_FOUND:
        log("Failed to detect index for angle column. Re-trying...")
        angle_col = getColumnIndex(headings, u'? [deg]')
    if delta_col == RT.COLUMN_NOT_FOUND:
        log("Failed to detect index for delta angle column. Re-trying...")
        delta_col = getColumnIndex(headings, u'?? [deg]')
    log("Last column index is %s" % rt.getLastColumn())

    if RT.COLUMN_NOT_FOUND in (id_col, d2p_col, delta_col, angle_col):
        uiservice.showDialog("Error: Some key columns were not found!",
                             "Invalid Table?")
        return

    log("Settings: BOUT_WINDOW= %s, MIN_D2P= %s, DEF_FRAME_INTERVAL= %s" %
        (BOUT_WINDOW, '{0:.4f}'.format(MIN_D2P), DEF_FRAME_INTERVAL))

    # Store all data on dedicated lists
    track_id_rows = rt.getColumnAsDoubles(id_col)
    d2p_rows = rt.getColumnAsDoubles(d2p_col)
    angle_rows = rt.getColumnAsDoubles(angle_col)
    delta_rows = rt.getColumnAsDoubles(delta_col)
    t_rows = rt.getColumnAsDoubles(t_col)

    # Assess n of data points and extract unique path ids
    n_rows = len(track_id_rows)
    row_indices = range(n_rows)
    track_ids = set(track_id_rows)
    n_tracks = len(track_ids)
    log("Table has %g rows" % n_rows)
    log("Table has %g tracks" % n_tracks)

    log("Parsing tracks...")
    for track_id in track_ids:

        for row, next_row in zip(row_indices, row_indices[1:]):

            if track_id_rows[row] != track_id:
                continue

            if not isNumber(angle_rows[row]):
                rt.setValue("FLAG", row, "NA")
                continue

            lower_bound = max(0, row - BOUT_WINDOW + 1)
            upper_bound = min(n_rows - 1, row + BOUT_WINDOW)
            win_d2p = []
            for _ in range(lower_bound, upper_bound):
                win_d2p.append(d2p_rows[row])

            if sum(win_d2p) <= MIN_D2P * len(win_d2p):
                rt.setValue("FLAG", row, 0)

            else:
                current_angle = angle_rows[row]
                next_angle = angle_rows[next_row]
                current_delta = delta_rows[row]

                flag = -1 if current_angle < 0 else 1
                delta_change = (abs(current_delta) > 90)
                same_sign = ((current_angle < 0) == (next_angle < 0))
                if delta_change and not same_sign:
                    flag *= -1

                rt.setValue("FLAG", row, flag)
                if next_row == n_rows - 1:
                    rt.setValue("FLAG", next_row, flag)

    if rt.save(table_file.getAbsolutePath()):
        log("Processed table successfully saved (file overwritten)")
    else:
        log("Could not override input file. Displaying it...")
        rt.show(table_file.name)

    log("Creating onset table...")
    onset_rt = RT()
    onset_rt.showRowNumbers(False)

    frame_int = DEF_FRAME_INTERVAL
    if "table" in frame_rate_detection:
        frame_int = getFrameIntervalFromTable(row_indices, track_id_rows,
                                              t_rows)
    elif "image" in frame_rate_detection:
        frame_int = getFrameIntervalFromImage(image_file.getAbsolutePath())
    else:
        log("Using default frame rate")

    for track_id in track_ids:

        for prev_row, row in zip(row_indices, row_indices[1:]):

            if not track_id in (track_id_rows[prev_row], track_id_rows[row]):
                continue

            flag = rt.getValue("FLAG", row)
            if not isNumber(flag):
                continue

            flag = int(flag)
            if flag == 0:
                continue

            if flag == 1 or flag == -1:
                srow = onset_rt.getCounter()
                onset_rt.incrementCounter()
                onset_rt.setValue("TID", srow, track_id)
                from_frame = int(t_rows[prev_row] / frame_int) + 1
                to_frame = int(t_rows[row] / frame_int) + 1
                onset_rt.setValue("First disp. [t]", srow,
                                  "%s to %s" % (t_rows[prev_row], t_rows[row]))
                onset_rt.setValue("First disp. [frames]", srow,
                                  "%s to %s" % (from_frame, to_frame))
                onset_rt.setValue("ManualTag", srow, "")
                break

    out_path = suffixed_path(table_file.getAbsolutePath(), "ManualTagging")
    if onset_rt.save(out_path):
        log("Summary table successfully saved: %s" % out_path)
    else:
        log("File not saved... Displaying onset table")
        onset_rt.show("Onsets %s" % table_file.name)
Esempio n. 6
0
roisBF = getRois(maskBF)

ipTomato = stack.getProcessor(imp.getStackIndex(3, z, 1)).duplicate()
sub = ipTomato.duplicate()
ipTomato.blurGaussian(5)
sub.blurGaussian(20)
ipTomato.copyBits(sub, 0, 0, Blitter.SUBTRACT)
maskTomato = getMask(ipTomato, AutoThresholder.Method.MaxEntropy)
roisTomato = getRois(maskTomato)

bfMeasure = stack.getProcessor(imp.getStackIndex(2, z, 1))
tomatoMeasure = stack.getProcessor(imp.getStackIndex(3, z, 1))
gfpMeasure = stack.getProcessor(imp.getStackIndex(1, z, 1))
ol = Overlay()
rt = ResultsTable()
rt.showRowNumbers(False)
for bf in roisBF:
    bfMeasure.setRoi(bf)
    roiStatsBF = bfMeasure.getStatistics()
    if roiStatsBF.area * cal.pixelWidth * cal.pixelHeight < BFminA:
        continue
    bounds = bf.getBounds()
    cXbf = int(bounds.x + (bounds.width / 2.0))
    cYbf = int(bounds.y + (bounds.height / 2.0))

    bf.setStrokeColor(Color.YELLOW)
    bf.setPosition(0, z, 1)
    ol.add(bf)

    tomatoA = 0
    for tomato in roisTomato:
def main():
    rt = RT.open2(table_file.getAbsolutePath())
    if not rt: return

    log(" --- --- --- ")
    log("Loaded %s" % table_file.getAbsolutePath())
    log("Loading column lists...")

    # Get column indices from imported file
    headings = getColumnHeadings(rt)
    id_col = getColumnIndex(headings, "TID")
    t_col = getColumnIndex(headings, "t [")
    d2p_col = getColumnIndex(headings, "D2P [")
    angle_col = getColumnIndex(headings, u'\u03B1 [deg]')
    delta_col = getColumnIndex(headings, u'\u0394\u03B1 [deg]')
    if angle_col == RT.COLUMN_NOT_FOUND:
        log("Failed to detect index for angle column. Re-trying...")
        angle_col = getColumnIndex(headings, u'? [deg]')
    if delta_col == RT.COLUMN_NOT_FOUND:
        log("Failed to detect index for delta angle column. Re-trying...")
        delta_col = getColumnIndex(headings, u'?? [deg]')
    log("Last column index is %s" % rt.getLastColumn())

    if RT.COLUMN_NOT_FOUND in (id_col, d2p_col, delta_col, angle_col):
        uiservice.showDialog("Error: Some key columns were not found!", "Invalid Table?")
        return

    log("Settings: BOUT_WINDOW= %s, MIN_D2P= %s, DEF_FRAME_INTERVAL= %s"
            % (BOUT_WINDOW, '{0:.4f}'.format(MIN_D2P), DEF_FRAME_INTERVAL))

    # Store all data on dedicated lists
    track_id_rows = rt.getColumnAsDoubles(id_col)
    d2p_rows = rt.getColumnAsDoubles(d2p_col)
    angle_rows = rt.getColumnAsDoubles(angle_col)
    delta_rows = rt.getColumnAsDoubles(delta_col)
    t_rows = rt.getColumnAsDoubles(t_col)

    # Assess n of data points and extract unique path ids
    n_rows = len(track_id_rows)
    row_indices = range(n_rows)
    track_ids = set(track_id_rows)
    n_tracks = len(track_ids)
    log("Table has %g rows" % n_rows)
    log("Table has %g tracks" % n_tracks)

    log("Parsing tracks...")
    for track_id in track_ids:


        for row, next_row in zip(row_indices, row_indices[1:]):

            if track_id_rows[row] != track_id:
                continue

            if not isNumber(angle_rows[row]):
                 rt.setValue("FLAG", row, "NA")
                 continue

            lower_bound = max(0, row - BOUT_WINDOW + 1)
            upper_bound = min(n_rows-1, row + BOUT_WINDOW)
            win_d2p = []
            for _ in range(lower_bound, upper_bound):
                win_d2p.append(d2p_rows[row])

            if sum(win_d2p) <= MIN_D2P * len(win_d2p):
                rt.setValue("FLAG", row, 0)

            else:
                current_angle = angle_rows[row]
                next_angle = angle_rows[next_row]
                current_delta = delta_rows[row]

                flag = -1 if current_angle < 0 else 1
                delta_change = (abs(current_delta) > 90)
                same_sign = ((current_angle<0) == (next_angle<0))
                if delta_change and not same_sign:
                    flag *= -1

                rt.setValue("FLAG", row, flag)
                if next_row == n_rows - 1:
                    rt.setValue("FLAG", next_row, flag)

    if rt.save(table_file.getAbsolutePath()):
        log("Processed table successfully saved (file overwritten)")
    else:
        log("Could not override input file. Displaying it...")
        rt.show(table_file.name)


    log("Creating onset table...")
    onset_rt = RT()
    onset_rt.showRowNumbers(False)

    frame_int = DEF_FRAME_INTERVAL
    if "table" in frame_rate_detection:
        frame_int = getFrameIntervalFromTable(row_indices, track_id_rows, t_rows)
    elif "image" in frame_rate_detection:
        frame_int = getFrameIntervalFromImage(image_file.getAbsolutePath())
    else:
        log("Using default frame rate")

    for track_id in track_ids:

        for prev_row, row in zip(row_indices, row_indices[1:]):

            if not track_id in (track_id_rows[prev_row], track_id_rows[row]):
                continue

            flag = rt.getValue("FLAG", row)
            if not isNumber(flag):
                continue

            flag = int(flag)
            if flag == 0:
                continue

            if flag == 1 or flag == -1:
                srow = onset_rt.getCounter()
                onset_rt.incrementCounter()
                onset_rt.setValue("TID", srow, track_id)
                from_frame = int(t_rows[prev_row]/frame_int) + 1
                to_frame = int(t_rows[row]/frame_int) + 1
                onset_rt.setValue("First disp. [t]", srow,
                    "%s to %s" % (t_rows[prev_row], t_rows[row]))
                onset_rt.setValue("First disp. [frames]", srow,
                    "%s to %s" % (from_frame, to_frame))
                onset_rt.setValue("ManualTag", srow, "")
                break

    out_path = suffixed_path(table_file.getAbsolutePath(), "ManualTagging")
    if onset_rt.save(out_path):
        log("Summary table successfully saved: %s" % out_path)
    else:
        log("File not saved... Displaying onset table")
        onset_rt.show("Onsets %s" % table_file.name)