def GUI(active):
    # GUI to select file and select input/output folders
    if not active:
        sourcedir = "D:\\JPA\\wt2"
        sourcefile = "D:\\JPA\\wt2.czi"
        targetdir = "D:\\JPA\\wt2"
        XMLinput = "D:\\JPA\\wt2.mvl"
    else:
        od = OpenDialog("Select CZI Zeiss file", None)
        soucedir = od.getDirectory()
        sourcefile = od.getFileName()
        od = OpenDialog("Select MVL Zeiss file", None)
        XMLdir = od.getDirectory()
        XMLfile = od.getFileName()
        XMLinput = os.path.join(XMLdir, XMLfile)
        targetdir = DirectoryChooser(
            "Choose destination folder").getDirectory()
        sourcedir = os.path.join(soucedir, sourcefile)
	# Create some global variables
    global INpath
    INpath = sourcedir
    global source
    source = sourcefile
    global OUTpath
    OUTpath = targetdir
    global XMLzeiss
    XMLzeiss = XMLinput
Beispiel #2
0
def openImp():
    '''function that calls an OpenDialog and returns filePath and imp'''
    od = OpenDialog("Open movie", "")
    filePath = path.join(od.getDirectory(), od.getFileName())
    if path.splitext(od.getFileName())[1] == ".tif" :  #on .dv, use LOCI
        imp = Opener().openImage(filePath)
    if path.splitext(od.getFileName())[1] == ".dv":
        IJ.run("Bio-Formats Importer", "open=["+filePath+"] autoscale color_mode=Grayscale view=Hyperstack stack_order=XYCZT")
        imp = IJ.getImage()
    return filePath, imp
Beispiel #3
0
def ChooseLandmarkFile():
	od = OpenDialog("Choose Landmark file", None)	
	file_name = od.getFileName()
	dir_name = od.getDirectory()
	print("Reading "+file_name)
	print("in directory "+dir_name)	
	return dir_name, file_name
Beispiel #4
0
def open_image():
    """
	opens an image, returns an imagePlus object and its name in that order
	"""
    # Prompt user for the input image file.
    print "open_image begin"
    op = OpenDialog("Choose input image...", "")

    if op.getPath() == None:
        sys.exit('User canceled dialog')
    # open selected image and prepare it for analysis

    inputName = op.getFileName()
    inputDirPath = op.getDirectory()
    inputPath = inputDirPath + inputName

    # Strip the suffix off of the input image name
    if inputName[-4] == ".":
        inputPrefix = inputName[:-4]  # assumes that a suffix exists
    else:
        inputPrefix = inputName

    #opens image and returns it.
    inputImp = ImagePlus(inputPath)

    print "open_image finis"
    return inputImp, inputPrefix, inputDirPath
def get_path():
	od = OpenDialog("Choose Spinning disk  file", None)
	srcDir = od.getDirectory()
	if srcDir is None:
		# User canceled the dialog
		sys.exit(0)
	file = os.path.join(srcDir, od.getFileName())
	return srcDir,file
Beispiel #6
0
def ChooseImageFile(image_type):
	od = OpenDialog("Choose %s image"%image_type, None)
	file_name = od.getFileName()
	dir_name = od.getDirectory()
	full_path = os.path.join(dir_name,file_name)
	print("Opening %s"%full_path)
	imp = IJ.openImage(full_path)
	return imp
def ui_get_input_file():
    """Ask user for input file and process results."""
    dialog = OpenDialog("Choose a 'MATL_Mosaic.log' file")
    fname = dialog.getFileName()
    if (fname is None):
        log.warn('No input file selected!')
        return((None, None))
    base = dialog.getDirectory()
    return((base, fname))
def get_metadata_table_filepath():
    """Get a the metadata template filename"""
    d = GenericDialog("Metadata Template")
    d.addMessage("Please choose a metadata template")
    d.enableYesNoCancel("OK", "Cancel")
    d.hideCancelButton()
    d.showDialog()
    if d.wasOKed():
        od = OpenDialog("Metadata File")
        return os.path.join(od.getDirectory(), od.getFileName())
    else:
        return
Beispiel #9
0
def get_config_file(folder):
    '''Returns the config file name.'''
    # Get list of files in the selected directory.
    files = os.listdir(folder)

    # Check if a config file is present in folder.
    if default_config in files:
        dialog = GenericDialog('Default config file found!')
        dialog.addMessage('Use this file for the analysis?\n \n%s' % os.path.join(folder, default_config))
        dialog.enableYesNoCancel()
        dialog.showDialog()
        if dialog.wasCanceled():
            return None
        elif dialog.wasOKed():
            return default_config
        else:
            open_dialog = OpenDialog('Select a config file', folder, default_config)
            return open_dialog.getFileName()
    else:
        # Ask user to select a config file.
        open_dialog = OpenDialog('Select a config file', folder, default_config)
        return open_dialog.getFileName()
Beispiel #10
0
def run():
    # Choose a file to open
    od = OpenDialog("Choose multi-image file", None)
    srcDir = od.getDirectory()
    if srcDir is None:
        # User canceled the dialog
        return
    path = os.path.join(srcDir, od.getFileName())
    # Choose a directory to store each slice as a file
    targetDir = DirectoryChooser("Choose target directory").getDirectory()
    if targetDir is None:
        # User canceled the dialog
        return
    # Ready:
    cs = ChannelSeparator()
    cs.setId(path)
    print "cs", cs
    bf = BFVirtualStack(path, cs, False, False, False)
    for sliceIndex in xrange(1, bf.getSize() + 1):
        print "Processing slice", sliceIndex
        ip = bf.getProcessor(sliceIndex)
        sliceFileName = os.path.join(targetDir, str(sliceIndex) + ".tif")
        FileSaver(ImagePlus(str(sliceIndex), ip)).saveAsTiff(sliceFileName)
