Exemplo n.º 1
0
def main(tableName, showPlot):
    image = IJ.getImage();
    roi = image.getRoi()
    if not roi:
        center = image.getWidth() / 2, image.getHeight() / 2
    else:
        center = roi.getXBase(), roi.getYBase();
    table = ResultsTable.getResultsTable(tableName)
    vectors = getVectorsFromTable(table, center)
    radialVelocity = calculateRadialVelocityPerTime(vectors, center)
    radialVelocityAndDistanceByTrack(table, center)
    stats = Tools.getStatistics(radialVelocity)
    median = calculateMedian(radialVelocity)
    rt = ResultsTable.getResultsTable(TABLE_NAME)
    if not rt:
        rt = ResultsTable()
    row = rt.getCounter()
    rt.setValue("label", row, tableName)
    rt.setValue("x", row, center[0])
    rt.setValue("y", row, center[1])
    rt.setValue("mean", row, stats.mean)
    rt.setValue("stdDev", row, stats.stdDev)
    rt.setValue("min", row, stats.min)
    rt.setValue("median", row, median)
    rt.setValue("max", row, stats.max)
    rt.show(TABLE_NAME)
    if showPlot:
        plot(radialVelocity, center)
Exemplo n.º 2
0
def analyze(imp, min_area):
    MAXSIZE = 1000000000000
    MINCIRCULARITY = 0.0
    MAXCIRCULARITY = 1.
    
    options = PA.SHOW_MASKS 
    
    temp_results = ResultsTable()
    
    p = PA(options, PA.AREA + PA.MEAN, temp_results, min_area, MAXSIZE, MINCIRCULARITY, MAXCIRCULARITY)
    p.setHideOutputImage(True)

    p.analyze(imp)

    if temp_results.getCounter() == 0:
        areas   = []
        signals = []
    else:
        areas   = list(temp_results.getColumn(0))
        signals = list(temp_results.getColumn(1))
    
    count  = len(areas)
    area   = sum(areas)

    total = 0
    if area > 0:
        total  = sum([a*s for a,s in zip(areas, signals)]) / area
      

    return p.getOutputImage(), count, area, total
def main(tableName, showPlot):
    image = IJ.getImage();
    roi = image.getRoi()
    if not roi:
        center = image.getWidth() / 2, image.getHeight() / 2
    else:
        center = roi.getXBase(), roi.getYBase();
    table = ResultsTable.getResultsTable(tableName)
    rma = RadialMovementAnalyzer(table, center)
    radialDistances = rma.getDeltaRadialDistancePerTrack()
    distances = rma.getDistances()
    frames = rma.getFrames()
    travelledDistances = rma.getTravelledDistances()
    TABLE_NAME = "Distance from " + str(center)
    rt = ResultsTable.getResultsTable(TABLE_NAME)
    if not rt:
        rt = ResultsTable()
    for index, dist in enumerate(radialDistances):
        row = rt.getCounter()
        rt.setValue("label", row, tableName)
        rt.setValue("track ID", row, rma.trackIDs[index])
        rt.setValue("total augmentation of distance from center", row, dist)
        rt.setValue("distance start to end", row, distances[index])
        rt.setValue("travelled distance", row, travelledDistances[index])
        rt.setValue("nr. of frames", row, frames[index])
        if not distances[index] == 0:
            rt.setValue("total augmentation / distance start to end", row, dist / distances[index])
        else:
            rt.setValue("total augmentation / distance start to end", row, float("nan"))
        if not travelledDistances[index] ==0:
            rt.setValue("total augmentation / travelled distance", row, dist / travelledDistances[index])
        else:
             rt.setValue("total augmentation / travelled distance", row, float("nan"))
        rt.setValue("mean speed", row, travelledDistances[index] / frames[index])
        rt.setValue("mean outward speed", row, dist / frames[index])
        
    rt.show(TABLE_NAME)
    if showPlot:
        plot(distances, radialDistances, center)
