示例#1
0
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        self.dir_path = dc.getDirectory()

        self.choose_dir_textField.setText(self.dir_path)
        self.got_exper(self.dir_path)
示例#2
0
def run():
    srcDir = DirectoryChooser("Choose directory").getDirectory()
    if not srcDir:
        return

    targetDir = DirectoryChooser("Choose target directory").getDirectory()
    if targetDir is None:
        # User canceled the dialog
        return

    sId = ".tiff"

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            path = os.path.join(root, filename)
            if not (sId in filename):
                continue

            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 + filename + "_" +
                                             str(sliceIndex) + ".tiff")
                print "writing ", sliceFileName
                FileSaver(ImagePlus(str(sliceIndex),
                                    ip)).saveAsTiff(sliceFileName)
示例#3
0
def run():
    imp = IJ.getImage()
    if imp is None:
        return
    if not imp.isHyperStack():
        print "Not a hyper stack!"
        return
    if 1 == imp.getNFrames():
        print "There is only one time frame!"
        return
    if 1 == imp.getNSlices():
        print "To register slices of a stack, use 'Register Virtual Stack Slices'"
        return
    dc = DirectoryChooser("Choose target folder")
    target_folder = dc.getDirectory()
    if target_folder is None:
        return  # user canceled the dialog
    if not validate(target_folder):
        return
    gd = GenericDialog("Options")
    channels = []
    for ch in range(1, imp.getNChannels() + 1):
        channels.append(str(ch))
    gd.addChoice("channel:", channels, channels[0])
    gd.showDialog()
    if gd.wasCanceled():
        return
    channel = gd.getNextChoiceIndex() + 1  # zero-based
    vs_imp = create_registered_hyperstack(imp, target_folder, channel)
    vs_imp.show()
示例#4
0
def main():
    #filename = sys.argv[1]
    #exportDir = sys.argv[2]

    inputDir = "/mnt/med-groups-lmu/ls1/users/l/lsalomie/"
    defaultName = "lif.lif"
    outputDir = "/home/hajaalin/tmp/lifexporttest"

    filename = OpenDialog("Choose LIF",inputDir,defaultName).getPath()
    if not filename:
        # user canceled dialog
        return
    
    chooser = DirectoryChooser("Choose export directory")
    chooser.setDefaultDirectory(outputDir)
    exportDir = chooser.getDirectory()
    if not exportDir:
        # user canceled dialog
        return

    # EDF parameters
    params = Parameters()
    params.setQualitySettings(params.QUALITY_HIGH)
    params.nScales = 10

    worker = EdfWorker(exportDir,params)

    iterateLif(filename,worker)
示例#5
0
def ijGUI():
	from ij.io import DirectoryChooser
	dc = DirectoryChooser("Choose directory with Stratec files to scrub")
	dir_in = dc.getDirectory()
	dc = DirectoryChooser("Choose directory to write scrubbed files")
	dir_out = dc.getDirectory()
	idle_task_ij (process_files (dir_in, dir_out))
示例#6
0
def run():
  imp = IJ.getImage()
  if imp is None:
    return
  if not imp.isHyperStack():
    print "Not a hyper stack!"
    return
  if 1 == imp.getNFrames():
    print "There is only one time frame!"
    return
  if 1 == imp.getNSlices():
    print "To register slices of a stack, use 'Register Virtual Stack Slices'"
    return
  dc = DirectoryChooser("Choose target folder")
  target_folder = dc.getDirectory()
  if target_folder is None:
    return # user canceled the dialog
  if not validate(target_folder):
    return
  gd = GenericDialog("Options")
  channels = []
  for ch in range(1, imp.getNChannels()+1 ):
    channels.append(str(ch))
  gd.addChoice("channel:", channels, channels[0])
  gd.showDialog()
  if gd.wasCanceled():
    return
  channel = gd.getNextChoiceIndex() + 1  # zero-based
  vs_imp = create_registered_hyperstack(imp, target_folder, channel)
  vs_imp.show()
示例#7
0
    def actionPerformed(self, event):
        dlg = DirectoryChooser("Choose an output directory for the classifier")

        if os.path.exists(self.path):
            dlg.setDefaultDirectory(self.path)

        self.path = dlg.getDirectory()
        IJ.log("Added path: "+self.path)
示例#8
0
def choose_folder():
    dc = DirectoryChooser("Choose a folder.")
    folder = dc.getDirectory()

    if folder is None:
        print("User canceled the dialog.")
    else:
        print("Selected folder:", folder)
        return folder
示例#9
0
def getDir():
    dc = DirectoryChooser("Choose a folder")
    sourcePath = dc.getDirectory()
    if sourcePath is None:
        print "User canceled the dialog!"
    else:
        print "Selected folder:", sourcePath
    targetPath = sourcePath + '_figs/'  #figure out how to mkdir in script
    return sourcePath, targetPath
示例#10
0
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        # self.dir_path = dc.getDirectory()

        # self.dir_text_field.setText(self.dir_path)
        # self.dir_text_field.setText('blerg')
        # IJ.log('blerg')
        # print('boop')
        self.got_exper(dc.getDirectory())
示例#11
0
def output_folder_chooser(default_directory):
	"""choose where output data should be saved"""
	DirectoryChooser.setDefaultDirectory(default_directory);
	dc = DirectoryChooser('Select the folder for saving cropped images...');
	output_root = dc.getDirectory();
	if output_root is None:
		raise IOError('no output path chosen');
	timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S');
	output_folder = os.path.join(output_root, (timestamp + ' output'));
	os.mkdir(output_folder);
	return output_folder;