Beispiel #11
0
def measure(cell):
    print "Opening", cell.getPpcdImageFilePath()
    imp = Opener().openImage(cell.getPpcdImageFilePath()) # open preprocessed Image
    imps = ChannelSplitter.split(imp)
    a = ATA()
    a.setSilent(True)
    a.segAndMeasure(imps[0], imps[1])
    results = a.getLinkedArray()
    print results
    
    

#---- M A I N ----

od = OpenDialog("Open Experiment!", "") # string head, string default path
loadFile = open(path.join(od.getDirectory(), od.getFileName()))
experiment = pickle.load(loadFile)

c = experiment.getPositions()[0].getCells()[1]

measure(c)

'''for p in experiment.getPositions():
    for c in p.getCells():
        print c.getPosition().getID(), c.getID()
        print c.getRawImageFilePath()
        if c.isPreProcessed() == False:
            ppcdImp = preprocess(c)
            #save preprocessed image under ppcd path
            c.saveImp(c.getPpcdImageFilePath(), ppcdImp)'''
	def runOnFile(self, afile, show = True, jobnr = None):
		afile = str(afile)
		if afile == '' or afile is None:
			od = OpenDialog("Choose image file", None)
			if od.getFileName() == None:
				return
			afile = os.path.join(od.getDirectory(), od.getFileName())
		if '.log' in afile:
			return
		
		try:
			zk = ZeissKeys()
			msg = Message()
			print "Hi"
			if self.jobs is None:
				IJ.showMessage("You need to first set the parameters")
			
			if all([job['pip']=='None' for job in self.jobs]):
				IJ.showMessage("Nothing to do! At least on job different than None") 
				return 0
			
			#create a copy otherwise self.jobs gets overwritten
			jobs = copy.deepcopy(self.jobs)
			random.seed()
			
			#create a roiManager in case one is missing and reset it
			roim = RoiManager.getInstance()
			if roim == None:
				roim = RoiManager()
			roim.runCommand("reset")
			
			for i, job in enumerate(self.jobs):
				jobl = job #not really necessary
				if jobl['pip'] == 'None':
					continue
				self.JOBS_DICT[jobl['pip']] + jobl['task'] + "_" 
				
				if jobnr is not None:
					if jobnr == i:
						#force opening
						imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']), 1)
					else: 
						continue
				else:
					imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']))
				print imageDef
				jobl['channel'] = int(jobl['channel'])
				
				if imageDef is None:
					continue
				#clean up registry for errors
				IJ.log("Clean up errorMsg registry")
				IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_errormsg+" value=[""] windows=REG_SZ")
				
				[imageC, pixelSize, filepath, filename] = imageDef
				if jobl['channel'] > len(imageC):
					raise IOError('Expecting at least ' + str(jobl['channel']) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
				
				self.rois = [None]*self.nrOfJobs
				self.Segs = [None]*self.nrOfJobs
				self.Procs = [None]*self.nrOfJobs
				#switch color to Cyan for better visibility
				IJ.run(imageC[jobl['channel']-1], "Cyan", "")

				#segment
				self.Procs[i], self.Segs[i], validParticles, self.rois[i] = segmentChannel_Weka(imageC, **jobl)
				if validParticles is None:
					IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ")

				#write values to registry
				try:
					executeTask_Weka(validParticles, **jobl)
				except Exception, err:
					self.exitWithError(str(err))
					return
				
				if self.rois[i] is None:
					imageC[jobl['channel']-1].show()
					self.Segs[i].show()
					self.Procs[i].show()
					continue
				if validParticles is None:
					particle = []
				else:
					particle = [part[0] for part in validParticles]
				imgOut = autTool.createOutputImg(imageC[jobl['channel']-1], self.rois[i], particle)
				
				imgOut.show()	
				self.saveOutputImg(imgOut, filepath, i+1)			
				
			IJ.run("Collect Garbage", "")
from ij import IJ, ImagePlus  #load the FIJI modules
from ij.io import FileSaver
from ij.io import OpenDialog
import os
#from ij.measure import ResultsTable
from fiji.threshold import Auto_Threshold

IJ.run("Clear Results")

od = OpenDialog("Choose a file", None)
filename = od.getFileName()
directory = od.getDirectory()
path = od.getPath()

print filename
print directory
print path

imp = IJ.openImage(path)
imp.show()

IJ.run(imp, "8-bit", "")
imp = IJ.getImage()

hist = imp.getProcessor().getHistogram()
lowTH = Auto_Threshold.Otsu(hist)
print lowTH
imp.getProcessor().threshold(lowTH)
#pulled from http://wiki.cmci.info/documents/120206pyip_cooking/python_imagej_cookbook#pluginauto_threshold

#imp2 = IJ.getImage()
 
print(sys.path)
# extend the search path by $FIJI_ROOT/bin/
path.append('/home/ehrenfeu/.local/lib/python2.7')
path.append('/home/ehrenfeu/.local/lib/python2.7/site-packages/volpy')
# path.append('C:\\Devel\\imcf_toolbox\\lib\\python2.7')
# path.append('C:\\Devel\\imcf_toolbox\\lib\\python2.7\\volpy')

import fluoview as fv
from log import log, set_loglevel

# set_loglevel(1)

infile = OpenDialog("Choose a 'MATL_Mosaic.log' file", '*.log')
print(infile.getDirectory())
print(infile.getFileName())

# dc = DirectoryChooser("Choose a directory with a 'MATL_Mosaic.log' file")
# base = dc.getDirectory()

mf = base + 'MATL_Mosaic.log'

mosaic = fv.FluoViewMosaic(mf)
mosaic.write_all_tile_configs(fixpath=True)
code = mosaic.gen_stitching_macro_code('stitching', base)
flat = ""
for line in code:
	flat += line

#print flat
IJ.runMacro(flat)
Beispiel #15
0
def open_Octopus_file():

	# set up a file info structure
	fi = FileInfo()
	fi.fileFormat = fi.RAW
	fi.fileType=FileInfo.GRAY16_UNSIGNED
	fi.intelByteOrder = True
	fi.nImages = 1

	op = OpenDialog("Choose Octopus .dth file...", "")
	if not op.getDirectory(): return False

	# get the file extension
	file_extension = re.search('(\.[a-z][a-z][a-z])', op.getFileName()).group(1)
	
	if file_extension != ".dth":
		dlg = GenericDialog("Warning")
		dlg.addMessage("Please select an octopus .dth file")
		dlg.showDialog()
		return False

	# now strip the filename into a stem and index
	file_parse = re.match('([a-zA-z0-9_]*_)([0-9]+)\.dth', op.getFileName())
	file_stem = file_parse.group(1)
	file_index = int( file_parse.group(2) )

	# ok now we need to parse the header info
	header = get_Octopus_header(op.getDirectory(), file_stem, file_index)
	fi.nImages  = len(header['N'])

	# check to see whether we have a bit depth, if not, assume 16-bit
	if 'Bit_Depth' in header:
		print header['Bit_Depth']
		bit_depth = int(header['Bit_Depth'][0])
		if bit_depth == 8: fi.fileType = FileInfo.GRAY8
	else:
		bit_depth = 16

	# will assume that all files have the same size
	fi.width = int( header['W'][0] )
	fi.height = int( header['H'][0] )
	file_timestamp = strftime("%a, %d %b %Y %H:%M:%S", gmtime(float(header['Time'][0])) )
	

	# make a new imagestack to store the data
	stack = ImageStack(fi.width, fi.height)

	# finally, we need to make a list of files to import as sometimes we have
	# non contiguous file numbers
	try:
		files = os.listdir(op.getDirectory())
	except IOError:
		raise IOError( "No files exist in directory: " + op.getDirectory())

	filenums = []
	for f in files:
		# strip off the stem, and get the number
		targetfile = re.match(file_stem+'([0-9]+)\.dth', f)
		# only take thosefiles which match the formatting requirements
		if targetfile:
			filenums.append( int(targetfile.group(1)) )

	# sort the file numbers
	sorted_filenums = sorted(filenums)

	# make a file stats string
	file_stats_str = file_stem + '\n' + str(fi.width) +'x' + str(fi.height) + 'x' + \
		str(len(sorted_filenums)) +' ('+str(bit_depth)+'-bit)\n' + file_timestamp


	# now open a dialog to let the user set options
	dlg = GenericDialog("Load Octopus Stream (v"+__version__+")")
	dlg.addMessage(file_stats_str)
	dlg.addStringField("Title: ", file_stem)
	dlg.addNumericField("Start: ", 1, 0);
	dlg.addNumericField("End: ", len(sorted_filenums), 0)
	dlg.addCheckbox("Open headers", True)
	dlg.addCheckbox("Contiguous stream?", False)
	dlg.addCheckbox("8-bit unsigned", bit_depth==8)
	dlg.showDialog()

	# if we cancel the dialog, exit here
	if dlg.wasCanceled():
		return

	# set some params
	file_title = dlg.getNextString()
	file_start = dlg.getNextNumber()
	file_end = dlg.getNextNumber()
	DISPLAY_HEADER = bool( dlg.getNextBoolean() )

	# check the ranges
	if file_start > file_end: 
		file_start, file_end = file_end, file_start
	if file_start < 1: 
		file_start = 1
	if file_end > len(sorted_filenums): 
		file_end = len(sorted_filenums) 

	# now set these to the actual file numbers in the stream
	file_start = sorted_filenums[int(file_start)-1]
	file_end = sorted_filenums[int(file_end)-1]

	files_to_open = [n for n in sorted_filenums if n>=file_start and n<=file_end]

	# if we've got too many, truncate the list
	if (len(files_to_open) * fi.nImages * fi.width * fi.height) > (MAX_FRAMES_TO_IMPORT*512*512):
		dlg = GenericDialog("Warning")
		dlg.addMessage("This may use a lot of memory. Continue?")
		dlg.showDialog()
		if dlg.wasCanceled(): return False

	IJ.log( "Opening file: " + op.getDirectory() + op.getFileName() )
	IJ.log( file_stats_str + "\nFile range: " + str(files_to_open[0]) + \
		"-" + str(files_to_open[-1]) +"\n" )

	# make a results table for the metadata
	# NOTE: horrible looping at the moment, but works
	if DISPLAY_HEADER:
		rt = ResultsTable()

	# ok now we can put the files together into the stack
	for i in files_to_open:

		# open the original .dat file and get the stack
		fi.fileName = get_Octopus_filename( op.getDirectory(), file_stem, i)
		
		if os.path.isfile( fi.fileName ):
			fo = FileOpener(fi)
			imp = fo.open(False).getStack() 
	
			# put the slices into the stack
			for im_slice in xrange( imp.getSize() ):
				ip = imp.getProcessor( im_slice+1 )
				if bit_depth == 8:
					bi = ip.getBufferedImage()
				else:
					bi = ip.get16BitBufferedImage() 
				stack.addSlice( file_title,  ip )


			if DISPLAY_HEADER:
				header = get_Octopus_header(op.getDirectory(), file_stem, i)
				for n in xrange(len(header['N'])):
					rt.incrementCounter()
					for k in header.keys():
						rt.addValue(k, parse_header( header[k][n] ) )

		else:
			break

	# done!
	output = ImagePlus('Octopus ('+file_stem+')', stack)
	output.show()

	if DISPLAY_HEADER:
		rt.show("Octopus header metadata")

	return True
Beispiel #16
0
"""
insert_scale.py

Jose Guzman, [email protected]
Created: Thu Apr 30 16:54:58 CEST 2020

This is an ImageJ-pluging writen in python that inserts a 2 mm scalebar
on the image selected.
To install the plugin sue Plugins->Install Pluging... in Fiji and 
select this file.
"""

from ij import IJ, ImagePlus
from ij import WindowManager
from ij.io import OpenDialog

op = OpenDialog("Select an image")

img = IJ.openImage(op.getPath())

mytitle = op.getFileName()[:-4] + '_2mm.tiff'
# Reduce size 50%
myimg = IJ.run(img, "Scale...", "x=0.5 y=0.5 width=1024 height=768 interpolation=Bilinear average create title=" + str(mytitle))
IJ.run(myimg, "Set Scale...", "distance=65 known=1 unit=mm")
IJ.run(myimg, "Scale Bar...", "width=2 height=6 font=20 color=White background=None location=[Lower Right]") # 2 mm

if __name__ in ['__builtin__', '__main__']:
	pass
	
Beispiel #17
0
def main():

    # start with the sequence parameters
    fieldNames = ["Number of views", "Number of projections for each view",
                  "Number of images for each projection (normally 1)",
                  "Number of flats in each set", "Number of darks in each set",
                  "Number of projections between each set of flats/darks"]
    fieldValues = []  # we start with zeros for the values

    # get user variables with imageJ dialog
    dialog = GenericDialog("Enter Scan Information")
    for i in range(6):
        dialog.addNumericField(fieldNames[i], 0, 0)
    dialog.addCheckbox("Two sets flats/darks between views?", False)
    dialog.showDialog()
    if dialog.wasCanceled():
        return  # exit function
    for i in range(6):
        fieldValues.append(int(dialog.getNextNumber()))
    extra = dialog.getNextBoolean()
    # make sure that none of the fields was left blank
    errmsg = ""
    for i in range(len(fieldNames)):
        if fieldValues[i] == "":
            errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
        try:
            int(fieldValues[i])
        except ValueError:
            errmsg += ('"%s" has to be an integer value.\n\n' %
                       fieldNames[i])
    if fieldValues[1] and fieldValues[5]:
        if int(fieldValues[1]) % int(fieldValues[5]) != 0:
            errmsg += ('Flat/Dark interval must divide evenly into projections\n\n')
    if errmsg != "":
        err_msg = GenericDialog("Error in Input")
        err_msg.addMessage(errmsg)
        err_msg.showDialog()
        return  # exit
    if fieldValues is None:
        return  # exit function
    fieldValues = [int(i) for i in fieldValues]
    # get the first item of the sequence using an imageJ dialog
    openFile = OpenDialog(
        "Select the first file of the sequence to rename.", None)
    fileName = openFile.getFileName()
    if fileName is None:
        return  # exit function
    fileDir = openFile.getDirectory()
    first = fileDir + fileName
    path1, filename = os.path.split(first)
    basename = short(filename)
    # get directory for new files using imageJ dialog
    openOutDir = DirectoryChooser("Select directory for new files.")
    path2 = openOutDir.getDirectory()
    if path2 is None:
        return  # exit function
    new_seq, fd_seq = gen_seq(fieldValues[0], fieldValues[1], fieldValues[2],
                              fieldValues[3], fieldValues[4], fieldValues[5],
                              extra)
    result = rename(basename, new_seq, fd_seq, path1, path2, fieldValues[0])
    print result
Beispiel #18
0
 def browse(self, event):
     od = OpenDialog("Select Position", "")
     filePath = path.join(od.getDirectory(), od.getFileName())
     self.pathField.text = filePath    
def getFile():
    od = OpenDialog("Choose image file", None)
    filename = od.getFileName()
    directory = od.getDirectory()
    filepath = directory + filename
    return filepath
def processFile():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for file
	ofd = OpenDialog("Choose a file", None)  
	filename = ofd.getFileName()  
  
	if filename is None:  
  		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
  		return

  	directory = ofd.getDirectory()  
  	filepath = directory + filename  
  	IJ.log("File path: " + filepath)

	if not filename.endswith(".oir"):
		IJ.log("Not an Olympus (.oir) file.\nNo image to process.\n")
		return

	filenameExExt = os.path.splitext(filename)[0]
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())

	# ask user to identify dichroic mirror used for each channel  
	gdDM = GenericDialog("Dichroic mirrors")
	DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] 
	for i in range(numChannels):
		gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0])
	gdDM.addCheckbox("Merge channels", False) 
	gdDM.showDialog()
	if gdDM.wasCanceled():
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
		return
	dichroics = []
	for i in range(numChannels):
		dichroics.append(gdDM.getNextChoice())
	merge = gdDM.getNextBoolean()
	IJ.log("\nUser selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])	

	if merge:
		channels = []
		chDict = {}
		for i in range(numChannels):
			chName = "Channel"+str(i+1)
			channels.append(chName)
			chDict[chName] = i
		channels.append("NONE")
		colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"]
		gdMerge = GenericDialog("Merge channels")
		for c in colourChoices:
			gdMerge.addChoice(c + ":", channels, channels[numChannels])
		gdMerge.showDialog()
		if gdMerge.wasCanceled():
			IJ.log("User canceled the dialog!\nImage processing canceled!\n")
			return
		IJ.log("\nUser selected channel colours")
		mergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				mergeList.append(None)
			else:
				mergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	od = dc.getDirectory()    
	if od is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
  
	if merge:
		tifDir = od + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = od + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		mergedChannelFilepath = od + filenameExExt + ".tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)
			
	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + od + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
Beispiel #21
0
from ij.gui import Plot, Arrow
from jarray import array
from ij.io import OpenDialog
import csv
from org.apache.commons.lang import ArrayUtils
import java.awt.Color

scale = 5

od = OpenDialog("Choose a file", "")
folder = od.getDirectory()
fName = od.getFileName()
path = folder + fName
x1 = []
y1 = []
x2 = []
y2 = []
dx = []
dy = []

#Draw Circles radii 30
cx = []
cy = []

for x in range(-7, 8, 1):
    for y in range(-7, 8, 1):
        if ((x**2) + (y**2)) <= (7.5**2):
            cx.append(x)
            cy.append(y)

fReader = csv.reader(open(path), delimiter=",")
Beispiel #22
0
def filechooser():
    od = OD("Choose image data file...")
    return (od.getPath(), od.getFileName(), od.getDirectory())
def getFile():
	od = OpenDialog("Choose image file", None)  
	filename = od.getFileName()  
	directory = od.getDirectory()  
	filepath = directory + filename
	return filepath 	
import os
from ij.io import OpenDialog
from ij import IJ
from ij.gui import PointRoi
#from ij import WindowManager as WM
#import ij.macro.Functions # import makeSelection

########################
# Open file dialog
########################
od = OpenDialog("Select the file to import")
srcDir = od.getDirectory()
if srcDir is None:
    print("Cancelled by user")
else:
    filePathName = os.path.join(srcDir, od.getFileName())

    print("importing from file", filePathName)

    ########################
    # Get data
    ########################
    #text = File.openAsString(fileName).split("\n")
    f = open(filePathName, "r")
    text = f.readlines()

    #these are the column indexes
    header = text[0].rstrip().split(",")
    headerDict = dict([(header[i], i) for i in range(len(header))])
    iX = headerDict["X"]
    iY = headerDict["Y"]
Beispiel #25
0
from ij import IJ, ImagePlus, ImageStack
from ij.process import FloatProcessor
from array import zeros
from ij.io import OpenDialog
from ij.plugin.frame import RoiManager
import os

# this script requires that Roi Manager be closed !
#
# convert ROI file (*.roi, *.zip for .roi collection)
# to mask image(s), 0 as

odroi = OpenDialog("Choose a ROI file", None)
roifn = odroi.getFileName()

if roifn is None:
    print "User canceled the dialog!"
else:
    roidir = odroi.getDirectory()
    roipath = os.path.join(roidir, roifn)

odref = OpenDialog("Choose a reference image file", None)
reffn = odref.getFileName()

if reffn is None:
    print "User canceled the dialog!"
else:
    refdir = odref.getDirectory()
    refpath = os.path.join(refdir, reffn)

refImp = IJ.openImage(refpath)
Beispiel #26
0
def regBf(fn=None, imp=None, refId=None):
    """ 
        Register a time series stack to a specified reference slice, 
            from a file (imported by BioFormat) or a stack ImagePlus.
        Returns a registered ImagePlus.
        The stack must have only 1 z layer.
        refId is in the format of [int channel, int slice, int frame]
            If no refId is supplied, will use the first slice [1,1,1]

        Note: since TurboReg is used for registeration, there will be 
            temporary opened image windows.

    """

    ## Prepare the right ImagePlus
    if imp is None:
        if fn is None:
            od = OpenDialog("Choose a file", None)
            filename = od.getFileName()

            if filename is None:
                print "User canceled the dialog!"
                return
            else:
                directory = od.getDirectory()
                filepath = directory + filename
                print "Selected file path:", filepath
        else:
            if os.path.exists(fn) and os.path.isfile(fn):
                filepath = fn
            else:
                print "File does not exist!"
                return

        imps = BF.openImagePlus(filepath)
        imp = imps[0]
        if imp is None:
            print "Cannot load file!"
            return

    else:
        if fn is not None:
            print "File or ImagePlus? Cannot load both."
            return

    width = imp.getWidth()
    height = imp.getHeight()
    # C
    nChannels = imp.getNChannels()
    # Z
    nSlices = imp.getNSlices()
    # T
    nFrames = imp.getNFrames()
    # pixel size
    calibration = imp.getCalibration()

    # Only supoort one z layer
    if nSlices != 1:
        print "Only support 1 slice at Z dimension."
        return

    # set registration reference slice
    if refId is None:
        refC = 1
        refZ = 1
        refT = 1
    else:
        refC = refId[0]
        refZ = refId[1]
        refT = refId[2]
        if (refC not in range(1, nChannels + 1)
                or refZ not in range(1, nSlices + 1)
                or refT not in range(1, nFrames + 1)):
            print "Invalid reference image!"
            return

    stack = imp.getImageStack()
    registeredStack = ImageStack(width, height, nChannels * nFrames * nSlices)

    # setup windows, these are needed by TurboReg
    tmpip = FloatProcessor(width, height)
    refWin = ImageWindow(ImagePlus("ref", tmpip))
    bounds = refWin.getBounds()
    # refWin.setVisible(False)
    toRegWin = ImageWindow(ImagePlus("toReg", tmpip))
    toRegWin.setLocation(bounds.width + bounds.x, bounds.y)
    # toRegWin.setVisible(False)
    toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip))
    toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y)
    # toTransformWin.setVisible(False)

    # get reference image
    refImp = ImagePlus("ref",
                       stack.getProcessor(imp.getStackIndex(refC, refZ, refT)))
    refWin.setImage(refImp)

    tr = TurboReg_()

    for t in xrange(1, nFrames + 1):
        IJ.showProgress(t - 1, nFrames)

        # print "t ", t
        # do TurboReg on reference channel
        toRegId = imp.getStackIndex(refC, refZ, t)
        toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId))
        toRegWin.setImage(toRegImp)

        regArg =  "-align " +\
                  "-window " + toRegImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-window " + refImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-rigidBody " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  "-hideOutput"

        tr = TurboReg_()
        tr.run(regArg)
        registeredImp = tr.getTransformedImage()
        sourcePoints = tr.getSourcePoints()
        targetPoints = tr.getTargetPoints()

        registeredStack.setProcessor(registeredImp.getProcessor(), toRegId)

        # toRegImp.flush()

        # apply transformation on other channels
        for c in xrange(1, nChannels + 1):
            # print "c ", c
            if c == refC:
                continue

            toTransformId = imp.getStackIndex(c, 1, t)
            toTransformImp = ImagePlus("toTransform",
                                       stack.getProcessor(toTransformId))
            toTransformWin.setImage(toTransformImp)

            transformArg = "-transform " +\
                           "-window " + toTransformImp.getTitle() + " " +\
                           str(width) + " " + str(height) + " " +\
                           "-rigidBody " +\
                           str(sourcePoints[0][0]) + " " +\
                           str(sourcePoints[0][1]) + " " +\
                           str(targetPoints[0][0]) + " " +\
                           str(targetPoints[0][1]) + " " +\
                           str(sourcePoints[1][0]) + " " +\
                           str(sourcePoints[1][1]) + " " +\
                           str(targetPoints[1][0]) + " " +\
                           str(targetPoints[1][1]) + " " +\
                           str(sourcePoints[2][0]) + " " +\
                           str(sourcePoints[2][1]) + " " +\
                           str(targetPoints[2][0]) + " " +\
                           str(targetPoints[2][1]) + " " +\
                           "-hideOutput"

            tr = TurboReg_()
            tr.run(transformArg)
            registeredStack.setProcessor(
                tr.getTransformedImage().getProcessor(), toTransformId)

            # toTransformImp.flush()
            sourcePoints = None
            targetPoints = None

        IJ.showProgress(t, nFrames)
        IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames))

    refWin.close()
    toRegWin.close()
    toTransformWin.close()

    imp2 = ImagePlus("reg_" + imp.getTitle(), registeredStack)
    imp2.setCalibration(imp.getCalibration().copy())
    imp2.setDimensions(nChannels, nSlices, nFrames)
    # print "type ", imp.getType()
    # print "type ", imp2.getType()
    # print nChannels, " ", nSlices, " ", nFrames
    # print registeredStack.getSize()

    for key in imp.getProperties().stringPropertyNames():
        imp2.setProperty(key, imp.getProperty(key))
    # comp = CompositeImage(imp2, CompositeImage.COLOR)
    # comp.show()
    # imp2 = imp.clone()
    # imp2.setStack(registeredStack)
    # imp2.setTitle("reg"+imp.getTitle())
    # imp2.show()
    # imp.show()

    return imp2
			continue

		# print out all .tif files in folder
		tifList = glob.glob(folder + '*')
		numTif = len(tifList)
		bPrintLog(time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime()),1)
		bPrintLog('[Folder ' + str(i) + ' of ' + str(numFolders) + '] with ' + str(numTif) + ' tif files in folder ' + folder, 1)
		for tif in tifList:
			bPrintLog(tif, 2)
			
		# do it
		bPrintLog('=== bALignBatchBatch is starting alignment on all stacks in folder: ' + folder, 2)
		#bALignBatch.runOneFolder(folder)

		i += 1

	bPrintLog('bAlignBatchBatch done at', 0)