Exemplo n.º 4
0
class MandersPlugin(ImageListener, WindowAdapter):

	def __init__(self):
		self.imp = None
		self.preview = None
		self.createMainWindow()
		self.cells = None
		self.files = []
		self.results = ResultsTable()
		ImagePlus.addImageListener(self)
		self.selectInputDir()
		self.selectOutputDir()
		self.pairs = []
		self.methods = []
		self.processNextFile()

	def selectInputDir(self):
		inputDialog = DirectoryChooser("Please select a directory contaning your images")
		inputDir = inputDialog.getDirectory()
		for imageFile in os.listdir(inputDir):
			self.files.append(inputDir + imageFile)

	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
		
	def closeImage(self):
		if self.imp is not None:
			self.imp.close()
			self.imp = None
		if self.preview is not None:
			self.preview.close()
			self.preview = None

	def openImage(self, imageFile):
		try:
			images = BF.openImagePlus(imageFile)
			self.imp = images[0]
		except UnknownFormatException:
			return None
		if self.imp.getNChannels() < 2:
			IJ.error("Bad image format", "Image must contain at lease 2 channels!")
			return None
		if not self.pairs or \
			not self.methods:
			self.getOptionsDialog(self.imp)
		title = self.imp.title
		self.imp.title = title[:title.rfind('.')]
		return self.imp

	def getOptionsDialog(self, imp):
		thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData",  "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"]
		gd = GenericDialog("Please select channels to collocalize")
		for i in range(1, imp.getNChannels() + 1):
			gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None")
		gd.showDialog()
		if gd.wasCanceled():
			self.exit()
		channels = []
		for i in range(1, imp.getNChannels() + 1):
			method = gd.getNextChoice()
			self.methods.append(method)
			if method != "None":
				channels.append(i)
		for x in channels:
			for y in channels:
				if x < y:
					self.pairs.append((x, y))

	def processNextFile(self):
		if self.files:
			imageFile = self.files.pop(0)
			return self.processFile(imageFile)
		else:
			return False
			
	def processFile(self, imageFile):
		imp = self.openImage(imageFile)
		if imp is not None:
			cell = Cell(imp.NSlices, 1)
			self.cells = DelegateListModel([])
			self.cells.append(cell)
			self.showMainWindow(self.cells)
			if self.checkbox3D.isSelected():
				self.displayImage(imp)
			else:
				self.displayImage(imp, False)
				self.preview = self.previewImage(imp)
				self.displayImage(self.preview)
			return True
		else:
			return self.processNextFile()
	
	def displayImage(self, imp, show = True):
		imp.setDisplayMode(IJ.COMPOSITE)
		enhancer = ContrastEnhancer()
		enhancer.setUseStackHistogram(True)
		splitter = ChannelSplitter()
		for c in range(1, imp.getNChannels() + 1):
			imp.c = c
			enhancer.stretchHistogram(imp, 0.35)
		if show:
			imp.show()

	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image

	def getCroppedChannels(self, imp, cell):
		splitter = ChannelSplitter()
		imp.setRoi(None)
		if cell.mode3D:
			cropRoi = cell.getCropRoi()
		else:
			cropRoi = cell.roi
		if cropRoi is None:
			return None
		crop = cropRoi.getBounds()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			slices = ImageStack(crop.width, crop.height)
			channel = splitter.getChannel(imp, c)
			for z in range(1, channel.getSize() + 1):
				zslice = channel.getProcessor(z)
				zslice.setRoi(cropRoi)
				nslice = zslice.crop()
				if cell.mode3D:
					oroi = cell.slices[z - 1].roi	
				else:
					oroi = cell.roi
				if oroi is not None:
					roi = oroi.clone()
					bounds = roi.getBounds()
					roi.setLocation(bounds.x - crop.x, bounds.y - crop.y)
					nslice.setColor(Color.black)
					nslice.fillOutside(roi)
					slices.addSlice(nslice)
			channels.append(ImagePlus("Channel %i" % c, slices))
		return channels

	def getThreshold(self, imp, method):
		thresholder = Auto_Threshold()
		duplicator = Duplicator()
		tmp = duplicator.run(imp)
		return thresholder.exec(tmp, method, False, False, True, False, False, True)

	def getContainer(self, impA, impB):
		imgA = ImagePlusAdapter.wrap(impA)
		imgB = ImagePlusAdapter.wrap(impB)
		return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB")

	def getManders(self, imp, cell):
	
		### Crop channels according to cell mask
		channels = self.getCroppedChannels(imp, cell)
		if channels is None:
			return None
			
		### Calculate channel thresholds
		thrs = []
		thrimps = []
		for c, method in enumerate(self.methods):
			if method != "None":
				thr, thrimp = self.getThreshold(channels[c], method)
			else:
				thr, thrimp = None, None
			thrs.append(thr)
			thrimps.append(thrimp)
		
		### Calculate manders colocalization
		manders = MandersColocalization()
		raws = []
		thrds = []
		for chA, chB in self.pairs:
			container = self.getContainer(channels[chA - 1], channels[chB - 1])
			img1 = container.getSourceImage1()
			img2 = container.getSourceImage2()
			mask = container.getMask()
			cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
			rtype = img1.randomAccess().get().createVariable()
			raw = manders.calculateMandersCorrelation(cursor, rtype)
			rthr1 = rtype.copy()
			rthr2 = rtype.copy()
			rthr1.set(thrs[chA - 1])
			rthr2.set(thrs[chB - 1])
			cursor.reset()
			thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
			raws.append(raw)
			thrds.append(thrd)
		
		return (channels, thrimps, thrs, raws, thrds)

	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()

	def createMainWindow(self):
		self.frame = JFrame('Select cells and ROIs',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
		)
		self.frame.setLayout(GridBagLayout())
		self.frame.addWindowListener(self)

		self.frame.add(JLabel("Cells"),
			GridBagConstraints(0, 0, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.cellList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectCell
		)
		self.frame.add(JScrollPane(self.cellList),
			GridBagConstraints(0, 1, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Add cell', actionPerformed = self.addCell),
			GridBagConstraints(1, 2, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
    	
		self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell),
			GridBagConstraints(1, 4, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 5, 0, 5), 0, 0
		))
		
		self.frame.add(JLabel("Slices"),
			GridBagConstraints(0, 6, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.sliceList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectSlice
		)
		self.frame.add(JScrollPane(self.sliceList),
			GridBagConstraints(0, 7, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice),
			GridBagConstraints(1, 8, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.frame.add(JButton('Done', actionPerformed = self.doneSelecting),
			GridBagConstraints(1, 10, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D)
		self.frame.add(self.checkbox3D,
			GridBagConstraints(0, 13, 2, 1, 0, 1,
				GridBagConstraints.WEST, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

	def showMainWindow(self, cells = None):
		if cells is not None:
			self.cellList.model = cells
			if cells:
				self.cellList.selectedIndex = 0
		self.frame.pack()
		self.frame.visible = True

	def hideMainWindow(self):
		self.frame.visible = False

	def closeMainWindow(self):
		self.frame.dispose()

	def toggle3D(self, event):
		mode3D = self.checkbox3D.isSelected()
		if mode3D:
			self.sliceList.enabled = True
			if self.imp is not None:
				self.imp.show()
			if self.preview is not None:
				self.preview.hide()
		else:
			self.sliceList.enabled = False
			if self.preview is None:
				self.preview = self.previewImage(self.imp)
				self.displayImage(self.preview)
			else:
				self.preview.show()
			if self.imp is not None:
				self.imp.hide()
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0:
			cell = self.cells[selectedCell]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		
	def addCell(self, event):
		size = len(self.cells)
		if (size > 0):
			last = self.cells[size - 1]
			n = last.n + 1
		else:
			n = 1
		self.cells.append(Cell(self.imp.NSlices, n))
		self.cellList.selectedIndex = size

	def removeCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			self.cells.remove(self.cells[selected])
			if (selected >= 1):
				self.cellList.selectedIndex = selected - 1
			else:
				self.cellList.selectedIndex = 0

	def selectCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			cell = self.cells[selected]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		else:
			self.sliceList.model = DelegateListModel([])
		if self.preview is not None:
			self.preview.setRoi(cell.roi)

	def selectSlice(self, event):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0:
			cell = self.cells[selectedCell]
			image = self.imp
			mode3D = self.checkbox3D.isSelected()
			if image is not None and cell is not None and mode3D:
				roi = cell.slices[selectedSlice].roi
				if (image.z - 1 != selectedSlice):
					image.z = selectedSlice + 1				
				image.setRoi(roi, True)
			if self.preview is not None and not mode3D:
				self.preview.setRoi(cell.roi, True)

	def updateSlice(self, event):
		if self.checkbox3D.isSelected():
			self.updateSlice3D(self.imp)
		else:
			self.updateSlice2D(self.preview)

	def updateSlice3D(self, imp):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				index = selectedSlice + 1
				roi = ShapeRoi(impRoi, position = index)
				cell.mode3D = True
				cell.name = "Cell %i (3D)" % cell.n
				cell.slices[selectedSlice].roi = roi
				if (index + 1 <= len(cell.slices)):
					imp.z = index + 1			
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
			self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice))

	def updateSlice2D(self, imp):
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				roi = ShapeRoi(impRoi, position = 1)
				cell.mode3D = False
				cell.name = "Cell %i (2D)" % cell.n
				cell.roi = roi	
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
	
	def imageOpened(self, imp):
		pass

	def imageClosed(self, imp):
		pass

	def imageUpdated(self, imp):
		if self.checkbox3D.isSelected():
			if imp is not None:
				selectedCell = self.cellList.selectedIndex
				selectedSlice = imp.z - 1
			if imp == self.imp and selectedSlice != self.sliceList.selectedIndex:
				self.sliceList.selectedIndex = selectedSlice

	def doneSelecting(self, event):
		oluts = self.imp.luts
		luts = []
		channels = []
		for c, method in enumerate(self.methods):
			if method != "None":
				luts.append(oluts[c])
				channels.append(c)
		for cell in self.cells:
			manders = self.getManders(self.imp, cell)
			if manders is not None:
				chimps, thrimps, thrs, raws, thrds = manders
				index = self.cells.index(cell) + 1
				title = "Cell_%i-" % index + self.imp.title
				self.saveMultichannelImage(title, chimps, oluts)
				title = "Cell_%i_thrd-" % index + self.imp.title
				self.saveMultichannelImage(title, thrimps, luts)
				self.results.incrementCounter()
				row = self.results.getCounter() - 1
				for i, thr in enumerate(thrs):
					if thr is not None:
						self.results.setValue("Threshold %i" % (i + 1), row, int(thr))
				for i, pair in enumerate(self.pairs):
					self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1))
					self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2))
					self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1))
					self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2))
		self.closeImage()
		if not self.processNextFile():
			print "All done - happy analysis!"
			self.results.show("Manders collocalization results")
			self.exit()

	def windowClosing(self, e):
		print "Closing plugin - BYE!!!"
		self.exit()

	def exit(self):
		ImagePlus.removeImageListener(self)
		self.closeImage()
		self.closeMainWindow()