示例#12
0
def run():
    srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
    if srcDir is None:
        IJ.log("Choose Dir Canceled!")
        return

    outDir = DirectoryChooser("Chose >Output< Dir").getDirectory()
    if outDir is None:
        IJ.log("Output to same dir as source.")
        ourtDir = srcDir

    refImageId = getRefIdDialog()
    if refImageId is None:
        IJ.log("Select Reference Image Canceled!")
        return

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Skip non-ND2 files
            if not filename.endswith(".nd2"):
                continue
            inpath = os.path.join(root, filename)

            # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif"
            # outpath = os.path.join(outDir, outfn)
            # if os.path.exists(outpath):
            #     print "Skipped, already exists: ", outfn
            #     continue

            IJ.log("Registering\n" + filename)
            imp = regBf(fn=inpath, refId=refImageId)
            if imp is None:
                IJ.log("Skipped, wrong with registration:\n" + filename)
                continue
            else:
                # fs = FileSaver(imp)
                # fs.saveAsTiffStack(outpath)
                # IJ.saveAsTiff(imp, outpath)
                # print "Registered and saved to ", outfn
                splittedimps = ChannelSplitter.split(imp)
                for i, simp in enumerate(splittedimps):
                    outfn = "reg_" + os.path.splitext(
                        filename)[0] + "_C_" + str(i) + ".tif"
                    outpath = os.path.join(outDir, outfn)
                    if os.path.exists(outpath):
                        IJ.log("Skipped saving, file already exists:\n" +
                               outfn)
                        continue
                    IJ.saveAsTiff(simp, outpath)
                    IJ.log("Registered and saved to\n" + outfn)

    IJ.log("done!")
示例#13
0
def file_location_chooser(default_directory):
    """choose folder locations and prepare output folder"""
    # input
    file_path = input_file_location_chooser(default_directory)
    # output
    DirectoryChooser.setDefaultDirectory(os.path.dirname(file_path))
    dc = DirectoryChooser('Select the root folder for saving output')
    output_root = dc.getDirectory()
    if output_root is None:
        raise IOError('no output path chosen')
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    output_folder = os.path.join(output_root, (timestamp + ' output'))
    os.mkdir(output_folder)
    return file_path, output_folder
示例#14
0
def get_tif_list(parent_dir=DirectoryChooser("Choose").getDirectory()):

    if parent_dir is not None:
        tif_list = glob.glob(parent_dir + "*" + ".tif")
        return tif_list
    else:
        pass
def getFileList():
    default_root_path = r'D:\\data\Marcksl1 cell shape analysis\\MaximumProjections'
    file_list = []
    directory_list = []
    dc = DirectoryChooser('Select the root folder containing all data...')
    root_path = dc.getDirectory()
    if root_path is None:
        return file_list
    for directory, dir_names, file_names in os.walk(root_path):
        if (directory is not root_path):
            #file_list = [file_list.append(os.path.join(directory.replace(root_path, ''), file_name)) for file_name in file_names]
            file_list = [
                os.path.join(directory.replace(root_path, ''), file_name)
                for file_name in file_names if '.tif' in file_name
            ]
    return root_path, file_list
示例#16
0
def run():
    sId = IJ.getString("Filenames contain:", "T0000")
    srcDir = DirectoryChooser("Choose!").getDirectory()
    if not srcDir:
        # user canceled dialog
        return
    # Assumes all files have the same size
    stack = None
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Skip non-TIFF files
            if not (sId in filename):
                continue
            print(filename)
            path = os.path.join(root, filename)
            # Upon finding the first image, initialize the VirtualStack
            imp = IJ.openImage(path)
            if stack is None:
                # stack = VirtualStack(imp.width, imp.height, None, srcDir)
                stack = ImageStack(imp.width, imp.height)
            # Add a slice to the virtual stack, relative to the srcDir
            #
            #stack.addSlice(path[len(srcDir):])

            # Add a slice to the real stack
            #
            stack.addSlice(filename, imp.getProcessor())

    # Make a ImagePlus from the stack
    ImagePlus("Stack from subdirectories", stack).show()
示例#17
0
    def obtain_prefixes(self):
        self.sourceDir = DirectoryChooser(
            "Choose directory to load stack from").getDirectory()
        os.chdir(self.sourceDir)

        curdir = os.getcwd()
        listdire = os.listdir(curdir)

        prefixlist = []
        prefix_len = JOptionPane.showInputDialog(
            None,
            "how long is the file prefix to group by?(integer value only)")
        for name in listdire:
            if ".tif" in name:
                prefixname = name[:int(prefix_len)]
                prefixlist.append(prefixname)

        unique_prefix = sorted(set(prefixlist))
        self.pref_dict = {}

        for a in unique_prefix:
            pref_list = []
            for b in listdire:
                if b.startswith(a):
                    pref_list.append(b)
            self.pref_dict[a] = pref_list
        return self.pref_dict
示例#18
0
def run():
    helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \
               "and empty calibration infomation.\n\n" + \
               ">> Press OK to Select a directory of TIFF images."
    MessageDialog(IJ.getInstance(), "Empty Calibration Guide", helpText)

    srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
    if srcDir is None:
        IJ.log("Choose Dir Canceled!")
        return

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            if not filename.endswith(".tif"):
                continue
            imgPath = os.path.join(root, filename)
            outPath = os.path.join(root, "decal-" + filename)

            imp = IJ.openImage(imgPath)
            imp.setCalibration(Calibration())
            ic = ImageConverter(imp)
            ic.convertToGray8()
            IJ.saveAsTiff(imp, outPath)
            print "removed calibration and saved to ", os.path.basename(
                outPath)
示例#19
0
def run():
    bPrintLog(' ', 0)
    bPrintLog('=====================================', 0)
    bPrintLog('Running bAlign_Batch_v6', 0)
    bPrintLog('=====================================', 0)

    if len(sys.argv) < 2:
        print "   We need a hard-drive folder with .tif stacks as input"
        print "	  Usage: ./fiji-macosx bALign_Batch_6 <full-path-to-folder>/"
        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return 0
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    if not os.path.isdir(sourceFolder):
        bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n',
                  0)
        return 0

    if (Options(sourceFolder)):
        runOneFolder(sourceFolder)

    bPrintLog('=====================================', 0)
    bPrintLog('Done bAlign_Batch_v6', 0)
    bPrintLog('=====================================', 0)
    bPrintLog(' ', 0)
