Пример #1
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))
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
Пример #3
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)
Пример #4
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()
Пример #5
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()
Пример #6
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)
Пример #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 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
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
Пример #14
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()
Пример #15
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()
Пример #16
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
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'))]
Пример #18
0
	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
Пример #19
0
import csv
import os
import sys
from array import array
import re
import zipfile

import ast

import platform

gene_list = ['dapi', 'syfp', 'sst', 'gad1', 'pvalb']

dir = DirectoryChooser('Select Directory')

fs = os.listdir(dir.getDirectory())
csv_path = os.path.join(dir.getDirectory(), 'cell_coordinates.csv')
#img_path = os.path.join(dir.getDirectory(), 'input', 'dapi_max-z.png')

print(csv_path)
#print(img_path)

#imp = IJ.openImage(img_path)

#imp.show()

roi_manager = RoiManager()

for gene in gene_list:
    roi_manager.reset()
    with open(csv_path) as csvfile:
def processDirectory():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for an input directory
	dc = DirectoryChooser("Choose folder containing Olympus (.oir) files")  
	inputDir = dc.getDirectory() 
	if inputDir is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
	IJ.log("\nInput directory: " + inputDir + "\n")

	oirFiles = []
	for f in os.listdir(inputDir):
		if f.endswith(".oir"):
			oirFiles.append(f)

	if len(oirFiles) < 1:
		IJ.log("Input directory does not contain any Olympus (.oir) files.\nNo images to process.\n")
		return
  	
	# find out how many channels are in first file (we will assume all files have same number of channels and were acquired using same DMs)
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(inputDir + oirFiles[0])
	numChannels = reader.getSizeC()

	# 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("User selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])
	IJ.log("\n")

	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("User selected channel colours")
		usersMergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				usersMergeList.append(None)
			else:
				usersMergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)
		IJ.log("\n\n")

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	outputDir = dc.getDirectory()    
	if outputDir is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  

	counter = 0
	totalFiles = len(oirFiles)
	for o in oirFiles:
		counter +=1
		IJ.log("Processing file " + str(counter) + " of " + str(totalFiles) + "\n")
		IJ.log("File path: " + inputDir + o)
		if merge:
			ml = usersMergeList[:]
		else:
			ml = None
		processFile(o, inputDir, outputDir, dichroics, ml)
		IJ.log("\n--------------------------\n")