Exemplo n.º 5
0
#    + PA.SHOW_RESULTS \    
rt = ResultsTable()
p = PA(options, PA.AREA + PA.STACK_POSITION, rt, MINSIZE, MAXSIZE)
p.setHideOutputImage(True)

# Morphological dilate
binner.setup('dilate', None)


clusters = 0
initialCells = 0

# dilate by 'SAMPLEITER'
for i in range(SAMPLEITER+1):
	p.analyze(binimp)
	cellcounts = rt.getCounter()
	if i == 0:
		initialCells = cellcounts
	#IJ.log("iter:" + str(i) + " -- cell counts: " + str(cellcounts))
	if i == SAMPLEITER:
		clusters = cellcounts
	binner.run(binimp.getProcessor())
	rt.reset()

#binimp.show()
#binorg.show()
IJ.log("==== " + imp3.getTitle() + " =====")
IJ.log("Number of Nucleus : " + str(initialCells))
IJ.log("Clusters at dilation " + str(SAMPLEITER) + ": " + str(clusters))
IJ.log("Clusters/Nucleus " + str(float(clusters)/float(initialCells)))
Exemplo n.º 6
0
		thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0])
		thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1])
		
		cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
		rtype = img1.randomAccess().get().createVariable()
		raw = manders.calculateMandersCorrelation(cursor, rtype)
		rthr1 = rtype.copy()
		rthr2 = rtype.copy()
		rthr1.set(thr1)
		rthr2.set(thr2)
		cursor.reset()
		thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
		print "Results are: %f %f %f %f" % (raw.m1, raw.m2, thrd.m1, thrd.m2)

		results.incrementCounter()
		rowno = results.getCounter() - 1
		results.setValue("Cell", rowno, int(rowno))
		results.setValue("Threshold 1", rowno, int(thr1))
		results.setValue("Threshold 2", rowno, int(thr2))
		results.setValue("M1 raw", rowno, float(raw.m1))
		results.setValue("M2 raw", rowno, float(raw.m2))
		results.setValue("M1 thrd", rowno, float(thrd.m1))
		results.setValue("M2 thrd", rowno, float(thrd.m2))
		
		thrimp = RGBStackMerge.mergeChannels([thrimp1, thrimp2], False)
		saver = FileSaver(thrimp)
		saver.saveAsTiffStack(outputDir + "Cell_%i-" % results.getCounter() + title + ".tif")
		thrimp.close()