#
if __name__ == '__main__': 

	srcDir = OpenDialog('Select a text file with your folders to batch process')
	print srcDir
	if srcDir:
		print srcDir.getDirectory()
		print srcDir.getFileName()
		fullPath = srcDir.getDirectory() + srcDir.getFileName()
		opentextfile(fullPath)
		# run()
	else:
		bPrintLog('Cancelled by user', 0)
		
Beispiel #28
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:
from ij import IJ, ImagePlus, ImageStack
from ij.process import FloatProcessor  
from array import zeros  
from ij.io import OpenDialog 
from ij.plugin.frame import RoiManager
import os

# this script requires that Roi Manager be closed !
#
# convert ROI file (*.roi, *.zip for .roi collection) 
# to mask image(s), 0 as 

odroi = OpenDialog("Choose a ROI file", None)
roifn = odroi.getFileName()

if roifn is None:
    print "User canceled the dialog!"
else:
    roidir = odroi.getDirectory()
    roipath = os.path.join(roidir, roifn)

odref = OpenDialog("Choose a reference image file", None)
reffn = odref.getFileName()

if reffn is None:
    print "User canceled the dialog!"
else:
    refdir = odref.getDirectory()
    refpath = os.path.join(refdir, reffn)

refImp = IJ.openImage(refpath)
Beispiel #30
0
#basename = os.path.splitext(filename)[0]
# print(basename)
#imp = IJ.openImage(srcpath)
# imp = IJ.getImage()

