Beispiel #1
0
def keep_blobs_bigger_than(imp, min_size_pix=100):
    """remove all blobs other than the largest by area"""
    imp.killRoi()
    rt = ResultsTable()
    if "Size_filtered_" in imp.getTitle():
        title_addition = ""
    else:
        title_addition = "Size_filtered_"
    out_imp = IJ.createImage("{}{}".format(title_addition, imp.getTitle()),
                             imp.getWidth(), imp.getHeight(), 1, 8)
    #out_imp.show()
    IJ.run(out_imp, "Select All", "")
    IJ.run(out_imp, "Set...", "value=0 slice")
    mxsz = imp.width * imp.height
    roim = RoiManager(False)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt,
                          min_size_pix, mxsz)
    pa.setRoiManager(roim)
    roim.reset()
    rt.reset()
    pa.analyze(imp)
    if roim.getCount() > 0:
        rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist()
        #	print("Number of cells identified: {}".format(len(rt_areas)))
        for idx in range(len(rt_areas)):
            roim.select(out_imp, idx)
            IJ.run(out_imp, "Set...", "value=255 slice")
    roim.reset()
    roim.close()
    imp.changes = False
    imp.close()
    return out_imp
Beispiel #2
0
def save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID): 
  saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir
  if not os.path.exists(saveDir):
    os.makedirs(saveDir)
  print "Saving to", saveDir
  IJ.selectWindow("Results for PA ")
  IJ.saveAs("Text", ""+saveDir+"\\"+localfile+".xls")
  IJ.selectWindow(imageID);
  imp=IJ.getImage()
  IJ.run("Duplicate...", "duplicate channels="+str(y)+"") #brightfield channel
  IJ.run("Z Project...", "projection=[Sum Slices]")
  rm= RoiManager(True)
  rm.runCommand("Show All without labels")
  rm.runCommand("Set Color", "red")
  rm.runCommand("Set Line Width", str(4))
  imp=IJ.getImage()
  IJ.saveAs(imp,"Tiff", ""+saveDir+"\\"+localfile+"_OV.tif")
  rm.runCommand("Show None")
  IJ.saveAs(imp,"Tiff", ""+saveDir+"\\"+localfile+".tif")
  IJ.selectWindow("IMAGE")
  imp=IJ.getImage()
  IJ.saveAs(imp, "Tiff", os.path.join(saveDir, filename))
  ROInumber = rm.getCount()
  if(ROInumber>0):
	RoiManager("Delete")
Beispiel #3
0
def perform_manual_qc(imp, rois, important_channel=1):
    """given cell rois generated by automatic methods, allow user to delete/add/redraw as appropriate"""
    for ch in range(imp.getNChannels()):
        imp.setC(ch + 1)
        sat_frac = 0.99 if (ch + 1) == important_channel else 0.01
        IJ.run(imp, "Enhance Contrast", "saturated={}".format(sat_frac))

    imp.setC(important_channel)
    IJ.setTool("freehand")
    proceed = False
    roim = RoiManager()
    roim.runCommand("Show all with labels")
    for roi in rois:
        roim.addRoi(roi)
    auto_rois_only = rois
    while not proceed:
        dialog = NonBlockingGenericDialog("Perform manual segmentation")
        dialog.setOKLabel("Proceed to next image...")
        dialog.addMessage("Perform manual correction of segmentation: ")
        dialog.addMessage(
            "Draw around cells and add to the region of interest manager (Ctrl+T). "
        )
        dialog.addMessage("Delete and redraw cells as appropriate. ")
        dialog.addMessage(
            "Then press \"proceed to next image\" when all cells have been added. "
        )
        dialog.showDialog()
        if dialog.wasCanceled():
            print("Manual segmentation canceled")
            return auto_rois_only
        elif dialog.wasOKed():
            if roim.getCount() == 0:
                rois = []
                confirm_dialog = GenericDialog("Continue?")
                confirm_dialog.addMessage(
                    "No rois selected in this FOV. Are you sure you want to proceed?"
                )
                confirm_dialog.setOKLabel("Yes, proceed")
                confirm_dialog.setCancelLabel("No, not yet")
                confirm_dialog.showDialog()
                if confirm_dialog.wasOKed():
                    proceed = True
            else:
                rois = roim.getRoisAsArray()
                proceed = True
    roim.reset()
    roim.close()
    for ch in range(imp.getNChannels()):
        imp.setC(ch + 1)
        IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35))
    imp.setC(important_channel)
    return rois
Beispiel #4
0
        #Checking if savepath exists

        #        try:
        #            os.makedirs(savepath)
        #       except OSError as e:
        #           if e.errno != errno.EEXIST:
        #               raise

        Nuclei = Segment_Nuclei(imp1, nucleus_channel)
        IJ.run(
            Nuclei, "Analyze Particles...",
            "size=5000-Infinity pixel circularity=0.3-1.00 add exclude stack")
        IJ.run("Tile", "")
        time.sleep(0.2)
        name1 = imp1.getTitle()
        nuclei_count = rm.getCount()

        if rm.getCount() != 0:
            rois = rm.getIndexes()
            rm.setSelectedIndexes(rois)
            if rm.getCount() > 1:
                rm.runCommand("Combine")
                rm.runCommand("Delete")
                rm.runCommand("Add")
            rois1 = rm.getIndexes()
            for roi in rois1:
                rm.select(imp1, roi)
                imp1.setC(1)
                IJ.run(imp1, "Draw", "slice")

        IJ.selectWindow(name1)
