def runPoreDetection():
    '''roiManager=RoiManager(False)
	roiManager.runCommand("open", roiname)
	roiHash=roiManager.getROIs()
	roi=roiHash.get("Right")
	print roi'''

    imageList = Utility.GetOpenImageList()

    nbgd = NonBlockingGenericDialog(Messages.AddRoi)
    nbgd.addMessage(Messages.ChooseImage)

    if (imageList == None):
        IJ.showMessage(Messages.noOpenImages)
        return

    nbgd.addChoice("Image1:", imageList, imageList[0])
    nbgd.showDialog()

    name = nbgd.getNextChoice()

    inputImp = WindowManager.getImage(name)
    inputDataset = Utility.getDatasetByName(data, name)

    detectionParameters = DetectionParameters(10, 200, 0.5, 1.0, 0.3)

    #inputImp.setRoi(roi)

    nbgd2 = NonBlockingGenericDialog(Messages.PositionRoi)
    nbgd2.addMessage(Messages.PositionRoiAndPressOK)
    nbgd2.showDialog()

    poreDetectionUV(inputImp, inputDataset,
                    inputImp.getRoi().clone(), ops, data, display,
                    detectionParameters)
def runPoreDetection():
	'''roiManager=RoiManager(False)
	roiManager.runCommand("open", roiname)
	roiHash=roiManager.getROIs()
	roi=roiHash.get("Right")
	print roi'''
	
	imageList=Utility.GetOpenImageList()

	nbgd=NonBlockingGenericDialog(Messages.AddRoi)
	nbgd.addMessage(Messages.ChooseImage)
	                              
	if (imageList==None):
		IJ.showMessage(Messages.noOpenImages)
		return;
		
	nbgd.addChoice("Image1:", imageList, imageList[0]);
	nbgd.showDialog()

	name = nbgd.getNextChoice()

	inputImp = WindowManager.getImage(name)
	inputDataset=Utility.getDatasetByName(data, name)
	
	detectionParameters=DetectionParameters(10, 200, 0.5, 1.0, 0.3)

	#inputImp.setRoi(roi)

	nbgd2=NonBlockingGenericDialog(Messages.PositionRoi)
	nbgd2.addMessage(Messages.PositionRoiAndPressOK)
	nbgd2.showDialog()

	poreDetectionUV(inputImp, inputDataset, inputImp.getRoi().clone(), ops, data, display, detectionParameters)
	def __mainsettings(self) :
		
		
		# options : 
		#We ask if the user wants to import cells from .cell files
		# we track the cells in a stack that the user has to choose.
		
		def outputpath(event) : 
			self.__pathdir=IJ.getDirectory("image")
			self.__pathdir=IJ.getDirectory("")
			self.__text.setText(self.__pathdir)
			

		panel0=Panel()
		pathbutton=Button("Select output path", actionPerformed = outputpath)
		#pathbutton.actionPerformed = outputpath
		self.__text = TextField(self.__pathdir)
		panel0.add(pathbutton)
		panel0.add(self.__text)

		firstgd=NonBlockingGenericDialog("First choices")
		firstgd.addMessage("------------------  WELCOME  ----------------------")
		firstgd.addMessage("")
		firstgd.addMessage("Please fill the following options")
		firstgd.addMessage("")
		choices=["Already opened images", "Files from hard disk"]
		firstgd.addChoice("Images source : ", choices, choices[0])				# 1 choice
		firstgd.addCheckbox("Run in batch mode ?", False)					# 2 batch 
		firstgd.addMessage("")
		firstgd.addCheckbox("Import a set of cells from hardisk ?", self.__optionImport) 	# 3 import
		firstgd.addMessage("")
		firstgd.addNumericField("Size factor (binning)", 2, 0)					# 4 number
		firstgd.addPanel(panel0)
		firstgd.showDialog()

		
		#self.__optionImages=firstgd.getNextBoolean()
		choice=firstgd.getNextChoiceIndex()							# 1 choice
		self.__batch = firstgd.getNextBoolean()							# 2 batch
		self.__optionImport=firstgd.getNextBoolean()						# 3 import
		self.__binning = firstgd.getNextNumber()						# 4 number
		if choice==0 : self.__optionImages=True
		else : self.__optionImages=False 

		if firstgd.wasCanceled() : return False

		

		#IJ.showMessage("Select a working directory to save results")
		#self.__pathdir=IJ.getDirectory("image")
		#self.__pathdir=IJ.getDirectory("")

		#self.__pathdir=self.__pathdir+imp.getShortTitle()+os.path.sep+time.strftime('%d-%m-%y_%Hh%Mm%Ss',time.localtime())+os.path.sep

		if self.__pathdir is not None : return True
		else : return False