results.show("Colocalization results")
Exemplo n.º 7
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)
Exemplo n.º 8
0
        roiStatsGfp = gfpMeasure.getStatistics()
        if roiStatsGfp.area * cal.pixelWidth * cal.pixelHeight < GFPminA:
            continue
        bounds = gfp.getBounds()
        cXgfp = int(bounds.x + (bounds.width / 2.0))
        cYgfp = int(bounds.y + (bounds.height / 2.0))
        if bf.contains(cXgfp, cYgfp):
            gfpA += roiStatsGfp.area
            gfpSum += roiStatsGfp.mean * roiStatsGfp.area
            gfp.setStrokeColor(Color.MAGENTA)
            gfp.setPosition(0, z, 1)
            ol.add(gfp)

    gfpMean = gfpSum / gfpA if gfpA > 0 else 0

    row = rt.getCounter()

    uni = row % 26
    cha = chr(ord('A') + uni)
    name = ""
    while len(name) < (row + 1) / 26.0:
        name += cha

    label = TextRoi(name, cXbf - 20, cYbf + 20, FONT)
    label.setStrokeColor(Color.GREEN)
    label.setPosition(0, z, 1)
    ol.add(label)

    rt.setValue("Organoid", row, name)
    rt.setValue("X", row, cXbf * cal.pixelWidth)
    rt.setValue("Y", row, cYbf * cal.pixelHeight)