CELLAREA = 36.7  # in um2
PIXSIZE = 0.307
CELLDENSITY = .000878  # cells per um2
CHANNEL = 3  # red channel
TRIALS = 5  # number of simulations

# user chooses the file
od = OpenDialog("Choose multi-image file", None)
srcDir = od.getDirectory()
# print("directory = "+srcDir)
filename = od.getFileName()
# print("file = "+filename)
path = os.path.join(srcDir, od.getFileName())
basename = os.path.splitext(filename)[0]
# print("base = "+basename)
# print("path = "+path)

# get the target image
imp = IJ.openImage(path)
imp = IJ.getImage()

# get image size, dimensions, nChannels
width = imp.getWidth()
height = imp.getHeight()
composite = imp.isComposite()
if composite:
Beispiel #31
0
            '[Folder ' + str(i) + ' of ' + str(numFolders) + '] with ' +
            str(numTif) + ' tif files in folder ' + folder, 1)
        for tif in tifList:
            bPrintLog(tif, 2)

        # do it
        bPrintLog(
            '=== bALignBatchBatch is starting alignment on all stacks in folder: '
            + folder, 2)
        #bALignBatch.runOneFolder(folder)

        i += 1

    bPrintLog('bAlignBatchBatch done at', 0)


#
if __name__ == '__main__':

    srcDir = OpenDialog(
        'Select a text file with your folders to batch process')
    print srcDir
    if srcDir:
        print srcDir.getDirectory()
        print srcDir.getFileName()
        fullPath = srcDir.getDirectory() + srcDir.getFileName()
        opentextfile(fullPath)
        # run()
    else:
        bPrintLog('Cancelled by user', 0)