Exemple #4
0
def apply_thresh_overlay(overlay):
    ''' Clear outside rois in overlay '''

    # --- Dialog -----------------------------------
    wlist = WindowManager.getImageTitles()
    gd = NonBlockingGenericDialog('Apply Mask to')
    gd.setCancelLabel('Exit')
    gd.addChoice('Select Movie', wlist, wlist[0])
    gd.addCheckbox('Duplicate', True)

    gd.showDialog()  # dialog is open

    if gd.wasCanceled():
        return False

    sel_win = gd.getNextChoice()
    do_duplicate = gd.getNextBoolean()

    # --- Dialog End ------------------------------

    win_name = IJ.selectWindow(sel_win)
    movie = IJ.getImage()
    movie = slices_to_frames(movie)

    C = movie.getC()
    S = movie.getSlice()

    if do_duplicate:
        IJ.log('duplicating ' + movie.shortTitle)
        movie = movie.duplicate()

    NFrames = movie.getNFrames()

    if overlay.size() != NFrames:  # one roi for each frame!
        display_msg(
            'Mask count mismatch!', 'Mask count mismatch!\nGot ' + str(Nrois) +
            ' masks and ' + str(NFrames) + ' frames.. !')

    for frame in range(1, NFrames + 1):
        movie.setPosition(C, S, frame)
        mask_roi = overlay.get(frame - 1)
        ip = movie.getProcessor()
        ip.setValue(0)
        ip.setRoi(mask_roi)
        ip.fillOutside(mask_roi)

    movie.show()
    return True
	def __selectMeasureStack(self) : 
		# We allow the user to choose what to measure in the stack, and on which stack.
		gd1=NonBlockingGenericDialog("Stack Choice for measures")
		idimages=WindowManager.getIDList()
		images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ]
		imagesnames=[img.getTitle() for img in images]

		activindex=0
		
		for i in range(len(imagesnames)) : 
				if imagesnames[i] == self.__activeTitle : 
					activindex=i
				
		gd1.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex])
		gd1.showDialog()
		chosenstack=gd1.getNextChoice()
		self.__img=WindowManager.getImage(chosenstack)
		IJ.selectWindow(self.__img.getID())
		if gd1.wasOKed() : return True
		else : 	return False
	def __selectTrackStack(self) : 
		gd0=NonBlockingGenericDialog("Stack Choice")
		idimages=WindowManager.getIDList()
		#images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ]
		images=[WindowManager.getImage(imgID) for imgID in idimages]
		imagesnames=[img.getTitle() for img in images]
		for i in range(len(imagesnames)) : 
			if imagesnames[i] == self.__activeTitle : activindex=i
				
		gd0.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex])
		gd0.showDialog()
			
		chosenstack=gd0.getNextChoice()
		self.__img = WindowManager.getImage(chosenstack)
		self.__maxLife = self.__img.getImageStackSize()

		IJ.selectWindow(self.__img.getID())
		self.__activeTitle=self.__img.getTitle()
		self.__imagesnames[:]=[]
		#self.__imagesnames.append("image1")
		self.__imagesnames.append(self.__activeTitle)

		if gd0.wasOKed() : return True
		else : 	return False
	m = p.search(metadata)
	if m is None:
		xtiles = 0
	else:
		xtiles = int(m.group(1))
	p = re.compile(r'Y Tiles: (\d+)')
	m = p.search(metadata)
	if m is None:
		ytiles = 0
	else:
		ytiles = int(m.group(1))
	nTiles = xtiles*ytiles
	
	## Opens the options dialog box
	gd = NonBlockingGenericDialog("Select channel...")
	gd.addChoice("Analysis_channel",["Channel "+str(i) for i in range(1,nChannels+1)],"Channel 1")
	gd.addChoice("Bleeding_channel",["Channel "+str(i) for i in range(nChannels+1)],"Channel 0")
	gd.addChoice("Refractive_reference_channel",["Channel "+str(i) for i in range(nChannels+1)],"Channel 0")
	gd.addNumericField("Intensity_threshold",128,0)
	gd.addNumericField("Size_threshold",100,0)
	gd.addChoice("Process_filter",["None","Min","Median"],"None")
	gd.addCheckbox("Operate_on_tile_subset",False)
	gd.addStringField("Which_tile_subset","1-4,9,11",12)
	gd.showDialog()

	## Parses the information from the dialog box
	if (gd.wasOKed()):
		analysisChannel = gd.getNextChoiceIndex()+1
		bleedingChannel = gd.getNextChoiceIndex()
		refChannel = gd.getNextChoiceIndex()
		intThreshold = gd.getNextNumber()
			IJ.run("Bio-Formats Importer", "open=" + parentLSMFilePath + "_tiles/tile_" + (containing_tiles_dict.keys())[0] + ".ome.tif color_mode=Default view=Hyperstack stack_order=XYCZT")
			IJ.log("Opened tile " + str((containing_tiles_dict.keys())[0]))
		subupcoords_dict = normalize_coords_in_dict(dict(("tile_"+k,upscaled_coords["tile_"+k]) for k in containing_tiles_dict.keys()))
		activeImage = draw_roi_on_full_res_tile(containing_tiles_dict,subupcoords_dict)	
		if (hadStitched):
			activeImage.copyScale(calibImage)
			calib = calibImage.getCalibration()
			calibImage.close()
			activeImage.updateAndRepaintWindow()
		else:
			calib = activeImage.getCalibration()
		
		## Runs interface that allows to correct for bleedthrough and refraction
		if activeImage is not None:
			gd = NonBlockingGenericDialog("Select channel to operate on...")
			gd.addChoice("Select_channel:",["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"Channel 1")
			gd.addChoice("Bleeding_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None")
			gd.addChoice("Refraction_reference_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None")
			gd.showDialog()
			if (gd.wasOKed()):
				channelImages = ChannelSplitter.split(activeImage)
				channel = gd.getNextChoiceIndex()+1
				bleedingC = gd.getNextChoiceIndex()
				refractRefC = gd.getNextChoiceIndex()
				if (bleedingC > 0):
					params = ("bleeding_channel=" + str(bleedingC) + " bloodied_channel=" + str(channel) + " " +
							"allowable_saturation_percent=1.0 rsquare_threshold=0.50")
					IJ.run("Remove Bleedthrough (automatic)", params)
					dataImage = WindowManager.getImage("Corrected_ch" + str(channel))
					if (refractRefC > 0):
						refractCImage = channelImages[refractRefC-1].duplicate()
	def __settings(self, imgName, flag) :
		"""
		Allows the user to choose several parameters for the tracking.
		
		"""
		
		#fenetre=JFrame("Import")
		#optionpane=JOptionPane("Do you want to import previous preferences ?",JOptionPane.QUESTION_MESSAGE ,JOptionPane.YES_NO_OPTION )
		#optionpane.setVisible(True)
		#dialog = optionpane.createDialog(fenetre, "Import")
     		#dialog.show()
     		#choice = optionpane.getValue()
     		#if choice==JOptionPane.YES_OPTION : self.__ImportPref()

		image=self.__dictImages[imgName]

		def outputpath(event) : 
			macrodir=IJ.getDirectory("macros")
			frame = Frame("Select the macro file")
			fd = FileDialog(frame)
			fd.setDirectory(macrodir)
			fd.show()
			macrodir = fd.getDirectory() 
			self.__macropath = fd.getFile()
			self.__text.setText(self.__macropath)
			print self.__macropath
			#self.__macropath=IJ.getDirectory("macros")
			#self.__macropath=IJ.getDirectory("")
			#self.__text.setText(self.__macropath)
		
		panel0=Panel()
		pathbutton=Button("Select macro file", actionPerformed = outputpath)
		#pathbutton.actionPerformed = outputpath
		self.__text = TextField(self.__macropath)
		panel0.add(pathbutton)
		panel0.add(self.__text)
		
		# -------- start batch mode --------- # 
		if self.__batch :
			pass
			#self.__ImportPref(flag) 
			image.hide()
		else :
			image.show()
			IJ.selectWindow(image.getID())
			gd0=NonBlockingGenericDialog("Settings")
			gd0.setFont(Font("Courrier", 1, 10))
			gd0.addMessage("---------------- PRE-PROCESSING OPTIONS -------------------")
			gd0.addCheckbox("Substract Background",self.__subback)				#box 1 subback
			gd0.addNumericField("Radius",self.__radius,0)
			gd0.addCheckbox("Run a macro for pre processing",self.__runmacro)		#box 2 runmacro
			gd0.addPanel(panel0)
			gd0.addMessage("-------------------------------------------")
			gd0.addMessage("Tracking parameters")
			gd0.addMessage("Coeffs modulate de weight of each parameter")
			gd0.addMessage("Max delta set the maximum allowed change in absolute units")
			gd0.addMessage(" ")
			gd0.addNumericField("Coeff Area   : ",self.__distparam[0],0)
			gd0.addNumericField("Max deltaArea   : ",self.__distparam[1],self.__nbdigits,6,"x times")
			gd0.addNumericField("Coeff Angle   : ",self.__distparam[2],0)
			gd0.addNumericField("Max deltaAngle   : ",self.__distparam[3],self.__nbdigits,6,"degrees")
			gd0.addNumericField("Coeff Feret   : ",self.__distparam[4],0)
			gd0.addNumericField("Max deltaFeret   : ",self.__distparam[5],self.__nbdigits,6,"x times")
			gd0.addNumericField("Coeff PositionX   : ",self.__distparam[6],0)
			gd0.addNumericField("Max deltaPositionX   : ",self.__distparam[7],self.__nbdigits,6,"pixels")
			gd0.addNumericField("Coeff PositionY   : ",self.__distparam[8],0)
			gd0.addNumericField("Max deltaPositionY   : ",self.__distparam[9],self.__nbdigits,6,"pixels")
			gd0.addMessage("-------------------------------------------")
			automethods=AutoThresholder.getMethods()
			gd0.addCheckbox("Manual Threshold",self.__manthresh)		#box 3 manthresh
			gd0.addChoice("Threshol Method : ",automethods,self.__thresMethod)
			gd0.addMessage("-------------------------------------------")
			#gd0.addCheckbox("Symmetry Around 0-180",self.__optionAngle)
			#gd0.addMessage("-------------------------------------------")
			#gd0.addCheckbox("Save cell files", self.__optionSave)
			#gd0.addMessage("-------------------------------------------")
			gd0.addCheckbox("Track new cells", self.__optionNewCells)	#box 4 newcells
			gd0.addMessage("-------------------------------------------")	
			gd0.addCheckbox("Generate time list with follow time lapse interval ?", self.__optionTimelapse)	#box 5 timelapse
			gd0.addNumericField("Estimated time lapse   : ",self.__timelapse,self.__nbdigits,6,"seconds")
			#gd0.hideCancelButton()
			gd0.showDialog()

			if gd0.wasCanceled() : return False
			#chosenstack=gd0.getNextChoice()
			#self.__img=WindowManager.getImage(chosenstack)
		
			self.__subback=gd0.getNextBoolean()				#box 1 subback
			self.__radius=gd0.getNextNumber()
			self.__runmacro=gd0.getNextBoolean()				#box 2 runmacro
			for i in range(10) : self.__distparam[i]=gd0.getNextNumber()
			#self.__distmethod=gd0.getNextChoice()
			self.__manthresh=gd0.getNextBoolean()				#box 3 manthresh
			self.__thresMethod=gd0.getNextChoice()
			#self.__optionAngle=gd0.getNextBoolean()
			#self.__optionSave=gd0.getNextBoolean()
			self.__optionNewCells=gd0.getNextBoolean()			#box 4 newcells
			self.__optionTimelapse=gd0.getNextBoolean()			#box 5 timelapse
			self.__timelapse=int(gd0.getNextNumber())
			
		# -------- start end batch mode --------- # 
		
		if self.__optionTimelapse :
			self.__dictTimeStack[imgName]=range(0,image.getImageStackSize()*self.__timelapse, self.__timelapse)

		if not self.__optionTimelapse and self.__source=="image" :
			self.__dictTimeStack[imgName]=range(0,image.getImageStackSize())
		
		#if option_import==True :
		#	temparray=
		#else : temparray=self.__calRois("image1", 1)
		#imp=self.__dictImages["image1"]
		if self.__manthresh :
			ip=image.getProcessor()
			self.__maxthr=ip.getMaxThreshold()
			self.__minthr=ip.getMinThreshold()

		temparray=self.__calRois(image, 1)
		self.__rr=RangeRois(temparray, image)		

		if (not self.__batch) : 
			image.show()
			self.__params=self.__rr.showSettingsDialog().values()
		if self.__batch : image.hide()

		return True
from ij import IJ
from ij import ImagePlus
from ij.gui import NonBlockingGenericDialog
from ij.gui import WaitForUserDialog
from ij.plugin import ChannelSplitter
from ij.plugin import ImageCalculator
from ij.measure import ResultsTable
from ij.measure import Measurements
from ij.plugin.filter import Analyzer

## Main body of script
theImage = IJ.getImage()
gd = NonBlockingGenericDialog("Pick parameters...")
gd.addChoice("Analysis_channel",["Channel "+str(i+1) for i in range(theImage.getNChannels())],"Channel 1")
gd.addNumericField("Pick_threshold",50,0)
gd.addCheckbox("Apply_min",True)
gd.showDialog()
if (gd.wasOKed()):
	analysisChannel = gd.getNextChoiceIndex() + 1
	intensityThreshold = gd.getNextNumber()
	doMin = gd.getNextBoolean() 
	splitImage = ChannelSplitter.split(theImage)
	dataImage = splitImage[analysisChannel-1].duplicate()
	if doMin:
		IJ.run(dataImage,"Minimum...", "radius=2 stack")
	goRun = True
	rt = ResultsTable()
	while goRun:
		wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze")
		wfud.show()
		roi = theImage.getRoi()
from ij import ImagePlus

theImage = IJ.getImage()

sourceImages = []
if theImage.getNChannels() == 1:
	IJ.run("8-bit")
	sourceImages.append(theImage)
else:
	sourceImages = ChannelSplitter.split(theImage)
	sourceNames = []
	for im in sourceImages:
		im.show()
		sourceNames.append(im.getTitle())
	gd0 = NonBlockingGenericDialog("Select source image...")
	gd0.addChoice("Source image",sourceNames,sourceNames[0])
	gd0.showDialog()
	if (gd0.wasOKed()):
		chosenImage = gd0.getNextChoice()
		theImage = WindowManager.getImage(chosenImage)
		IJ.selectWindow(chosenImage)
	else:
		theImage = sourceImages[0]
		IJ.selectWindow(sourceNames[0])
	
gd = NonBlockingGenericDialog("Set slice params...")
gd.addNumericField("Slice start:",1,0)
gd.addNumericField("Slice end:",theImage.getNSlices(),0)
gd.showDialog()

if (gd.wasOKed()):