示例#20
0
def run():
    imp = IJ.getImage()
    if imp is None:
        return
    if not imp.isHyperStack():
        print "Not a hyper stack!"
        return
    if 1 == imp.getNFrames():
        print "There is only one time frame!"
        return
    if 1 == imp.getNSlices():
        print "To register slices of a stack, use 'Register Virtual Stack Slices'"
        return

    options = getOptions(imp)
    if options is not None:
        channel, virtual = options
        print "channel=" + str(channel) + " virtual=" + str(virtual)
    if virtual is True:
        dc = DirectoryChooser("Choose target folder to save image sequence")
        target_folder = dc.getDirectory()
        if target_folder is None:
            return  # user canceled the dialog
        if not validate(target_folder):
            return
    else:
        target_folder = None

    registered_imp = create_registered_hyperstack(imp, channel, target_folder,
                                                  virtual)
    if virtual is True:
        if 1 == imp.getNChannels():
            ip = imp.getProcessor()
            ip2 = registered_imp.getProcessor()
            ip2.setColorModel(ip.getCurrentColorModel())
            registered_imp.show()
        else:
            registered_imp.copyLuts(imp)
            registered_imp.show()
    else:
        if 1 == imp.getNChannels():
            registered_imp.show()
        else:
            registered_imp.copyLuts(imp)
            registered_imp.show()

    registered_imp.show()
示例#21
0
def get_file_list():
    parent_dir = DirectoryChooser("Choose").getDirectory()

    if parent_dir is not None:
        file_list = glob.glob(parent_dir + "*")
        return file_list
    else:
        pass
示例#22
0
def run():
  imp = IJ.getImage()
  if imp is None:
    return
  if not imp.isHyperStack():
    print "Not a hyper stack!"
    return
  if 1 == imp.getNFrames():
    print "There is only one time frame!"
    return
  if 1 == imp.getNSlices():
    print "To register slices of a stack, use 'Register Virtual Stack Slices'"
    return

  options = getOptions(imp)
  if options is not None:
    channel, virtual = options
    print "channel="+str(channel)+" virtual="+str(virtual)
  if virtual is True:
    dc = DirectoryChooser("Choose target folder to save image sequence")
    target_folder = dc.getDirectory()
    if target_folder is None:
      return # user canceled the dialog
    if not validate(target_folder):
      return
  else:
    target_folder = None 

  registered_imp= create_registered_hyperstack(imp, channel, target_folder, virtual)
  if virtual is True:
    if 1 == imp.getNChannels():
      ip=imp.getProcessor()
      ip2=registered_imp.getProcessor()
      ip2.setColorModel(ip.getCurrentColorModel())
      registered_imp.show()
    else:
    	registered_imp.copyLuts(imp)
    	registered_imp.show()
  else:
    if 1 ==imp.getNChannels():
    	registered_imp.show()
    else:
    	registered_imp.copyLuts(imp)
    	registered_imp.show()
  
  registered_imp.show()
示例#23
0
def run(debug=False):
    srcDir = DirectoryChooser("Batch Splitter: Chose Source Dir").getDirectory()
    # print srcDir
    # print type(srcDir)
    if srcDir is None:
        return

    sumf = open(os.path.join(srcDir, 'summary.z.txt'), 'w')
    # fn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry001.nd2'
    # # fn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry011.nd2'
    # outfn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry001.txt'

    zString = ["Z position for position, plane #01", "Z position for position, plane #001", "Z position for position #1, plane #1", "dZStep", "dZLow", "dZPos", "dZHigh"]

    for fn in os.listdir(srcDir):
        # Skip non-ND2 files
        if not fn.endswith(".nd2"):
            continue

        # get input and output filenames
        fullfn = os.path.join(srcDir, fn)
        outfn = os.path.splitext(fn)[0] + ".z.txt"
        fulloutfn = os.path.join(srcDir, outfn)
        # if os.path.exists(fulloutfn):
        #     print "Skipped, already exists: ", outfn
        #     continue

        print "Reading ", fn
        sumf.write(fn)
        sumf.write('\n')
        op = ImporterOptions()
        op.setId(fullfn)
        process = ImportProcess(op)
        process.execute()
        meta = process.getOriginalMetadata()

        print "Writing", fulloutfn
        # if debug:
            # print meta.getMetadataString('\t')
            # f.write('\n')
        f = open(fulloutfn, 'w')
        for k in meta.keySet():
            if debug and 'Z' in k:
                line = ''.join([k, '\t', str(meta[k])])
                f.write(line)
                f.write('\n')
            if k in zString:
                line = ''.join([k, '\t', str(meta[k])])
                f.write(line)
                f.write('\n')
                sumf.write(line)
                sumf.write('\n')                
        f.close()
        sumf.write('\n')
    sumf.close()
    print 'done.'
def file_location_chooser(default_directory):
    # input
    dc = DirectoryChooser('Select the root folder for loading input images')
    input_root = dc.getDirectory()
    if input_root is None:
        print("no input root")
    # output
    DirectoryChooser.setDefaultDirectory(default_directory)
    dc = DirectoryChooser('Select the root folder for saving output')
    output_root = dc.getDirectory()
    if output_root is None:
        print("no output root")
    return input_root, output_root
示例#25
0
 def clickEx(self):
     if self.exeunt == JOptionPane.YES_OPTION:
         print "confirmed"
         self.fileExt = str(self.filetype.getText())
         self.frame.setVisible(False)
         if self.saveState == "Y":
             self.saveDir = DirectoryChooser(
                 "Choose directory to save MIPs to").getDirectory()
         self.createMIP()
     else:
         print "cancelled"
def run():
    bPrintLog(' ', 0)
    bPrintLog('=====================================', 0)
    bPrintLog('Running bAlign_Batch_v7', 0)
    bPrintLog('=====================================', 0)

    if len(sys.argv) < 2:
        print "   We need a hard-drive folder with .tif stacks as input"
        print "	  Usage: ./fiji-macosx bALign_Batch_7 <full-path-to-folder>/"
        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return 0
        strippedFolder = sourceFolder.replace(' ', '')
        if sourceFolder != strippedFolder:
            print 'found a space in specified path. Pease remove spaces and try again.'
            print 'path:', sourceFolder
            errorDialog = GenericDialog('Align Batch 7 Options')
            errorDialog.addMessage('bAlignBatch7 Error !!!')
            errorDialog.addMessage('There can not be any spaces in the path.')
            errorDialog.addMessage('Please remove spaces and try again.')
            errorDialog.addMessage('Offending path is:')
            errorDialog.addMessage(sourceFolder)
            errorDialog.showDialog()
            return 0
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    if not os.path.isdir(sourceFolder):
        bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n',
                  0)
        return 0

    if (Options(sourceFolder)):
        runOneFolder(sourceFolder)

    bPrintLog('=====================================', 0)
    bPrintLog('Done bAlign_Batch_v7', 0)
    bPrintLog('=====================================', 0)
    bPrintLog(' ', 0)