import os
import math
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ
from ij import WindowManager

# Gets the input LSM image
theOpenDialog = OpenDialog("Choose large LSM file to open...")
theFilePath = theOpenDialog.getPath()
if not(theFilePath is None):
	theDirectory = theOpenDialog.getDirectory()
	theFileName = theOpenDialog.getFileName()
	baseName = os.path.splitext(theFileName)[0]
		
	# Creates the output directory
	if not os.path.exists(theDirectory + baseName + "_resized"):
		os.mkdir(theDirectory + baseName + "_resized")

	# Asks for parameters
	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Start tile:",1,0)
	gd.addNumericField("Finish tile:",9,0)
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addNumericField("Step size (higher is faster but uses more memory):",10,0)
	gd.showDialog()
	startTile = int(gd.getNextNumber())
	finishTile = int(gd.getNextNumber())
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
	stepSize = int(gd.getNextNumber())
from ij import IJ, ImagePlus, ImageStack
from ij.process import ImageStatistics as IS
from ij.gui import Plot as Plot
from ij.gui import PlotWindow as PlotWindow
from ij.io import OpenDialog
#from loci.plugins.util import BFVirtualStack

# there are two ways to use the BioFormats importer: using the BioFormats API, and using the 
# IJ namespace function run() to use the standard macro language input.