maximaip = findmaximashow.getProcessor()
maximahist = maximaip.getHistogram()
CountMethod2 = maximahist[255]
print "Using the findMaxima method with a threshold of " + str(
    THRESH) + ", I found " + str(CountMethod2) + " maxima."

IJ.setRawThreshold(findmaximashow, 255, 255, "red")
IJ.run(findmaximashow, "Create Selection", "")
rm.addRoi(findmaximashow.getRoi())
rm.rename(1, "Maxima with threshold")

# ---- METHOD 3-4: API getMaxima WITH THE POINTS COUNTED OR ADDED TO THE RESULTS TABLE

maxima = mf.getMaxima(ip, 100.0, False)
CountMethod3 = maxima.npoints
print "Using the getMaxima method with no threshold , I found " + str(
    CountMethod3) + " maxima."

rt = ResultsTable()
for i in range(maxima.npoints):
    rt.incrementCounter()
    rt.addValue("X", maxima.xpoints[i])
    rt.addValue("Y", maxima.ypoints[i])

rt.show("Results")
CountMethod4 = rt.getCounter()
print "By counting points generated by getMaxima, I found " + str(
    CountMethod4) + " maxima."
# TODO: add these to the ROI mgr

# TODO: as alternative, check out HMaxima transform from landini, basically subtracting the threshold before running the find maxima
Exemplo n.º 10
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)