def run():
	bPrintLog(' ', 0)
	bPrintLog('=====================================', 0)
	bPrintLog('Running bAlign_Batch_v7', 0)
	bPrintLog('=====================================', 0)

	if len(sys.argv) < 2:
		print "   We need a hard-drive folder with .tif stacks as input"
		print "	  Usage: ./fiji-macosx bALign_Batch_7 <full-path-to-folder>/"
		# Prompt user for a folder
		sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
		if not sourceFolder:
			return 0
		strippedFolder = sourceFolder.replace(' ', '')
		if sourceFolder != strippedFolder:
			print 'found a space in specified path. Pease remove spaces and try again.'
			print 'path:', sourceFolder
			errorDialog = GenericDialog('Align Batch 7 Options')
			errorDialog.addMessage('bAlignBatch7 Error !!!')
			errorDialog.addMessage('There can not be any spaces in the path.')
			errorDialog.addMessage('Please remove spaces and try again.')
			errorDialog.addMessage('Offending path is:')
			errorDialog.addMessage(sourceFolder)
			errorDialog.showDialog()
			return 0
	else:
		sourceFolder = sys.argv[1] #assuming it ends in '/'
	
	if not os.path.isdir(sourceFolder):
		bPrintLog('\nERROR: run() did not find folder: ' + sourceFolder + '\n',0)
		return 0

	
	if (Options(sourceFolder)):
		runOneFolder(sourceFolder)

	bPrintLog('=====================================', 0)
	bPrintLog('Done bAlign_Batch_v7', 0)
	bPrintLog('=====================================', 0)
        bPrintLog(' ', 0)
示例#28
0
def rerun_location_chooser(default_filepath):
    """choose folder containing a previous analysis run to reanalyse"""
    DirectoryChooser.setDefaultDirectory(os.path.dirname(default_filepath))
    dc = DirectoryChooser(
        'Select the folder containing the previous analysis output...')
    old_output_folder = dc.getDirectory()
    if old_output_folder is None:
        raise IOError('no input path chosen')
    # check that chosen folder contains the right files...
    files_lst = os.listdir(old_output_folder)
    #if not all([f in files_lst for f in ['user_defined_edges.zip', 'parameters used.json']]):
    if not 'parameters used.json' in files_lst or not (
        ('user_defined_edges.json' in files_lst) or
        ('user_defined_edges.zip' in files_lst)):
        raise IOError('chosen path isn'
                      't a valid membrane blebbing output folder')
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    new_output_folder = os.path.join(
        os.path.dirname(os.path.normpath(old_output_folder)),
        (timestamp + ' output'))
    os.mkdir(new_output_folder)
    return old_output_folder, new_output_folder
def get_tif_list():
    """
    Tiff file のリストを得る関数
    """
    from glob import glob
    from ij.io import DirectoryChooser

    parent_dir = DirectoryChooser("Choose").getDirectory()

    if parent_dir:
        tif_list = glob(parent_dir + "*" + ".tif")
        return tif_list
    else:
        pass
示例#30
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)
from ij.io import DirectoryChooser
import ij.ImageStack
from ij import IJ, ImagePlus
import os
import time

# Choose a directory containing the data
dc = DirectoryChooser("Choose directory containing embryo folders...")
srcDir = dc.getDirectory()
print(srcDir)
IJ.log('Root directory: ' + srcDir)

# Prepare output directories...
nowStr = time.strftime('%Y-%m-%d %H%M%S')
outputDir = os.path.join(srcDir, nowStr+ " results")
if not os.path.exists(outputDir):
	os.makedirs(outputDir)

# Loop through embryo sample directories, taking note of date and embryo number
folders=[f for f in os.listdir(srcDir)
	if os.path.isdir(os.path.join(srcDir,f)) and not (f.endswith('results'))]

for folder in folders:
	print(folder)
	IJ.log('Working on data in sample folder: ' + folder)
	(date, embryoNumber) = folder.split('_E')
	
	# Identify the indices of the files where cuts occur
	textFiles=[f for f in os.listdir(os.path.join(srcDir, folder))
	    if (f.endswith('.txt')) and not (f.endswith('para.txt'))]
示例#32
0
psgd.addNumericField("Which frame to choose?", 1, 0)
psgd.addCheckbox("Use table of selected frames?", False)
psgd.showDialog()
choose = psgd.getNextNumber()
choice = psgd.getCheckboxes().get(0).getState()

#open a tab separated txt file with one column Frame selected
if choice == 1:
    choose = 0
    IJ.run("Table... ", "open=")
    frametable = WM.getWindow("selected_frames.txt")
    meta = frametable.getTextPanel()
    metaRT = TP.getResultsTable(meta)

# Choose a directory
directory_load = DirectoryChooser(
    "Select the directory of your files").getDirectory()
directory_load = directory_load.replace("\\", "/")

# get a list of all files in the directory
dList = os.listdir(directory_load)
# set a counter to 1
n = 1