Beispiel #5
0
def run():
	zk = ZeissKeys()
	msg = Message()
	timestart = time.clock()
	channel = 1
	#size in um2
	minArea = 20 
	maxArea = 200
	maxMetaArea = 70
	minMetaAR = 1.8
	method = "Triangle"
	print "Enter run"
	detectionNucleus = [minArea, maxArea]
	detectionMetaphase = [minArea, maxMetaArea]
	filepath = ""
	try:			 
		filepath  = getArgument()
		image = IJ.openImage(filepath) #arguments provided by runMacro
	except NameError:
		try: 
			filepath = newImagePath  #argument provided by the macroRunner
		except NameError: #no file name specified
			errMsg = "Fiji error segmentNuclei.py: no filepath has been passed to the macro"
			exitWithError(errMsg)
			od = OpenDialog("Choose image file", None)
			if od.getFileName() == None:
				return
			filepath = os.path.join(od.getDirectory(), od.getFileName())
	
	# A roimanager is recquired
	roim = RoiManager.getInstance()
	if roim == None:
		roim = RoiManager()
	#test a last time
	if roim == None:
		print 'Fiji error segmentNuclei.py: no RoiManager!'
		exitWithError('Fiji error segmentNuclei.py: no RoiManager!')
		
	try:	
		IJ.run("Close all forced")
		IJ.run("Clear Results")
		IJ.log("\\Clear")
		image = IJ.openImage(filepath)
		IJ.log("File Path  " + filepath)

		
		try: 
			image.hide()
		except: 
			image = IJ.getImage()
			image.hide()
		image.show()	
		if image is None:
			exitWithError("Fiji failed to open image")
			return 0 

		#convert um2 to pixels
		pixelSize = image.getCalibration().pixelWidth
		detectionNucleus = [area/pixelSize/pixelSize for area in detectionNucleus]
		detectionMetaphase = [area/pixelSize/pixelSize for area in detectionMetaphase]
		detectionMetaphase.append(minMetaAR)
		
		title = image.getTitle()
		
		imageC = None
		#split colors if needed
		if image.getNChannels() > 1: 
			chSp = ChannelSplitter()
			imageC = chSp.split(image)
			imageSeg = imageC[channel-1].duplicate()
		else: 
			imageSeg = image.duplicate()
		
		imageSeg.setTitle("SEG_"+title)

				
		sp = segment_Particles()
		imageSeg = sp.preprocessImage(imageSeg, "MAX", "C1", 2, 2)
		imageSeg = sp.segmentParticles(imageSeg, method, detectionNucleus[0], detectionNucleus[1], 2, 2)


		roim = RoiManager.getInstance()
		if roim == None:
			print 'Fiji error segmentNuclei.py: no RoiManager!'
			exitWithError('Fiji error segmentNuclei.py: no RoiManager!')

		#compute central object
		if roim.getCount() > 0:
			centPart, msg.position = centerParticle(imageSeg, roim)
			msg.position = msg.position + (focusParticle(image, roim, centPart),)
			writePositionToRegistry(msg.position)
		else:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ")
			return 0

		#create output image
		if imageC is None:
			impOut = createOutputImg(image, roim, centPart, 0)
		else:
			impOut = createOutputImg(imageC[channel-1], roim, centPart, 0)
		impOut.show()

		#save outut image
		#saveOutputImg(impOut, filepath, 'Analyzed')

		#check for roi properties to identofy metaphase
		metaphase = isSpecialParticle(image, roim, centPart,detectionNucleus, detectionMetaphase,pixelSize, msg.position[2])

		if os.path.basename(filepath).startswith('TR1_') or '_TR1_' in  os.path.basename(filepath):
			metaphase = 0
		if metaphase:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_TRIGGER1+"] windows=REG_SZ")
		else:
			IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_FOCUS+"] windows=REG_SZ")

		IJ.log("time focus " + str(time.clock() - timestart))
		IJ.run("Collect Garbage")
		
		#IJ.run("Close all forced")
		#IJ.run("Clear Results")
		
	except BaseException, err:
Beispiel #6
0
# ImageJ Python (Jython) script by Theresa Swayne, Columbia University, 2016
# Purpose:  Select random ROIs from a grid produced by EPFL VSI Reader

# to start with, open your VSI and select a rectangular area of tissue, then click Grid.
# if you have a lot of ROIs that have no tissue, delete these before running

from ij import IJ
from ij.plugin.frame import RoiManager
from ij.gui import Roi

rm = RoiManager.getInstance()
if not rm:
  rm = RoiManager()

# number of squares in the grid = number of values to choose from
gridSquares = rm.getCount()

# number of fields you need (must be <= gridSquares)
fieldsNeeded = 6

# get path for temp file

import os
from ij.io import DirectoryChooser

dc = DirectoryChooser("Pick folder for saving ROI temp file")
folder = dc.getDirectory()

# make a list of random integers
# ROI manager indices start with 0
	def __displayCells(self, nameimage, methodeleon=False):
		"""
		Displays all the ROIs of the cells with different colors
		
		"""
		# we define a list of colors that will be used.

		colors = []
		ncells= len(self.__dict[nameimage])
		if ncells > 0 :
			step=200/ncells
			if step<1 : step=1
			for i in range(ncells) : 
				r = random.randrange(5,205,step)
				g = random.randrange(10,210,step)
				b = random.randrange(30,230,step)
				#r = int(0+i*step)
				#g = random.randrange(10, 190, 30)
				#b = int(250-i*step)
				
				colors.append(Color(r, g, b))

		else : 	colors=[Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow]
		tempcolors=list(colors)
		# we try to have random and different colors for each cell.
		for cellname in self.__dict[nameimage].keys() :
			if len(tempcolors)>0 : 
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
			else :
				tempcolors=list(colors)
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
		

		self.__SaveCells(nameimage)
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		# if the user wants to save files, .zip for the ROIs are saved.
		#if self.__optionSave == True : 
		#os.mkdir(self.__pathdir+"ROIs/", mode=0777)
		os.makedirs(self.__pathdir+"ROIs/", mode=0777)
		tempimp = IJ.createImage("tempimp", "8-bit Black", self.__dictImages[nameimage].getWidth(), self.__dictImages[nameimage].getHeight(), 1)
		tempimp.show()
		for cellname in self.__dict[nameimage].keys() :
			for numslice in range(self.__dictImages[nameimage].getImageStackSize()) :
				r = self.__dict[nameimage][cellname].getRoi(numslice)
				try : 
					name=r.getName()
				
				except AttributeError : continue

				else :
					s = "%04i" % (numslice+1)
					#name=s+"-"+name.split("-", 1)[1]
					name=s+"-cell"+name.split("cell")[1]
					r.setName(name)
					try :
						rm.addRoi(r)
						rname=rm.getName(rm.getCount()-1)
						#rm.select(self.__dictImages[nameimage], rm.getCount()-1)
						rm.select(tempimp, rm.getCount()-1)
						rm.runCommand("Rename", name)
					except TypeError : continue
					
					
				#if isinstance(self.__dict[nameimage][cellname].getRoi(numslice),Roi) == True :
				#	s = "%04i" % (numslice)
				#	#rm.add(self.__dictImages[nameimage], self.__dict[nameimage][cellname].getRoi(numslice)  ,  numslice)
				#	name=self.__dict[nameimage][cellname].getRoi(numslice).getName()
				#	name=s+name
				#	self.__dict[nameimage][cellname].getRoi(numslice).setName(name)
				#	rm.addRoi(self.__dict[nameimage][cellname].getRoi(numslice))
			rm.runCommand("Save", self.__pathdir+"ROIs/"+cellname+".zip")
			rm.runCommand("reset")
		
		tempimp.close()