# BioFormats API has more options I think, but for now the run() thing is working.  
# can I see this in git diff??

od = OpenDialog("Choose a file", None)
filename = od.getFileName()

if filename is None:
    print "You clicked cancel!"
else:
    directory = od.getDirectory()
    path = directory + filename
    print "Selected file path:", path

IJ.run("Bio-Formats Importer", "open=" + path + " color_mode=Grayscale view=Hyperstack stack_order=XYCZT use_virtual_stack");

#loading in the active ImagePlus and stack
imp = IJ.getImage()
stack = imp.getImageStack()

#how big is it?  set whether to use slices or frames for looping
sys.path.append(os.path.realpath(imctool_dir))

import imctools.imagej.library as lib


def view_image5d_ome(img, ome_meta):
    """

    :param img:
    :param ome_meta:
    :return:
    """
    nchannels = ome_meta.getChannelCount(0)
    channel_names = [ome_meta.getChannelName(0, i) for i in range(nchannels)]

    img = lib.get_image5d(imgName=ome_meta.getImageName(0),
                          img_stack=img.getStack(),
                          channel_names=channel_names)

    img.show()


def load_and_view(file_name):
    (imag, omeMeta) = lib.load_ome_img(file_name)
    view_image5d_ome(imag, omeMeta)


op = OpenDialog('Choose multichannel TIFF')
file = os.path.join(op.getDirectory(), op.getFileName())
load_and_view(file_name=file)
def regBf(fn=None, imp=None, refId=None):
    """ 
        Register a time series stack to a specified reference slice, 
            from a file (imported by BioFormat) or a stack ImagePlus.
        Returns a registered ImagePlus.
        The stack must have only 1 z layer.
        refId is in the format of [int channel, int slice, int frame]
            If no refId is supplied, will use the first slice [1,1,1]

        Note: since TurboReg is used for registeration, there will be 
            temporary opened image windows.

    """

    ## Prepare the right ImagePlus
    if imp is None:
        if fn is None:
            od = OpenDialog("Choose a file", None)
            filename = od.getFileName()

            if filename is None:
                print "User canceled the dialog!"
                return
            else:
                directory = od.getDirectory()
                filepath = directory + filename
                print "Selected file path:", filepath
        else:
            if os.path.exists(fn) and os.path.isfile(fn):
                filepath = fn
            else:
                print "File does not exist!"
                return

        imps = BF.openImagePlus(filepath)
        imp = imps[0]
        if imp is None:
            print "Cannot load file!"
            return

    else:
        if fn is not None:
            print "File or ImagePlus? Cannot load both."
            return

    width = imp.getWidth()
    height = imp.getHeight()
    # C
    nChannels = imp.getNChannels()
    # Z
    nSlices = imp.getNSlices()
    # T
    nFrames = imp.getNFrames()
    # pixel size
    calibration = imp.getCalibration()

    # Only supoort one z layer
    if nSlices != 1:
        print "Only support 1 slice at Z dimension."
        return

    # set registration reference slice
    if refId is None:
        refC = 1
        refZ = 1
        refT = 1
    else:
        refC = refId[0]
        refZ = refId[1]
        refT = refId[2]
        if (refC not in range(1, nChannels+1) or
            refZ not in range(1, nSlices+1) or
            refT not in range(1, nFrames+1) ):
            print "Invalid reference image!"
            return

    stack = imp.getImageStack()
    registeredStack = ImageStack(width, height, nChannels*nFrames*nSlices)

    # setup windows, these are needed by TurboReg
    tmpip = FloatProcessor(width, height)
    refWin = ImageWindow(ImagePlus("ref", tmpip))
    bounds = refWin.getBounds()
    # refWin.setVisible(False)
    toRegWin = ImageWindow(ImagePlus("toReg", tmpip))
    toRegWin.setLocation(bounds.width + bounds.x, bounds.y)
    # toRegWin.setVisible(False)
    toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip))
    toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y)
    # toTransformWin.setVisible(False)

    # get reference image
    refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT)))
    refWin.setImage(refImp)

    tr = TurboReg_()

    for t in xrange(1, nFrames+1):
        IJ.showProgress(t-1, nFrames)

        # print "t ", t
        # do TurboReg on reference channel
        toRegId = imp.getStackIndex(refC, refZ, t)
        toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId))
        toRegWin.setImage(toRegImp)

        regArg =  "-align " +\
                  "-window " + toRegImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-window " + refImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-rigidBody " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  "-hideOutput"
                
        tr = TurboReg_()
        tr.run(regArg)
        registeredImp = tr.getTransformedImage()
        sourcePoints = tr.getSourcePoints()
        targetPoints = tr.getTargetPoints()

        registeredStack.setProcessor(registeredImp.getProcessor(), toRegId)

        # toRegImp.flush()

        # apply transformation on other channels
        for c in xrange(1, nChannels+1):
            # print "c ", c
            if c == refC:
                continue

            toTransformId = imp.getStackIndex(c, 1, t)
            toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId))
            toTransformWin.setImage(toTransformImp)

            transformArg = "-transform " +\
                           "-window " + toTransformImp.getTitle() + " " +\
                           str(width) + " " + str(height) + " " +\
                           "-rigidBody " +\
                           str(sourcePoints[0][0]) + " " +\
                           str(sourcePoints[0][1]) + " " +\
                           str(targetPoints[0][0]) + " " +\
                           str(targetPoints[0][1]) + " " +\
                           str(sourcePoints[1][0]) + " " +\
                           str(sourcePoints[1][1]) + " " +\
                           str(targetPoints[1][0]) + " " +\
                           str(targetPoints[1][1]) + " " +\
                           str(sourcePoints[2][0]) + " " +\
                           str(sourcePoints[2][1]) + " " +\
                           str(targetPoints[2][0]) + " " +\
                           str(targetPoints[2][1]) + " " +\
                           "-hideOutput"

            tr = TurboReg_()
            tr.run(transformArg)
            registeredStack.setProcessor(tr.getTransformedImage().getProcessor(), toTransformId)

            # toTransformImp.flush()
            sourcePoints = None
            targetPoints = None

        IJ.showProgress(t, nFrames)
        IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames))

    refWin.close()
    toRegWin.close()
    toTransformWin.close()

    imp2 = ImagePlus("reg_"+imp.getTitle(), registeredStack)
    imp2.setCalibration(imp.getCalibration().copy())
    imp2.setDimensions(nChannels, nSlices, nFrames)
    # print "type ", imp.getType()
    # print "type ", imp2.getType()
    # print nChannels, " ", nSlices, " ", nFrames
    # print registeredStack.getSize()

    for key in imp.getProperties().stringPropertyNames():
        imp2.setProperty(key, imp.getProperty(key))
    # comp = CompositeImage(imp2, CompositeImage.COLOR)  
    # comp.show()
    # imp2 = imp.clone()
    # imp2.setStack(registeredStack)
    # imp2.setTitle("reg"+imp.getTitle())
    # imp2.show()
    # imp.show()

    return imp2