for i in dList:
    dL = directory_load + "/" + str(i)

    #consider only files with .ome file ending
    if ".ome" in dL:
        #open the images as virtual stack
        imp = IJ.run(
            "Bio-Formats", "open=[" + dL +
from ij.io import DirectoryChooser
from ij.gui import GenericDialog
from ij import IJ
from ij import WindowManager
import os
import glob

dirChooser = DirectoryChooser("Choose directory of images to normalize...")
dirPath = dirChooser.getDirectory()
scaleXs = []
if dirPath is not None:
	if not os.path.exists(dirPath + "resized"):
		os.mkdir(dirPath + "resized")

	gd = GenericDialog("Settings...")
	gd.addNumericField("Final scale factor:",0.5,2)
	gd.addCheckbox("Convert multichannel to RGB:",True)
	gd.showDialog()
	if (gd.wasOKed()):
		common_scale = gd.getNextNumber()
		convert_to_rgb = gd.getNextBoolean()
		filecollection = glob.glob(os.path.join(dirPath, '*.tif'))
		if (len(filecollection) > 0):
			for path in filecollection:
				theImage = IJ.openImage(path)
				calibration = theImage.getCalibration()
				scaleXs.append(calibration.pixelWidth)
				theImage.close()
			lc_scale = max(scaleXs)
			print lc_scale
			for path in filecollection:
def run():

  IJ.log("Correct_3D_Drift")
    
  imp = IJ.getImage()
  if imp is None:
    return
  if 1 == imp.getNFrames():
    print "There is only one time frame!"
    return

  options = getOptions(imp)
  if options is not None:
    channel, virtual, multi_time_scale, subpixel, process, only_compute = options
    
  if virtual is True:
    dc = DirectoryChooser("Choose target folder to save image sequence")
    target_folder = dc.getDirectory()
    if target_folder is None:
      return # user canceled the dialog
    if not validate(target_folder):
      return
  else:
    target_folder = None 

  # compute shifts
  IJ.log("  computing drifts..."); print("\nCOMPUTING SHIFTS:")

  IJ.log("    at frame shifts of 1"); 
  dt = 1; shifts = compute_and_update_frame_translations_dt(imp, channel, dt, process)
  
  # multi-time-scale computation
  if multi_time_scale is True:
    dt_max = imp.getNFrames()-1
    # computing drifts on exponentially increasing time scales 3^i up to 3^6
    # ..one could also do this with 2^i or 4^i
    # ..maybe make this a user choice? did not do this to keep it simple.
    dts = [3,9,27,81,243,729,dt_max] 
    for dt in dts:
      if dt < dt_max:
        IJ.log("    at frame shifts of "+str(dt)) 
        shifts = compute_and_update_frame_translations_dt(imp, channel, dt, process, shifts)
      else: 
        IJ.log("    at frame shifts of "+str(dt_max));
        shifts = compute_and_update_frame_translations_dt(imp, channel, dt_max, process, shifts)
        break

  # invert measured shifts to make them the correction
  shifts = invert_shifts(shifts)
  print(shifts)
  
  
  # apply shifts
  if not only_compute:
    
    IJ.log("  applying shifts..."); print("\nAPPLYING SHIFTS:")
    
    if subpixel:
      registered_imp = register_hyperstack_subpixel(imp, channel, shifts, target_folder, virtual)
    else:
      shifts = convert_shifts_to_integer(shifts)
      registered_imp = register_hyperstack(imp, channel, shifts, target_folder, virtual)
    
    
    if virtual is True:
      if 1 == imp.getNChannels():
        ip=imp.getProcessor()
        ip2=registered_imp.getProcessor()
        ip2.setColorModel(ip.getCurrentColorModel())
        registered_imp.show()
      else:
    	registered_imp.copyLuts(imp)
    	registered_imp.show()
    else:
      if 1 ==imp.getNChannels():
        registered_imp.show()
      else:
        registered_imp.copyLuts(imp)
        registered_imp.show()
  
    registered_imp.show()
  
  else:
   
    if imp.getRoi(): 
      xmin = imp.getRoi().getBounds().x
      ymin = imp.getRoi().getBounds().y
      zmin = 0
      xmax = xmin + imp.getRoi().getBounds().width - 1
      ymax = ymin + imp.getRoi().getBounds().height - 1
      zmax = imp.getNSlices()-1  
    else:
      xmin = 0
      ymin = 0
      zmin = 0
      xmax = imp.getWidth() - 1
      ymax = imp.getHeight() - 1
      zmax = imp.getNSlices() - 1  
    
    save_shifts(shifts, [xmin, ymin, zmin, xmax, ymax, zmax])
    IJ.log("  saving shifts...")
def get_files_and_analyze(folder):

  count = 0
  timeseries = []
  for root, directories, filenames in os.walk(folder):
    #print directories
    for directory in sorted(directories):
      #print directory
      if not (("field" in directory)): # "field is specific to the folder where the image files are"
        continue
      else:
        print os.path.join(root, directory)
        analyze(os.path.join(root, directory), 3, 7, 1)

  
          
if __name__ == '__main__':
  dc = DirectoryChooser("Choose top directory containing all Matrix Screener images")
  foldername = dc.getDirectory()
  #od = OpenDialog("Click on one of the image files in the folder to be analysed", None	)
  #filename = od.getFileName()
  #foldername = od.getDirectory()
  #print foldername
  
  print "\n\n\n\n\n\n"
  
  #foldername = "/g/almf/software/scripts/imagej/Data_MatrixScreenerImport"
  
  if None != foldername:
    print "foldername = "+foldername
    get_files_and_analyze(foldername)
from ij.plugin.filter import ParticleAnalyzer
from ij.plugin.frame import RoiManager
from ij.measure import Calibration
from loci.plugins import BF
from ij.io import FileSaver
from ij.measure import Measurements
from ij.process import ImageStatistics as IS
from java.awt import Color
from ij.io import DirectoryChooser
# Python imports
import os
import math
import sys

# Choose a folder that you want the images resized to the same scale
input_dc = DirectoryChooser("Choose a folder with images to be rescaled.")
inputDir = input_dc.getDirectory()

output_dc = DirectoryChooser("Choose output folder.")
outputDir = output_dc.getDirectory()

# What we need to do is crop EQUAL AREAS. First find the smallest
# image area.

# Find the minimum area per pixel
minArea = 999999
for filename in os.listdir(inputDir):
	if '.tif' in filename:
		print 'Opening ' , filename , '...'
		image = IJ.openImage(inputDir + '/' + filename)
		ip = image.getProcessor()
from ij import IJ
from ij.io import FileSaver, DirectoryChooser
from ij import ImagePlus
from ij.io import FileSaver
import jmFijiGen as jmg

tic = time.time()

sFac = 0.0
barW = 5						# bar width, microns
barH = 6						# bar height, pts
barF = 24						# bar font, pts
barC = "White"			# bar color
barL= "Lower Right"	# bar location

dc = DirectoryChooser("Choose directory")
basePath = dc.getDirectory()

sPngPath = basePath + os.sep + "png" + os.sep
jmg.ensureDir(sPngPath)


names = []

for file in os.listdir(basePath):
	if file.endswith(".tif"):
		name = os.path.splitext(file)[0]
		names.append(name)

names.sort()
示例#38
0
from ij.plugin import ChannelSplitter, RGBStackMerge, ZProjector, ContrastEnhancer, CompositeConverter, Duplicator
from ij.plugin.frame import RoiManager
from ij.process import Blitter, ImageConverter
from fiji.threshold import Auto_Threshold
from loci.plugins import BF
from loci.formats import UnknownFormatException

from algorithms import MandersColocalization
from net.imglib2 import TwinCursor
from net.imglib2.img import ImagePlusAdapter
from net.imglib2.view import Views
from gadgets import DataContainer
from gadgets import ThresholdMode


inputDialog = DirectoryChooser("Please select a directory contaning your images")
outputDialog = DirectoryChooser("Please select a directory to save your results")
inputDir = inputDialog.getDirectory()
outputDir = outputDialog.getDirectory()

imageA = 2  # Second channel
imageB = 3  # Third channel
methods = ["Mean", "Otsu"]


def createContainer(roi, imgA, imgB):
	rect = roi.getBounds()
	ipmask = roi.getMask()
	offset = [rect.x, rect.y]
	size = [rect.width, rect.height]
	if (ipmask != None):
示例#39
0
import glob
import os.path

from ij import IJ, ImagePlus, ImageStack, WindowManager
from ij.io import DirectoryChooser

from edfgui import ExtendedDepthOfField, Parameters

dc = DirectoryChooser("Set input directory")
files = glob.glob(dc.getDirectory() + "/*.tiff")

dc = DirectoryChooser("Set output directory")
outputDir = dc.getDirectory()

# EDF parameters
params = Parameters()
params.setQualitySettings(params.QUALITY_HIGH)

for f in files:
    imp = ImagePlus(f)

    # output name
    head,tail = os.path.split(f)
    base,ext = os.path.splitext(tail)
    output = os.path.join(outputDir,base + "_edf.tif")
    print output

    # make all-in-focus image
    edf = ExtendedDepthOfField(imp,params)
    edf.process()
from ij import IJ, WindowManager, Prefs
from ij.plugin.frame import RoiManager
from ij.measure import ResultsTable
from ij.gui import Roi, Toolbar, WaitForUserDialog
import os
from ij.io import DirectoryChooser, OpenDialog
from ij.process import ImageProcessor
from ij.plugin import ChannelSplitter

# Bioformats
from loci.plugins import BF
from loci.common import Region
from loci.plugins.in import ImporterOptions

# get input path for merge file
opener = DirectoryChooser("Select the input folder")
input_folder = opener.getDirectory()
print input_folder


#Define results output folder
folder = input_folder+"timepoints/"
if not os.path.exists(folder):
	os.mkdir(folder)

# collect list of files to be processed
#file_list = [filename for filename in os.listdir(input_folder) if ".tif" in filename]
# Recursive option
file_list = [os.path.join(dp, f) for dp, dn, fn in os.walk(input_folder) for f in fn if '.tif' in f]

for file_path in file_list:
示例#41
0
def loadStacks():

    IJ.log(" ")
    IJ.log(
        "oib concatenator v0.5.1; 2012; [email protected]; [email protected]; revised by [email protected]"
    )
    IJ.log("tested with: ImageJ 1.47a; FIJI update on July 20th 2012")

    srcDir = DirectoryChooser("Choose directory").getDirectory()
    if not srcDir:
        return

    sId = ".oib"

    #stackType = getChoice("", ["normal stack", "virtual stack"])
    stackType = "normal stack"  # Concatenate seems not to work with virtual
    #filepath = srcDir +"tiff"
    #print(filepath)
    iStack = 0
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            path = os.path.join(root, filename)
            if not (sId in filename):
                continue

            IJ.log("opening " + filename)

            if stackType == "virtual stack":
                IJ.run(
                    "Bio-Formats Importer", "open=" + path +
                    " color_mode=Default view=[Standard ImageJ] stack_order=Default use_virtual_stack"
                )
            else:
                IJ.run(
                    "Bio-Formats Importer", "open=" + path +
                    " color_mode=Default view=[Standard ImageJ] stack_order=Default"
                )

            # first stack
            if iStack == 0:
                imp = IJ.getImage()
                imp.setTitle(
                    filename +
                    ".tiff")  # in order of the combining to work additive
                nSlices = imp.getNSlices()
                nChannels = imp.getNChannels()
                nTimeFrames = imp.getNFrames()
                #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color");
                #IJ.log("convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack")
                fs = FileSaver(imp)
                fs.saveAsTiff(srcDir + filename + ".tiff")
            else:
                imp = IJ.getImage()
                imp.setTitle(
                    filename +
                    ".tiff")  # in order of the combining to work additive
                #IJ.run(imp,"Concatenate...", "image1=stack image2=st2 title=[stack]");
                #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color");
                #IJ.log("convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack")
                fs = FileSaver(imp)
                fs.saveAsTiff(srcDir + filename + ".tiff")
            iStack = iStack + 1
            print(iStack)

        IJ.log("nChannels = " + str(nChannels))
        IJ.log("nSlices = " + str(nSlices))
        IJ.log("nFrames = " + str(nTimeFrames * iStack))
        #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color");
        IJ.log(
            "convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack"
        )
        IJ.log(
            "if you got an error message from the hyperstack you probably ran out of memory and it did not load all files!"
        )
示例#42
0
	def selectInputDir(self):
		inputDialog = DirectoryChooser("Please select a directory contaning your images")
		inputDir = inputDialog.getDirectory()
		for imageFile in os.listdir(inputDir):
			self.files.append(inputDir + imageFile)
	arr1 = [x - mi for x in arr]
	arr2 = [x - ma for x in arr]
	start = find_index_greater_zero(arr1)
	end = find_index_greater_zero(arr2)
	length = end-start+1
	return [start,end,length]

def make_tile_series(xs,ys,xlen,ylen):
	arr = []
	for y in range(ys[0],ys[1]+1):
		arr.extend(range(xlen*y+xs[0],xlen*y+xs[1]+1))
	arr = [m+1 for m in arr]
	return arr

##### Sets directory of full-res tiles and gets metadata ######
dc = DirectoryChooser("Choose directory where full-res tiles are stored...")
imgDir = dc.getDirectory()
metadata = IJ.openAsString(imgDir+"tile_info.txt")
p = re.compile(r'X Tiles: (\d+)')
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))
if not os.path.exists(imgDir + "temp"):
		theSize = os.path.getsize(theFile)
		sumSize = sumSize + theSize
	return sumSize