Beispiel #8
0
	def __settings(self, imgName) :
		"""
		Lets the user to choose different measures to make, and displays it following the choice of the user.
		
		"""

		try : dico=self.__dictCells[imgName]
		except KeyError : 
			try : dico=self.__dictCells[imgName[:-4]]
			except KeyError : return False
			else : imgName=imgName[:-4]
		
		dico=self.__dictCells[imgName]
		for cellname in dico.keys() :
			self.__dictMeasures[dico[cellname]]={}
			
		# Represents the datas on a diagram
		def diagrambuttonPressed(event) :
			IJ.showMessage("Push 'Auto' button each time you want to see the diagram")
			x1=10
			y1=20
			x2=100
			y2=50
			x3=60
			y3=30
			xr=10
			yr=20
			wr=20
			hr=20

			
			rect=Rectangle(xr,yr,wr,hr)
			
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife
			IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1")
			im=IJ.getImage()
			ip=im.getProcessor()
			for i in range(len(self.__measures)) :
				indiceligne=0
				maxvalue=0
				minvalue=1000000
				im.setPosition(1,i+1,1)
				for cellname in self.__listcellname :
					indiceligne+=1
					for indicecolonne in range(1,nbslices+1):
						rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2)))
						# we create at the first iteration a dictionary with the rectangles (for a future use)
						if i==0 :
							self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect)
						im.setRoi(rect)
						ipr=im.getProcessor()
						# we find the min and max values of the datas for a measure given.
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue :
							maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue :
							minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						# we fill the rectangle with the value of the measure
						ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1])
						ipr.fill()
				# we write the names and the n of slices on the image with the maxvalue.
				ip.setValue(maxvalue)
				ip.moveTo(x1,y1)
				ip.drawString(self.__measures[i])
				for j in range(1,nbslices+1) :
					ip.moveTo(x2+j*x3,y1)
					ip.drawString("Slice "+str(j))
				j=0
				for cellname in self.__listcellname :
					ip.moveTo(x1,y2+j*y3)
					ip.drawString(cellname)
					j+=1
			im.killRoi()
			im=IJ.run(im,"Fire","")
			IJ.run("Brightness/Contrast...", "")
			#im.setMinAndMax(minvalue,maxvalue)
			#im.updateImage()
			
			#we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it.
			listener = ML()
			listener.name=imgName
			for imp in map(WindowManager.getImage, WindowManager.getIDList()):
				if imp.getTitle().startswith("Diagram") : 
					win = imp.getWindow()
 					if win is None:
						continue
					win.getCanvas().addMouseListener(listener)
		
		# Represents the datas on a series of graphs.
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")

		#def histbuttonPressed(event) :
		#	
		#	pass

		# Represents the values in a tab.
		def tabbuttonPressed(event) :
		
			tab="\t"
			headings=[]
			measures=[]
			#img=IJ.getImage()
			#for i in range(self.__img.getImageStackSize()+1) :
			for i in range(self.__maxLife+1) :
				headings.append("Slice "+str(i))
			
			headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle())
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				
				headstring=""
				for head in headings: 
					headstring+=head+tab
				tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600)
				tp=tw.getTextPanel()
				#for cellname in dico.keys() :
				for cellname in self.__listcellname :
					line=[]
					line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]]
					line.insert(0, cellname+tab)
					linestr=""
					for s in line: linestr+=s
					tp.appendLine(linestr)
				tp.updateDisplay()

			if self.__measuresparambool_global[0] :
				tw=TextWindow("Latency","cell\tLatency", "",800,600)
				tp=tw.getTextPanel()
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					tp.appendLine(line)
				tp.updateDisplay() 
				
		def helpbuttonPressed(event) :

			IJ.showMessage("TO DO")

		def newsetPressed(event) :
			gd0.dispose()
			self.__settings()

		def alignbuttonPressed(event) :
			IJ.showMessage("TO DO")


		def mergebuttonPressed(event) :
			IJ.showMessage("TO DO")

		def saveResults() :
			
			#if len(self.__listcellname) == 0 :
			
			nbslices=self.__maxLife
			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time_sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
							
			if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777)
			tab="\t"
			nl="\n"
			measures=[]
			headstring=""
			#if self.__savemode : mode = "a"
			#else : mode ="w"
			mode = "a"
			
			#for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab
			for i in range(self.__maxLife) :headstring += str(x[i])+tab
			
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				#f.write(m+nl)
				f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl)
				if len(self.__listcellname) == 0 : f.write("no cells")
				else : 
					for cellname in self.__listcellname :
						linestr=cellname+tab
						for measure in self.__dictMeasures[dico[cellname]][m] :
							#print m, cellname, measure 
							linestr += str(measure)+tab
						linestr+=nl
						f.write(linestr)
				f.close()

			if self.__measuresparambool_global[0] :
				m = "Latency"
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				f.write(imgName+"-"+self.__time+"-"+m+nl)
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					line+=nl
					f.write(line)
				f.close()
				
			

			

		#
		# ----------- main measures dialog -------------------------
		#
     		# Allows the user to choose the measures to make, etc..
		
		measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"]
		measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]
		measureslabels_global=["Latency", "velocity", "cumulatedDist"]
		measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"])
		ens_measures_global=set(measureslabels_global)
		ens_measures_indep=set(measureslabels_indep)
		ens_measures_dep=set(measureslabels_dep)
		measureslabels=[]
		
		for label in measureslabels_indep :
			measureslabels.append(label)

		for label in measureslabels_dep :
			measureslabels.append(label)

		#self.__defaultmeasures=[False for i in range(len(measureslabels))]
		#self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))]

		gdmeasures=NonBlockingGenericDialog("MeasuresChoice")
		gdmeasures.setFont(Font("Courrier", 1, 10))
		gdmeasures.addMessage("*******     TIME SETTINGS     *******")
		gdmeasures.addCheckbox("Only starting at begining  :", self.__onlystart)				# 1 only start
		gdmeasures.addNumericField("Minimal Lifetime  : ",self.__minLife,0)
		gdmeasures.addNumericField("Maximal Lifetime  : ",self.__maxLife,0)
		#gdmeasures.addNumericField("Maximal Lifetime  : ",self.__img.getImageStackSize(),0)
		gdmeasures.addCheckbox("x axis in seconds", self.__useTime)				# 2 use time
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		gdmeasures.addMessage("Choose the measures to make on the cells : ")			
		gdmeasures.addMessage("*******     TIME MEASURES     *******")
		gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures)
		gdmeasures.addMessage("")
		gdmeasures.addMessage("*******     GLOBAL MEASURES     *******")
		gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !")
		gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global)
		gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0)
		gdmeasures.addMessage("")	
		gdmeasures.addMessage("*******     OPTIONS     *******")
		gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect)			# 3 only select
		gdmeasures.addCheckbox("Save results to text files ?", self.__savetables)			# 4 save files
		#gdmeasures.addCheckbox("Append mode ?", self.__savemode)					# 5 append mode
		gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse)				# 6 analysis batch mode
		gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay)				# 7 update overlay
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		help_panel=Panel()
		helpbutton=Button("HELP")
		helpbutton.actionPerformed = helpbuttonPressed
		help_panel.add(helpbutton)	
		gdmeasures.addPanel(help_panel)	
		gdmeasures.hideCancelButton()

		if not self.__batchanalyse :
			gdmeasures.showDialog()
			self.__onlystart=gdmeasures.getNextBoolean() 						# 1 only start
			self.__minLife=gdmeasures.getNextNumber()
			self.__maxLife=gdmeasures.getNextNumber()
			self.__useTime=gdmeasures.getNextBoolean()						# 2 use time

			self.__measuresparambool=[]
			self.__measuresparambool_global=[]
			for i in range(len(measureslabels)) : 
				self.__measuresparambool.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures[i]=self.__measuresparambool[-1]
			for i in range(len(measureslabels_global)) : 
				self.__measuresparambool_global.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures_global[i] = self.__measuresparambool_global[i]
 
			self.__noise=gdmeasures.getNextNumber()
			self.__onlyselect=gdmeasures.getNextBoolean()						# 3 only select
			self.__savetables = gdmeasures.getNextBoolean()						# 4 save files
			#self.__savemode = gdmeasures.getNextBoolean()						# 5 append mode
			self.__batchanalyse = gdmeasures.getNextBoolean()					# 6 analyse mode
			self.__updateoverlay = gdmeasures.getNextBoolean()					# 7 update overlay

		# we update a list of all cells that have a lifetime corresponding to what the user chose.
		if len (self.__allcells) == 0 :
			for cellname in dico.keys() :
				if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife :
					if self.__onlystart :
						if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname)
						else : self.__allcells.append(cellname)

		
		if self.__noise == 0 : self.__noise = None
		if self.__batchanalyse : self.__onlyselect = False
		
		if self.__onlyselect : 
			
			try : 
				self.__gw
			except AttributeError :
				if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
				self.__gw = CellsSelection()
				self.__gw.setTitle(imgName)
				self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
				self.__gw.show()
				self.__gw.setSelected(self.__allcells)
				while not self.__gw.oked and self.__gw.isShowing() : 
					self.__gw.setLabel("Validate selection with OK !!")
					self.__listcellname = list(self.__gw.getSelected())
				self.__gw.resetok()
				self.__gw.setLabel("...")
				self.__gw.hide()
			else : 
				if self.__gw.getTitle() == imgName :
					self.__gw.show()
					self.__gw.setSelected(self.__listcellname)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

				else : 
					self.__gw.dispose()
					if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
					self.__gw = CellsSelection()
					self.__gw.setTitle(imgName)
					self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
					self.__gw.show()
					self.__gw.setSelected(self.__allcells)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

			filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell")
			for f in filestodelet : os.remove(f)
			for cell in self.__listcellname :
				sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell"
				deststr =  self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell"
				#os.system("copy "+sourcestr+", "+deststr) 
				#shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell")
				shutil.copy(sourcestr,deststr)

			self.__dictNcells[imgName] = len(self.__listcellname)
		
		else : 
			self.__listcellname = list(self.__allcells)
			self.__dictNcells[imgName] = len(self.__listcellname)

		if len(self.__listcellname) == 0 : 
			self.__dictNcells[imgName] = 0
			return False
		
		self.__img.hide()
		
		# we make the measures.
		for i in range(len(measureslabels)) :
			IJ.showProgress(i, len(measureslabels))
			if  self.__measuresparambool[i]==True :
				
				self.__measurescompl.append(measureslabels[i])
				
				if (measureslabels[i] in measureslabels_dep_tabonly)==False :
					self.__measures.append(measureslabels[i])
				
				if (i<18) and (measureslabels[i] in ens_measures_indep) :
					self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise)
					ens_measures_indep.discard(measureslabels[i])
					
				if i>=18 :
					self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise)
					
		if self.__measuresparambool_global[0] : # calculate latency
			latencies=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime))

		if self.__measuresparambool_global[1] : # calculate velocity
			self.__measures.append("velocity")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measureVelocity(self.__img,imgName)

		if self.__measuresparambool_global[2] : # calculate cumulatedDistance
			self.__measures.append("cumulatedDist")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measurecumulDist(self.__img,imgName)	
				
		
		self.__img.show()

		self.__img.getProcessor().resetThreshold()		

		
		if self.__updateoverlay :
			if self.__img.getOverlay() is not None : self.__img.getOverlay().clear()
		
			outputrois=[]
			cellnames=[]
			self.__img.hide()
			for cellname in self.__listcellname :
				
				for r in dico[cellname].getListRoi():
					if isinstance(r,Roi) : 
						pos=r.getPosition()
						#print "MC overlay", cellname, r.getName(), pos
						#r.setPosition(0)
						#overlay.add(r)
						outputrois.append(r)
						if "cell" in r.getName() : cellnames.append(r.getName())
						else : cellnames.append(str(pos)+"-"+cellname)
						#print cellnames[-1]

			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.show()
			self.__img.show()
			IJ.selectWindow(self.__img.getTitle())
			rm.runCommand("reset")
			for i in range(len(outputrois)) :
				outputrois[i].setName(cellnames[i])
				rm.addRoi(outputrois[i])
				rm.select(rm.getCount()-1)
				rm.runCommand("Rename", cellnames[i])
			
			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(self.__img, "Labels...", "color=red font=12 show use")
			IJ.run(self.__img, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")


		# ----------- batch analyse ------------------------
		if self.__batchanalyse :
			if self.__savetables :  saveResults()
			self.__dictMeasures.clear()
     			self.__allcells[:]=[]
     			self.__measurescompl[:]=[]
     			self.__measures[:]=[] 
			return False
			
		# ---------- display methodes dialog ----------------
		# Allows the user to choose how to see the results of the measures.		
		
		gd0=NonBlockingGenericDialog("Display")

		gd0.addMessage("How do you want to see the results ?")
		
		panel0=Panel()
		
		diagrambutton=Button("Diagram")
		diagrambutton.actionPerformed = diagrambuttonPressed
		panel0.add(diagrambutton)

		graphbutton=Button("Graph")
		graphbutton.actionPerformed = graphbuttonPressed
		panel0.add(graphbutton)

		tabbutton=Button("Tab")
		tabbutton.actionPerformed = tabbuttonPressed
		panel0.add(tabbutton)
		gd0.addPanel(panel0)
		gd0.addCheckbox("Analyse next stack ?", self.__nextstack)
		gd0.hideCancelButton()	
		gd0.showDialog()

		self.__nextstack = gd0.getNextBoolean()

		# ---------- save tables ---------------------------
		if self.__savetables :  saveResults()
		
		# --------- re-start analysis -------------------
		
     		self.__dictMeasures.clear()
     		#self.__listcellname[:]=[]
     		self.__allcells[:]=[]
     		self.__measurescompl[:]=[]
     		self.__measures[:]=[]

     		if self.__nextstack : return False
     		else : return True
Beispiel #9
0
	def __ImportCells(self, imagesnames) :

		#self.__dictCells[imgName]={}
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		listpaths = []
		listfilescells=[]

		if self.__optionImages :
			IJ.showMessage("Select the folder 'Cells' containing the cells to import")
			selectdir=IJ.getDirectory("image")
			selectdir=IJ.getDirectory("")
			listfilescells.extend(glob.glob(selectdir+os.path.sep+"*"))
			listpaths.append("")

		else : 
			IJ.showMessage("Select the text file containing the list cell paths (listpaths.txt)")
			selectdir=IJ.getDirectory("current")
			frame = Frame("Text file settings ?")
			fd = FileDialog(frame)
			fd.setDirectory(selectdir)
			fd.show()
			selectdir = fd.getDirectory() 
			textfile = fd.getFile()
			fichier = open(selectdir+textfile,"r")
			listpaths=[ glob.glob(f.split("\n")[0]+"Selected-Cells"+os.path.sep+"*") for f in fichier.readlines()]

			#for f in templist : 
			#	listpaths.append(f.split("\n")+"Cells")
				
			listfilescells.append("")

		if listfilescells[0]=="" : importmode = True
		else : importmode = False
		
		for j in range(len(listpaths)) :
			self.__dictCells[imagesnames[j]]={}
			if importmode : listfilescells = listpaths[j]
			pathtemp = []
			for cellfile in listfilescells :
				filetemp = open(cellfile,"r")
				linestemp=filetemp.readlines()
				for line in linestemp :
					params=line.split("=")
					values=params[1].split("\n")
					if params[0] == "NAMECELL" :
						celltemp=Bacteria_Cell(str(values[0]))
						self.__dictCells[imagesnames[j]][values[0]]=celltemp
						self.__dictMeasures[self.__dictCells[imagesnames[j]][values[0]]]={} 


					if params[0] == "PATHROIS" :
						pathtemp.append(str(values[0]))
						
					if params[0] == "NSLICES" : 
						for i in range(int(values[0])) :
							celltemp.getListRoi().append("")
				
					if params[0] == "SLICEINIT" :
						celltemp.setSlideInit(int(values[0]))
						for i in range(int(values[0])-2) :
							celltemp.setRoi("NOT HERE YET",i)
				
					if params[0] == "SLICEEND" :
						celltemp.setSlideEnd(int(values[0]))
						for i in range(int(values[0])) :
							celltemp.setRoi("LOST",i)
				
					if params[0] == "COLOR" :
						colorstemp=values[0].split(";")
						celltemp.setColor(Color(int(colorstemp[0]),int(colorstemp[1]),int(colorstemp[2])))
		
		
			indiceroi=0
			ind=0
			tempimp = WindowManager.getImage(imagesnames[j])
			if tempimp is not None : 
				IJ.selectWindow(imagesnames[j])
				tempimp.show()
			else : 
				if imagesnames[j][-4:]==".tif" : 
					IJ.selectWindow(imagesnames[j][:-4])
					tempimp = IJ.getImage()
				else : 
					IJ.selectWindow(imagesnames[j]+".tif")
					tempimp = IJ.getImage()
					
			rm.runCommand("reset")
			
			for cellname in self.__dictCells[imagesnames[j]].keys() :
				rm.runCommand("Open", pathtemp[ind])
				ind+=1
				nbtemp=self.__dictCells[imagesnames[j]][cellname].getLifeTime()
				for i in range(nbtemp) :
					rm.select(tempimp, indiceroi)
					roi=rm.getSelectedRoisAsArray()[0]
					self.__dictCells[imagesnames[j]][cellname].setRoi(roi,i+self.__dictCells[imagesnames[j]][cellname].getSlideInit()-1)
					indiceroi+=1

			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(tempimp, "Labels...", "color=red font=12 show use")
			if rm.getCount()>0 : IJ.run(tempimp, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")

			roipath = os.path.split(pathtemp[0])[0]+os.path.sep
			rootpath = roipath.rsplit(os.path.sep, 2)[0]+os.path.sep

			self.__listpaths[j] = rootpath
			self.__rootpath=rootpath
Beispiel #10
0
def adjustRoiAndMeasure(imp, frameNumber, dstDir):

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    nROIs = rm.getCount()
    indexlist = range(nROIs)

    if nROIs > 2:
        for roi in indexlist:

            indexlist_copy = list(indexlist)
            del indexlist_copy[roi]
            rm.setSelectedIndexes(indexlist_copy)
            rm.runCommand(imp, "Combine")
            IJ.run(imp, "Make Inverse", "")
            rm.addRoi(imp.getRoi())
            new_nROI = rm.getCount()
            rm.setSelectedIndexes([roi, new_nROI - 1])
            rm.runCommand(imp, "AND")
            if imp.getRoi():
                rm.addRoi(imp.getRoi())
                rm.setSelectedIndexes([new_nROI])
                rm.runCommand("Rename", "Cell" + str(roi))
            else:
                rm.setSelectedIndexes([roi])
                rm.addRoi(imp.getRoi())
            rm.setSelectedIndexes([new_nROI - 1])
            rm.runCommand(imp, "Delete")
    elif nROIs == 2:
        for roi in indexlist:
            indexlist_copy = list(indexlist)
            del indexlist_copy[roi]

            rm.setSelectedIndexes(indexlist_copy)
            IJ.run(imp, "Make Inverse", "")
            rm.addRoi(imp.getRoi())
            new_nROI = rm.getCount()
            rm.setSelectedIndexes([roi, new_nROI - 1])
            rm.runCommand(imp, "AND")
            rm.addRoi(imp.getRoi())
            rm.setSelectedIndexes([new_nROI])
            rm.runCommand("Rename", "Cell" + str(roi))
            rm.setSelectedIndexes([new_nROI - 1])
            rm.runCommand(imp, "Delete")

    elif nROIs == 1:
        nROIs = 0
        new_nROI = 1
        rm.setSelectedIndexes([new_nROI])
        rm.runCommand("Rename", "Cell0")

    else:
        return

    adjustedROIs = range(nROIs, new_nROI, 1)
    rm.setSelectedIndexes(adjustedROIs)
    measureChannels(adjustedROIs, imp, frameNumber)
    rm.setSelectedIndexes(adjustedROIs)
    rm.runCommand("Save selected",
                  dstDir + "\\Frame " + str(frameNumber + 1) + " roi set.zip")
    rm.runCommand(imp, "Deselect")
    rm.runCommand(imp, "Delete")
Beispiel #11
0
		num_frames = imp.getNFrames();
		num_z_stacks = imp.getNSlices();
		
		if num_frames < num_z_stacks:
			imp.setDimensions(1,num_frames,num_z_stacks);
				
		    
		    		       
		ROI_list = os.listdir(Folder_ROIs);

		Roi_File = Folder_ROIs + ROI_list[ROI_idx];
		print(ROI_list[ROI_idx]);
		rm = RoiManager();
		rm = RoiManager.getInstance();
		rm.runCommand("Open", Roi_File);
		total_rois = rm.getCount();

		for idx in range(total_rois):
		
			#----------------------------
			# 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);
			model.setPhysicalUnits(Calib.getUnit(), Calib.getTimeUnit());
Beispiel #12
0
def merge_incorrect_splits_and_get_centroids(imp,
                                             centroid_distance_limit=100,
                                             size_limit=100):
    """if particles are found with centroids closer than centroid_distance_limit and both have size<size_limit, get average centroid"""
    imp.killRoi()
    rt = ResultsTable()
    out_imp = IJ.createImage("Nuclei_centroids_from_{}".format(imp.getTitle()),
                             imp.getWidth(), imp.getHeight(), 1, 8)
    IJ.run(out_imp, "Select All", "")
    IJ.run(out_imp, "Set...", "value=0 slice")
    cal = imp.getCalibration()
    mxsz = imp.width * cal.pixelWidth * imp.height * cal.pixelHeight
    roim = RoiManager(False)
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, 0,
        size_limit)
    pa.setRoiManager(roim)
    roim.reset()
    rt.reset()
    pa.analyze(imp)
    centroids_set = set()
    if roim.getCount() > 0:
        rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist()
        rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist()
        centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)]
        for c in centroids:
            ds = [
                math.sqrt((c[0] - cx)**2 + (c[1] - cy)**2)
                for (cx, cy) in centroids
            ]
            close_mask = [d < centroid_distance_limit for d in ds]
            # if no other centroids are within centroid_distance_limit, add this centroid to the output set
            # otherwise, add the average position of this centroid and those within centroid_distance_limit to the output set
            centroids_set.add(
                (sum([msk * b[0] for msk, b in zip(close_mask, centroids)]) /
                 sum(close_mask),
                 sum([msk * b[1] for msk, b in zip(close_mask, centroids)]) /
                 sum(close_mask)))
    roim.reset()
    rt.reset()
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, size_limit,
        mxsz)
    pa.setRoiManager(roim)
    pa.analyze(imp)
    if roim.getCount() > 0:
        if rt.columnExists("X"):
            rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist()
            rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist()
        centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)]
        for c in centroids:
            centroids_set.add(c)
    centroids = list(centroids_set)
    #	cal = imp.getCalibration()
    centroids = [(c[0] / cal.pixelWidth, c[1] / cal.pixelHeight)
                 for c in centroids]
    roim.reset()
    roim.close()
    for idx, c in enumerate(centroids):
        roi = OvalRoi(c[0], c[1], 1, 1)
        out_imp.setRoi(roi)
        IJ.run(out_imp, "Set...", "value={} slice".format(idx + 1))
    #imp.changes = False
    #imp.close()
    return out_imp, centroids