Пример #21
0
def main():
    check_dependencies()
    # setup
    Prefs.blackBackground = True
    params = Parameters()
    params.load_last_params()
    # select folders
    if params.last_input_path is not None:
        DirectoryChooser.setDefaultDirectory(params.last_input_path)
    dc = DirectoryChooser("Choose root folder containing data for analysis")
    input_folder = dc.getDirectory()
    params.last_input_path = input_folder
    if input_folder is None:
        print("Run canceled")
        return
    if params.last_output_path is not None:
        DirectoryChooser.setDefaultDirectory(
            os.path.dirname(params.last_output_path))
    dc = DirectoryChooser("choose location to save output")
    output_folder = dc.getDirectory()
    if output_folder is None:
        print("Run canceled")
        return
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    output_folder = os.path.join(output_folder, (timestamp + ' output'))
    params.last_output_path = output_folder
    os.mkdir(output_folder)
    analysis_mode, threshold_method, minimum_cell_area_um2 = choose_analysis_mode(
        params)
    if analysis_mode is None:
        print("Run canceled")
        return
    params.last_analysis_mode = analysis_mode
    do_manual_qc = "+ manual correction" in analysis_mode
    params.last_threshold_method = threshold_method
    params.last_minimum_cell_area_um2 = minimum_cell_area_um2
    params.persist_parameters()

    # load  image(s):
    files_lst = [
        f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif'
    ]
    out_statses = []
    for f in files_lst:
        print("Working on image {}...".format(os.path.splitext(f)[0]))
        imp = IJ.openImage(os.path.join(input_folder, f))
        metadata = import_iq3_metadata(
            os.path.join(input_folder,
                         os.path.splitext(f)[0] + '.txt'))
        n_channels = int(metadata['n_channels'])
        gfp_channel_number = [
            ("488" in ch) for ch in metadata['channel_list']
        ].index(True) + 1 if any(
            [("488" in ch) for ch in metadata['channel_list']]) else None
        dapi_channel_number = [
            ("405" in ch) for ch in metadata['channel_list']
        ].index(True) + 1 if any(
            [("405" in ch) for ch in metadata['channel_list']]) else None
        red_channel_number = [
            ("561" in ch) for ch in metadata['channel_list']
        ].index(True) + 1 if any(
            [("561" in ch) for ch in metadata['channel_list']]) else None
        imp = HyperStackConverter.toHyperStack(imp, n_channels,
                                               imp.getNSlices() // n_channels,
                                               1, "Color")
        imp = ZProjector.run(imp, "max")
        if dapi_channel_number is not None:
            imp.setC(dapi_channel_number)
            IJ.run(imp, "Blue", "")
            IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        else:
            raise NotImplementedError(
                "Nuclear staining channel doesn't seem to exist!")
        if red_channel_number is not None:
            imp.setC(red_channel_number)
            IJ.run(imp, "Red", "")
            IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        if gfp_channel_number is not None:
            imp.setC(gfp_channel_number)
            IJ.run(imp, "Green", "")
            IJ.run(imp, "Enhance Contrast", "saturated=0.35")
            imp.setC(gfp_channel_number)

        imp.show()
        imp.setDisplayMode(IJ.COMPOSITE)
        cal = imp.getCalibration()
        cal.setUnit(metadata["y_unit"])
        cal.pixelWidth = metadata["x_physical_size"]
        cal.pixelHeight = metadata["y_physical_size"]
        imp.setCalibration(cal)

        min_size_pix = minimum_cell_area_um2 / (cal.pixelHeight *
                                                cal.pixelWidth)
        if "GFP intensity" in analysis_mode:
            out_stats = gfp_analysis(imp,
                                     f,
                                     output_folder,
                                     gfp_channel_number=gfp_channel_number,
                                     dapi_channel_number=dapi_channel_number,
                                     threshold_method=threshold_method,
                                     do_manual_qc=do_manual_qc,
                                     min_size_pix=min_size_pix)
        elif analysis_mode == "Manual":
            important_channel = gfp_channel_number if gfp_channel_number is not None else dapi_channel_number
            out_stats = manual_analysis(
                imp,
                f,
                output_folder,
                gfp_channel_number=gfp_channel_number,
                dapi_channel_number=dapi_channel_number,
                important_channel=important_channel)
        elif "E-cadherin watershed" in analysis_mode:
            out_stats = ecad_analysis(imp,
                                      f,
                                      output_folder,
                                      gfp_channel_number=gfp_channel_number,
                                      red_channel_number=red_channel_number,
                                      dapi_channel_number=dapi_channel_number,
                                      do_manual_qc=do_manual_qc)
            imp.close()
        out_statses.extend(out_stats)
        print("Current total number of cells identified: {}".format(
            len(out_statses)))
        # get # nuclei per "cell"
    params.save_parameters_to_json(
        os.path.join(output_folder, "parameters used.json"))
    WaitForUserDialog(
        "Done", "Done, having analysed {} cells in total!".format(
            len(out_statses))).show()
    return
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...")
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:
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()
		
	
Пример #25
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()
Пример #26
0
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()
		
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")
Пример #28
0
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):
		ipslice = ipmask.createProcessor(imgA.getWidth(), imgA.getHeight())
		ipslice.setValue(0.0)
Пример #29
0
import os
import shutil

from ij import IJ
from ij.io import DirectoryChooser

dc = DirectoryChooser("Select Main Folder")
inputPath = dc.getDirectory()

file_list = os.listdir(inputPath)

if not os.path.exists(os.path.join(inputPath, "Channel 1")):
    os.makedirs(os.path.join(inputPath, "Channel 1"))

if not os.path.exists(os.path.join(inputPath, "Channel 2")):
    os.makedirs(os.path.join(inputPath, "Channel 2"))

channel_1 = inputPath + "Channel 1" + "\\"
channel_2 = inputPath + "Channel 2" + "\\"

for files in file_list:

    if "Ch1" in files:

        shutil.move(inputPath + files, channel_1 + files)

    if "Ch2" in files:

        shutil.move(inputPath + files, channel_2 + files)
Пример #30
0
if IN_DEV :
	canceled = False
else :
	canceled = not IJ.showMessageWithCancel(__program__,'To proceed program will close all open images and windows, continue?')