def calculate_memory_recs(dirsize,maxmem):
	values = []
	maxchannel = maxmem / 10
	maxtot = long(maxmem * 0.3)
	for i in range(1,6):
		if (maxtot/i > maxchannel):
			values.append((maxchannel*i)/1048576)
		else:
			values.append(maxtot/1048576)
	return values

dc = DirectoryChooser("Choose directory with OME.TIF files...")
sourceDir = dc.getDirectory()

if not(sourceDir is None):
	if not os.path.exists(sourceDir + "resized"):
		os.mkdir(sourceDir + "resized")

	dirSize = get_directory_size(sourceDir)
	dirSizeMB = dirSize / 1048576
	memoryObj = Memory()
	memFiji = memoryObj.maxMemory()
	memFijiMB = memFiji / 1048576

	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Sizing_ratio (Final disk space / Initial disk space):",0.25,2)
	gd.addMessage("Directory size: " + str(dirSizeMB) + "MB")
示例#45
0
		except:
			IJ.log("failed")
			os.rmdir(outputName)
			wList = WindowManager.getIDList()
			for i in range(len(wList)):
				currImage = WindowManager.getImage(wList[i])
				currImage.close()
			returnVal = 1
	else:
		IJ.log("skipped")
		returnVal = 2

	return returnVal
	