pa = ParticleAnalyzer((ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_MASKS), (Measurements.CENTROID | Measurements.STACK_POSITION), rt, 500, 30000, 0.0, 1.0)
pa.setHideOutputImage(False)
keep_rois = [];
pa.analyze(imp);

IJ.run("Set Measurements...", "centroid redirect=None decimal=3");
frames = imp.getNFrames();	
for fridx in range(0, frames):
	rt.reset();
	imp.setSliceWithoutUpdate(fridx + 1);
	ip = imp.getProcessor();
	if not pa.analyze(imp, ip):
		raise Exception("something went wrong analysing particles!")
	rt.show("centroids");
	rm = RoiManager.getInstance();
	if rm.getCount() > 0:
		rois = rm.getRoisAsArray();
		centroidsx = rt.getColumn(rt.getColumnIndex('X'));
		centroidsy = rt.getColumn(rt.getColumnIndex('Y'));
		print(centroidsx);
		print(centroidsy);
		gd = GenericDialog("Continue?");
		gd.showDialog();
		if gd.wasCanceled():
			raise Exception("Run interupted");
		for roi in rois:
			imp.setRoi(roi);
			stats = ImageStatistics().getStatistics(ip);
			print(stats.xCenterOfMass)
			
def Overlayer(org_size, dirs):
	""" Overlays ROIs with appropriate color,
	    saves to .tif and animates aligned images to .gif """
    
    # Get colors.
	Colors, Colors_old = colorlist()

    # Get ROImanager.
	rm = RoiManager().getInstance()
	rois = rm.getCount()
	
	# Overlays ROI on aligned images, converts to 8-bit (for gif).
	for root, directories, filenames in os.walk(dirs["Composites_Aligned"]):
		for filename in filenames:
			imp = IJ.openImage(os.path.join(root, filename))
			converter = ImageConverter(imp)
			converter.setDoScaling(True)
			converter.convertToGray8()

			# Lookup table and local contrast enhancement for vizualisation.
			IJ.run(imp, "Rainbow RGB", "")
			IJ.run(imp, "Enhance Local Contrast (CLAHE)", 
			       "blocksize=127 histogram=256 maximum=3 mask=*None*")

			
			for roi in range(rois):
				roi_obj = rm.getRoi(roi)
				roi_obj.setStrokeWidth(2)		
				if roi < 19:
					roi_obj.setStrokeColor(Color(*Colors[roi][0:3]))
				else:
					roi_obj.setStrokeColor(eval(Colors_old[roi]))
			
			
			rm.moveRoisToOverlay(imp)

			IJ.saveAs(imp, "Tiff", os.path.join(dirs["Overlays"], filename))
			
	# Opens overlaid images, saves as tiff stack.
	overlay_stack = IJ.run("Image Sequence...", "open="+dirs["Overlays"]+
					       " number=3040 starting=0 increment=1 scale=300 file=.tif sort")
	
	# Takes care of spaces in titles. 
	tiftitle = Title.replace(" ", "_")
	tiftitle = tiftitle.replace(".", "_")
	
	# Gets dimensions for scalebar.
	imp = WindowManager.getImage("Overlays")
	dimensions = imp.getDimensions()
	size = dimensions[0] + dimensions[1]
	microns = org_size / size

	# Sets scale and writes scale-bar, flattens overlays. 
	IJ.run(imp, "Set Scale...", "distance=1 known="
	       +str(microns)+" pixel=1 unit=micron")
           
	IJ.run(imp, "Scale Bar...", 
	    "width=10 height=4 font=14 color=Yellow background=None location=[Lower Right] bold overlay")
    
	IJ.run(imp, "Flatten", "stack")
	IJ.saveAs(imp, "Tiff", os.path.join(dirs["Gifs"], tiftitle))
	
	# Animates tiff stack from directoy. 
	for root, directories, filenames in os.walk(dirs["Gifs"]):
		for filename in filenames:		
			if tiftitle in filename and filename.endswith(".tif"):
				# set=xx parameter controls gif speed.
				# for additional parameters run with macro recorder.
				try:
					print "Animating gif..."
					imp = WindowManager.getImage(tiftitle + ".tif")
					gif = IJ.run("Animated Gif ... ", 
					             "set=200 number=0 filename="
					             + os.path.join(dirs["Gifs"], tiftitle + ".gif"))
				
				except Exception, e:
					print str(e)
				
				print "gif animated."