if not canceled :
	
	setup()


	if IN_DEV :
		exper_path = "/Users/baylieslab/Documents/Amelia/data/patrick/2019-05-20_Dmef2-2xeGFP"
	else :
		dir_chooser = DirectoryChooser(__program__)
		exper_path = dir_chooser.getDirectory()
		if exper_path.endswith('/') :
			exper_path = exper_path[:-1]
	

	exper_name = os.path.basename(exper_path)

	exper = Exper(exper_path, exper_name)

	

	hemisegs = []
	fs = os.listdir(exper_path)

	for f in fs : 
		if f.startswith(exper_name) :
Пример #31
0
			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)
					stitchPaths = map(get_first_in_tuple,filter(filter_by_return_status,map(lambda x,y:(x,y),resizePaths,resizeStatuses)))
Пример #32
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()
import sys

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()
Пример #34
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)
def main():
    # define here which membrane indices will be used in the analysis, with last index the "control" index
    membrane_indices = [-1, 0, 1, 3]

    # for now, work with frontmost open image...
    imp = IJ.getImage()
    im_title = imp.getTitle()
    settings = MembraneEvolutionAnalysisSettings(
        membrane_indices=membrane_indices)
    settings.loadPersistedSettings()

    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    DirectoryChooser.setDefaultDirectory((settings.output_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')
    settings.output_path = output_root

    # get calibration
    cal = imp.getCalibration()
    if cal.getTimeUnit() == "sec":
        cal.setTimeUnit('s')

    # pop up a dialog prompting for selection of zero time point, frame interval, and time step for analysis
    time_steps_not_ok = True
    while time_steps_not_ok:
        dialog = NonBlockingGenericDialog("Determine time parameters...")
        dialog.addNumericField("0 timepoint frame (1-index): ",
                               settings.zero_timepoint_frame, 0)
        dialog.addNumericField("Acquisition time step (s): ",
                               cal.frameInterval,
                               2)  # assume stored in seconds
        dialog.addNumericField(
            "Time step for analysis (s): ",
            cal.frameInterval * settings.analysis_frame_step, 2)
        dialog.showDialog()

        if dialog.wasCanceled():
            return

        zero_f = dialog.getNextNumber()
        acq_t_step = dialog.getNextNumber()
        analysis_t_step = dialog.getNextNumber()
        if acq_t_step != 0 and analysis_t_step != 0:
            analysis_frame_step = analysis_t_step / acq_t_step

            if round(analysis_frame_step) == analysis_frame_step:
                time_steps_not_ok = False
                settings.zero_timepoint_frame = zero_f
                settings.analysis_frame_step = analysis_frame_step
        if time_steps_not_ok:
            warning_dlg = GenericDialog("Error!")
            warning_dlg.addMessage(
                "Analysis time step must be an integer multiple of acquisition time steps, and neither should be zero!!"
            )
            warning_dlg.setOKLabel("Try again...")
            warning_dlg.showDialog()

            if warning_dlg.wasCanceled():
                return

    start_frame = int(((zero_f - 1) % analysis_frame_step) + 1)
    end_frame = int(imp.getNFrames() -
                    (imp.getNFrames() - zero_f) % analysis_frame_step)
    frames = [
        f + 1
        for f in range(start_frame - 1, end_frame, int(analysis_frame_step))
    ]
    print("frames = " + str(frames))
    imp.killRoi()
    analysis_imp = SubstackMaker().makeSubstack(
        imp,
        str(start_frame) + "-" + str(end_frame) + "-" +
        str(int(analysis_frame_step)))
    imp.changes = False
    imp.close()
    analysis_imp.show()
    drawn_membranes = [
        TimepointsMembranes(input_image_title=im_title,
                            time_point_s=(t - 1) * acq_t_step) for t in frames
    ]
    membranes_listener = UpdateRoiImageListener(drawn_membranes)
    analysis_imp.addImageListener(membranes_listener)

    # now attach roi listener to store all 0th membranes after showing a waitforuserdialog to prompt continuation
    IJ.setTool("freeline")
    for membrane_idx in membrane_indices:
        #		if membrane_idx>50:
        #			IJ.setTool("line");
        analysis_imp.killRoi()
        membranes_listener.resetLastFrame()
        membranes_listener.setCurrentMembraneIndex(membrane_idx)
        analysis_imp.setZ(1)
        continue_dlg = WaitForUserDialog(
            "Continue?", "Click OK once all the " + str(membrane_idx) +
            "-index membranes have been drawn")
        continue_dlg.show()
        membranes_listener.imageUpdated(analysis_imp)
        drawn_membranes = membranes_listener.getDrawnMembraneTimepointsList()
        json_path = os.path.join(output_root,
                                 "Membranes " + timestamp + ".json")
        f = open(json_path, 'w+')
        try:
            json.dump(drawn_membranes, f, default=encode_membrane)
        finally:
            f.close()
        # save csv containing mebrane measurements for current membrane index
        csv_path = os.path.join(
            output_root, ("Membrane measurements " + timestamp + ".csv"))
        if membrane_idx == membrane_indices[0]:
            try:
                f = open(csv_path, 'wb')
                writer = csv.writer(f)
                writer.writerow([
                    "Membrane index", ("Time point, " + cal.getTimeUnit()),
                    ("Membrane length, " + cal.getUnit()),
                    ("Euclidean length, " + cal.getUnit()),
                    "Membrane sinuoisty"
                ])
            finally:
                f.close()
        try:
            f = open(csv_path, 'ab')
            writer = csv.writer(f)
            for mems in drawn_membranes:
                mem = mems.getMembrane(membrane_idx)
                if mem is not None:
                    writer.writerow([
                        membrane_idx, mems.time_point_s,
                        mem.getPathLength() * cal.pixelWidth,
                        mem.getEuclidean() * cal.pixelWidth,
                        mem.getSinuosity()
                    ])
        finally:
            f.close()

    settings.persistSettings()
    settings.save_settings()
    print("Finished getting all membranes with indices " +
          str(membrane_indices))
    analysis_imp.close()
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:
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()

sSat = "saturated=%.2f" % sFac
Пример #39
0
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()
Пример #40
0
clij2 = CLIJ2.getInstance()


def run_tube(image, sigma, index, result):
    tp = TubenessProcessor(sigma, True)
    tubimg = tp.generateImage(image)
    tubimg = tubimg.getProcessor().convertToShortProcessor()
    tubimg = ImagePlus("img", tubimg)
    result[index] = tubimg


# vessel detection training

dc = DirectoryChooser("Choose a folder")
folder = dc.getDirectory()
pos = IJ.openImage(folder + "\\vessels_positive.tif")
posroi = pos.getRoi()
neg = IJ.openImage(folder + "\\vessels_negative.tif")
negroi = neg.getRoi()
pos.close()
IJ.run("Select None", "")

channels = ChannelSplitter.split(neg)

neg.close()
image = channels[3]
channels = channels[0:3]
proc = image.getProcessor()
directional_op = ImagePlus("directional_op", proc)
Пример #41
0
                headerStr = ''
                for k, v in myInfoDict.items():
                    headerStr += k + ','
                print(headerStr, file=f)
            rowStr = ''
            for k, v in myInfoDict.items():
                rowStr += str(v) + ','
            print(rowStr, file=f)


if __name__ in ['__main__', '__builtin__']:

    # debug file open errors
    #gTheseFileExtensions = ['.oir', '.tif', '.csv']

    #
    # ask user for a folder path
    userFolder = DirectoryChooser('Choose a folder')
    folderPath = userFolder.getDirectory()
    if folderPath is None:
        print('Warning: User did not choose a folder')
    else:
        # remove trailing /  or \
        if folderPath.endswith(os.sep):
            folderPath = folderPath[:-1]
        #
        myRun(folderPath, gTheseFileExtensions)
        #

    print('    simpleFileInfo is done !!!')
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)
Пример #43
0
		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")
	gd.addMessage("Maximum memory: " + str(memFijiMB) + "MB")
Пример #44
0
def run():

  IJ.log("Correct_3D_Drift")

  imp = IJ.getImage()
  if imp is None:
    return
  if 1 == imp.getNFrames():
    IJ.showMessage("Cannot register because there is only one time frame.\nPlease check [Image > Properties...].")
    return

  options = getOptions(imp)
  if options is None:
    return # user pressed Cancel

  if options['z_min'] < 1:
    IJ.showMessage("The minimal z plane must be >=1.")
    return
    
  if options['z_max'] > imp.getNSlices():
    IJ.showMessage("Your image only has "+str(imp.getNSlices())+" z-planes, please adapt your z-range.")
    return
  
  if options['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 drift
  #
  IJ.log("  computing drift...");

  IJ.log("    at frame shifts of 1"); 
  dt = 1; shifts = compute_and_update_frame_translations_dt(imp, dt, options)
  
  # multi-time-scale computation
  if options['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, dt, options, shifts)
      else: 
        IJ.log("    at frame shifts of "+str(dt_max));
        shifts = compute_and_update_frame_translations_dt(imp, dt_max, options, shifts)
        break

  # invert measured shifts to make them the correction
  shifts = invert_shifts(shifts)
  #print(shifts)
  
  
  # apply shifts
  if not options['only_compute']:
    
    IJ.log("  applying shifts..."); #print("\nAPPLYING SHIFTS:")
    
    if options['subpixel']:
      registered_imp = register_hyperstack_subpixel(imp, options['channel'], shifts, target_folder, options['virtual'])
    else:
      shifts = convert_shifts_to_integer(shifts)
      registered_imp = register_hyperstack(imp, shifts, target_folder, options['virtual'])
      
    if options['virtual'] is True:
      if 1 == imp.getNChannels():
        ip=imp.getProcessor()
        ip2=registered_imp.getProcessor()
        ip2.setColorModel(ip.getCurrentColorModel())
      else:
    	registered_imp.copyLuts(imp)
    else:
      if imp.getNChannels() > 1:
        registered_imp.copyLuts(imp)
  
    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...")
Пример #45
0
def dirchooser():
    dc = DirCh("Choose data folder...")
    return dc.getDirectory()
Пример #46
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)
	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"):
	os.mkdir(imgDir + "temp")
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:
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":
Пример #51
0
def main():
    # setup
    Prefs.blackBackground = True
    params = Parameters()
    params.load_last_params()
    # select folders
    if params.last_input_path is not None:
        DirectoryChooser.setDefaultDirectory(params.last_input_path)
    dc = DirectoryChooser("Choose root folder containing data for analysis")
    input_folder = dc.getDirectory()
    params.last_input_path = input_folder
    if input_folder is None:
        raise KeyboardInterrupt("Run canceled")
    if params.last_output_path is not None:
        DirectoryChooser.setDefaultDirectory(
            os.path.dirname(params.last_output_path))
    dc = DirectoryChooser("choose location to save output")
    output_folder = dc.getDirectory()
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    output_folder = os.path.join(output_folder, (timestamp + ' output'))
    params.last_output_path = output_folder
    os.mkdir(output_folder)
    analysis_mode = choose_analysis_mode(params)
    params.last_analysis_mode = analysis_mode
    params.persist_parameters()

    # load  image(s):
    files_lst = [
        f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif'
    ]
    out_statses = []
    for f in files_lst:
        print("Working on image {}...".format(os.path.splitext(f)[0]))
        imp = IJ.openImage(os.path.join(input_folder, f))
        metadata = import_iq3_metadata(
            os.path.join(input_folder,
                         os.path.splitext(f)[0] + '.txt'))
        imp = HyperStackConverter.toHyperStack(imp, 3,
                                               imp.getNSlices() // 3, 1,
                                               "Color")
        imp = ZProjector.run(imp, "max")
        imp.setC(3)
        IJ.run(imp, "Blue", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.setC(2)
        IJ.run(imp, "Red", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.setC(1)
        IJ.run(imp, "Green", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.show()
        imp.setDisplayMode(IJ.COMPOSITE)
        cal = imp.getCalibration()
        cal.setUnit(metadata["y_unit"])
        cal.pixelWidth = metadata["x_physical_size"]
        cal.pixelHeight = metadata["y_physical_size"]
        imp.setCalibration(cal)

        if analysis_mode == "GFP intensity":
            out_stats = gfp_analysis(imp, f, output_folder)
        elif analysis_mode == "Manual":
            out_stats = manual_analysis(imp, f, output_folder)
        out_statses.extend(out_stats)
        print("Current total number of cells identified: {}".format(
            len(out_statses)))
        # get # nuclei per "cell"
    params.save_parameters_to_json(
        os.path.join(output_folder, "parameters used.json"))
    WaitForUserDialog(
        "Done", "Done, having analysed {} cells in total!".format(
            len(out_statses))).show()
    return