dc = DirectoryChooser("Choose root directory")
rootPath = dc.getDirectory()
if rootPath is not None:
	gd = GenericDialog("Batch mode options...")
	gd.addStringField("Filename extension","lsm",6)
	gd.showDialog()
	if (gd.wasOKed()):
		extension = gd.getNextString()
		for root, dirs, files in os.walk(rootPath):
			LSMfiles = filter(lambda x: check_if_filetype(x,extension),files)
			if len(LSMfiles)>0:
				LSMpaths = map(lambda x: generate_path(x,root),LSMfiles)
				explodeStatuses = map(run_explode,LSMpaths)
				resizePaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),LSMpaths,explodeStatuses)))
				if len(resizePaths)>0:
					resizeStatuses = map(run_resize,resizePaths)
import glob
import os
from ij import IJ
from ij.io import DirectoryChooser
from ij.plugin import Memory

dc = DirectoryChooser("Choose directory of LSM files...")
dirPath = dc.getDirectory()
if dirPath is not None:
	fileList = glob.glob(dirPath+"*.lsm")

	for path in fileList:
		processImage = False
		theSize = os.path.getsize(path) / 1048576.0
		print theSize
		totFijiMem = Memory().maxMemory() / 1048576.0
		print totFijiMem
		if (theSize < totFijiMem/3.0):
			basename = os.path.splitext(os.path.basename(path))[0]
			outputPath = dirPath + basename + ".tif"
			if not os.path.exists(outputPath):
				processImage = True

			params = "type=[Positions from file] order=[Defined by image metadata] browse=[" + path + "] multi_series_file=[" + path + "] fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap ignore_z_stage increase_overlap=10 subpixel_accuracy computation_parameters=[Save memory (but be slower)] image_output=[Fuse and display]"
			print params
			if (processImage):
				try:
					IJ.run("Grid/Collection stitching", params)
					stitchedImage = IJ.getImage()
					IJ.saveAsTiff(stitchedImage,outputPath)
					stitchedImage.close()
示例#47
0
	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
homedir=IJ.getDirectory('imagej')
jythondir=os.path.join(homedir,'plugins/Evalulab/')
jythondir=os.path.abspath(jythondir)
sys.path.append(jythondir)

import PoreDetectionTrueColor
reload(PoreDetectionTrueColor)
from PoreDetectionTrueColor import runPoreDetection

import MessageStrings
reload(MessageStrings)
from MessageStrings import Messages

import Utility
reload(Utility)

if __name__ == '__main__':
	dlg=DirectoryChooser(Messages.ChooseImageDirectory)
	print dlg.getDirectory()

	imageList=Utility.getImageListFromDirectory(dlg.getDirectory())

	for imageName in imageList:
		fullImageName=os.path.join(dlg.getDirectory(), imageName)
		image=IJ.openImage(fullImageName)
		image.show()
		runPoreDetection(image, data, ops, display)
		image.close()
		
	
	retStr = yyyy + mm + dd
	return retStr


##################################################################################################
# main
##################################################################################################
"""
	print __name__
	This is coming up as '__builtin__' in Fiji downloaded on 20170810.
"""
if __name__ in ['__main__', '__builtin__']: 
	startTime = time.time()
	
	bPrintLog('\n=================')
	bPrintLog('Starting bFolder2MapManager')
	bPrintLog('*** IMPORTANT *** Using magic_scan_image_scale:' + str(magic_scan_image_scale) + ' for ScanImage files. voxel (um) = ' + str(magic_scan_image_scale) + '/zoom')
	
	#sourceFolder = '/Volumes/fourt/MapManager_Data/sarah_immuno/8.17.16/8.17.16.mdb/'
	sourceFolder = DirectoryChooser("Please Choose A Directory Of Files").getDirectory()

	outFiles = 0
	if (sourceFolder):
		outFiles = runOneFolder(sourceFolder)
	else:
		bPrintLog('Canceled by user', 0)
	
	stopTime = time.time()
	bPrintLog('Finished bFolder2MapManager with ' + str(outFiles) + ' files in ' + str(round(stopTime-startTime,2)) + ' seconds')
	bPrintLog('=================\n')
	
			type, path = sys.argv[1].split('=')
			bPrintLog('type:' + type)
			bPrintLog('path:' + path)
			if type == 'oneFile':
				alignFile = bAlignFile(path)
				if alignFile:
					alignFile.run()
			elif type == 'srcDir':
				alignFolder = bAlignFolder(path)
				if alignFolder:
					alignFolder.run()
		else:
			#ask user for folder, this is a folder that contains folders with single image .tif files
			
			# this asks for a folder
			path = DirectoryChooser("Please Choose A Directory Of .lsm Files").getDirectory()
			# this asks for a file
			#path = OpenDialog("xxx").getPath()
			
			if (path):
				print 'path:', path
				# '''
				if path.endswith('/'):
					alignFolder = bAlignFolder(path)
					if alignFolder:
						alignFolder.run()
				elif path.endswith('_ch2.tif'):
					alignFile = bAlignFile(path)
					if alignFile:
						alignFile.run()
				# '''