def tethered_cell(image_path, frame_number=100, frame_rate=100.0, CCW=1):
    """
    parameter setting; frame rate (frame/sec)

    CCW = 1 : the motor rotation direction and the cell rotation direction on the image are same
    CCW = -1: the motor rotation direction and the cell rotation direction on the image are different
    """
    opener = Opener()
    imp = opener.openImage(image_path)
    image_slice_number = imp.getNSlices()
    rm = RoiManager().getInstance()

    if image_slice_number < frame_number: # too short movie
        IJ.log('Number of frame of the movie is fewer than the number of frame that you selected')
        return False
    # create result directory
    result_path = image_path + '_tethered_cell_result'
    if os.path.lexists(result_path) is False:
        os.mkdir(result_path)

    #z projection; standard deviation, tethered cell shorws circle
    IJ.run(imp, 'Subtract Background...', 'rolling=5 light stack')
    IJ.run(imp, 'Median...', 'radius=2 stack')
    IJ.run(imp, 'Z Project...', 'stop=500 projection=[Standard Deviation]')
    zimp = IJ.getImage()
    IJ.saveAs(zimp, 'bmp', os.path.join(result_path,'STD_DEV.bmp'))
    # pick up tethered cell
    IJ.setAutoThreshold(zimp, 'MaxEntropy dark')
    IJ.run(zimp, 'Convert to Mask', '')
    IJ.run('Set Measurements...', "area centroid bounding shape feret's limit redirect=None decimal=3")
    IJ.run(zimp, 'Analyze Particles...', 'size=30-Infinity circularity=0.88-1.00 show=Nothing display exclude clear include')
    zrt = ResultsTable.getResultsTable()
    IJ.saveAs('Results', os.path.join(result_path,'RoiInfo.csv'))

    #tcX and tcY are xy coordinates of tethered cell, tcdia is outer diameter of rotating tethered cell
    #add ROI into stack image
    for i in range(zrt.getCounter()):
        tcX = zrt.getValue('X', i)
        tcY = zrt.getValue('Y', i)
        tcdia = zrt.getValue('Feret', i)
        rm.add(imp, OvalRoi(tcX - tcdia/2.0, tcY - tcdia/2.0, tcdia + 1, tcdia + 1), i)

    #calculate rotation speed by ellipse fitting
    IJ.setAutoThreshold(imp, 'Li')
    for roi_number in range(rm.getCount()):
        t = []
        XM = []
        YM = []
        theta = []
        rotation_speed = []
        area = []
        imp.setRoi(rm.getRoi(roi_number))
        cropped_imp = Duplicator().run(imp)
        IJ.run('Set Measurements...', 'area mean center fit limit redirect=None decimal=3')
        rm.select(roi_number)
        rt = rm.multiMeasure(imp)

        # check cell is present while analysis. Don't a cell gose anywhare?
        for i in range(frame_number):
            area.append(rt.getValue('Area1', i))
        if 0 in area:
            continue

        for i in range(frame_number):
            t.append((1/frame_rate)*i)
            XM.append(rt.getValue('XM1', i))
            YM.append(rt.getValue('YM1', i))
            theta.append(rt.getValue('Angle1', i)/180.0*math.pi)  # convert to radian
            if i == 0:
                rotation_speed.append(0)
            else:
                # phase treatment, theta should be -pi ~ pi
                temp_rotation_speed = [theta[i] - theta[i-1],
                          theta[i] - theta[i-1] + math.pi,
                          theta[i] - theta[i-1] - math.pi,
                          theta[i] - theta[i-1] + 2*math.pi,
                          theta[i] - theta[i-1] - 2*math.pi]
                temp_rotation_speed = sorted(temp_rotation_speed, key = lambda x :abs(x) )[0]
                rotation_speed.append(CCW*temp_rotation_speed/(2.0*math.pi)*frame_rate)

        # write csv
        # earch columns indicate 1:index, 2:time(sec), 3:X-coordinate of center of mass(pixel), 4:Y-coordinate of center of mass (pixel), 5:Angle(Radian), 6:Rotation Speed(Hz)
        with open(os.path.join(result_path,'Roi' + str(roi_number) + '.csv'), 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['Index', 'time(s)', 'X', 'Y', 'Angle(rad)', 'Rotation Speed(Hz)'])
            for i in range(len(t)):
                writer.writerow([i, t[i], XM[i], YM[i], theta[i], rotation_speed[i]])
        # plot x-y, t-x, t-y, t-rotation speed, save plot as bmp
        plotRotation(roi_number, result_path, t, XM, YM, rotation_speed)
        IJ.saveAs(cropped_imp, 'tiff', os.path.join(result_path,'Roi' + str(roi_number) + '.tiff'))
        rt.reset()

    # get analysis date and time
    dt = datetime.datetime.today()
    dtstr = dt.strftime('%Y-%m-%d %H:%M:%S')

    # wtite analysis setting
    with open(os.path.join(result_path,'analysis_setting.csv'), 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter'])
        writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2'])

    # save roi
    if rm.getCount() != 0:
        rm.runCommand('Save', os.path.join(result_path, 'Roi.zip'))

    zimp.close()
    imp.close()
    rm.close()
    zrt.reset()
Beispiel #16
0
         IJ.run(
             "Analyze Particles...",
             "size=" + str(uGsize) + "-Infinity pixel circularity=" +
             str(uGshape) + "-" + str(uGshapemax) +
             " show=[Overlay Masks] exclude clear summarize add")
         print "ATP, Exclude edges"
     else:
         IJ.run(
             "Analyze Particles...", "size=" + str(uGsize) +
             "-Infinity pixel circularity=" + str(uGshape) + "-" +
             str(uGshapemax) + " show=[Overlay Masks] clear summarize add")
         print "ATP, include all"
 # ROI management
 rm.runCommand("Combine")
 rm.runCommand("Add")
 rct = rm.getCount()
 fullTitle = ImagePlus.getTitle(thisImage)
 shortTitle = ImagePlus.getShortTitle(thisImage)
 IJ.run("Invert LUT")  ### Invert LUT
 rm.rename(rct - 1, str(shortTitle))
 rm.select(rct - 1)
 if image == newPaths[0]:
     rm.runCommand(
         "Save",
         analysisOut + File.separatorChar + "ROIindividual_wt" + ".zip")
 if image == newPaths[1]:
     rm.runCommand(
         "Save",
         analysisOut + File.separatorChar + "ROIindividual_dic" + ".zip")
 if image == newPaths[2]:
     rm.runCommand(