示例#51
0
def run(title):
    gd = GenericDialog("Record Window")
    gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.")
    gd.addNumericField("Max. frames:", 50, 0)
    gd.addNumericField("Milisecond interval:", 300, 0)
    gd.addSlider("Start in (seconds):", 0, 20, 5)
    frames = []
    titles = []
    for f in Frame.getFrames():
        if f.isEnabled() and f.isVisible():
            frames.append(f)
            titles.append(f.getTitle())
    gd.addChoice("Window:", titles, titles[0])
    gd.addCheckbox("To file", False)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    frame = frames[gd.getNextChoiceIndex()]
    delay = int(gd.getNextNumber())
    tofile = gd.getNextBoolean()

    dir = None
    if tofile:
        dc = DirectoryChooser("Directory to store image frames")
        dir = dc.getDirectory()
        if dir is None:
            return  # dialog canceled

    snaps = []
    borders = None
    executors = Executors.newFixedThreadPool(1)
    try:
        while delay > 0:
            IJ.showStatus("Starting in " + str(delay) + "s.")
            time.sleep(1)  # one second
            delay -= 1

        IJ.showStatus("Capturing frame borders...")
        bounds = frame.getBounds()
        robot = Robot()
        frame.toFront()
        time.sleep(0.5)  # half a second
        borders = robot.createScreenCapture(bounds)

        IJ.showStatus("Recording " + frame.getTitle())

        # Set box to the inside borders of the frame
        insets = frame.getInsets()
        box = bounds.clone()
        box.x = insets.left
        box.y = insets.top
        box.width -= insets.left + insets.right
        box.height -= insets.top + insets.bottom

        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        i = 1
        fus = None
        if tofile:
            fus = []

            # 0 n_frames means continuous acquisition
        while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval):
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                img = snapshot(frame, box)
                if tofile:
                    fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets)))  # will flush img
                    i += 1
                else:
                    snaps.append(img)
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)
                # interrupt capturing:
            if IJ.escapePressed():
                IJ.showStatus("Recording user-interrupted")
                break

                # debug:
                # print "insets:", insets
                # print "bounds:", bounds
                # print "box:", box
                # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight()

                # Create stack
        stack = None
        if tofile:
            for fu in snaps:
                fu.get()  # wait on all
            stack = VirtualStack(bounds.width, bounds.height, None, dir)
            files = File(dir).list(TifFilter())
            Arrays.sort(files)
            for f in files:
                stack.addSlice(f)
        else:
            stack = ImageStack(bounds.width, bounds.height, None)
            t = 0
            for snap, real_interval in zip(snaps, intervals):
                bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB)
                g = bi.createGraphics()
                g.drawImage(borders, 0, 0, None)
                g.drawImage(snap, insets.left, insets.top, None)
                stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor())
                t += real_interval
                snap.flush()
                bi.flush()

        borders.flush()

        ImagePlus(frame.getTitle() + " recording", stack).show()
        IJ.showStatus("Done recording " + frame.getTitle())
    except Exception, e:
        print "Some error ocurred:"
        print e.printStackTrace()
        IJ.showStatus("")
        if borders is not None:
            borders.flush()
        for snap in snaps:
            snap.flush()
def main():
    userDir = DirectoryChooser("Choose a folder")
    imgDir = userDir.getDirectory()
    import_and_straighten(imgDir)
    measure_growth(imgDir)
# this is the macro to quickly go through image stacks and choose which ones to make into a montage
# the input is sets of stacks and montages that match all in one folder

import os, csv
from ij import IJ, ImagePlus, ImageStack, WindowManager
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.io import FileSaver
from ij.gui import WaitForUserDialog
from ij.plugin import MontageMaker
from ij.gui import GenericDialog

dc = DirectoryChooser("Choose an input directory")
inputDirectory = dc.getDirectory()

dc = DirectoryChooser("Select an output directory")
outputDirectory = dc.getDirectory()

for image in os.listdir(inputDirectory):
    print(image)
    if "stack" in image:
        imp = IJ.openImage(inputDirectory + "/" + image)
        imp2 = IJ.openImage(inputDirectory + "/" +
                            image.replace("stack", "montage"))
        imp.show()
        imp2.show()

        gd = GenericDialog("?")
        gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No")
        gd.showDialog()
        if gd.getNextChoice() == "Yes":
import os
from ij.io import DirectoryChooser
from ij import IJ
from ij.plugin import ChannelSplitter
from ij.process import LUT
from ij.process import StackConverter
from java.awt import Color
from ij.gui import GenericDialog

dc = DirectoryChooser("Select folder to operate on...")
dirPath = dc.getDirectory()
if dirPath is not None:
	dc2 = DirectoryChooser("Select output directory...")
	outPath = dc2.getDirectory()
	if outPath is not None:
		gd = GenericDialog("Options...")
		gd.addCheckbox("Recolor_images",True)
		gd.showDialog()
		if (gd.wasOKed()):
			doRecolor = gd.getNextBoolean()
		
			for f in os.listdir(dirPath):
				if f.endswith(".tif") or f.endswith(".tiff"):
					theImage = IJ.openImage(dirPath+f)
					IJ.log("Loaded " + f)
					palette = [Color.GREEN,Color.RED,Color.BLUE]
					if (theImage.getNChannels() < 4):
						if doRecolor:
							for i in range(theImage.getNChannels()):
								theImage.setChannelLut(LUT.createLutFromColor(palette[i]),i+1)
						try: