def run():
    global pmWin
    global imgData
    helpText = "This is Point Marker, " + \
               "a program for marking points in images.\n\n" + \
               ">> Press OK to Select a file for storing points infomation.\n"+\
               ">> TIF-Images within the same directory will be auto-loaded."
    MessageDialog(IJ.getInstance(),"Point Marker Guide", helpText)

    fileChooser = OpenDialog("Point Marker: Choose working directory and file")
    outfilePath = fileChooser.getPath()
    imgDir = fileChooser.getDirectory()
    if not imgDir:  return
    imgPaths = []
    if imgDir:
        for root, directories, filenames in os.walk(imgDir):
            for filename in filenames:
                if not filename.endswith(".tif"):
                    continue
                imgPaths.append(os.path.join(root, filename))

    pointsTable1 = readPoints(outfilePath)

    imgData = PointMarkerData(imgPaths, outfilePath, pointsTable1)

    IJ.setTool("multipoint")
    PointRoi.setDefaultSize(3)

    pmWin = PointMarkerWin(imgData)
    pmWin.win.setLocation(IJ.getInstance().getLocation())
    prepareNewImage(imgData)
Ejemplo n.º 2
0
def run():
    global pmWin
    global imgData
    helpText = "This is Point Marker, " + \
               "a program for marking points in images.\n\n" + \
               ">> Press OK to Select a file for storing points infomation.\n"+\
               ">> TIF-Images within the same directory will be auto-loaded."
    MessageDialog(IJ.getInstance(), "Point Marker Guide", helpText)

    fileChooser = OpenDialog("Point Marker: Choose working directory and file")
    outfilePath = fileChooser.getPath()
    imgDir = fileChooser.getDirectory()
    if not imgDir: return
    imgPaths = []
    if imgDir:
        for root, directories, filenames in os.walk(imgDir):
            for filename in filenames:
                if not filename.endswith(".tif"):
                    continue
                imgPaths.append(os.path.join(root, filename))

    pointsTable1 = readPoints(outfilePath)

    imgData = PointMarkerData(imgPaths, outfilePath, pointsTable1)

    IJ.setTool("multipoint")
    PointRoi.setDefaultSize(3)

    pmWin = PointMarkerWin(imgData)
    pmWin.win.setLocation(IJ.getInstance().getLocation())
    prepareNewImage(imgData)
Ejemplo n.º 3
0
def ChooseLandmarkFile():
	od = OpenDialog("Choose Landmark file", None)	
	file_name = od.getFileName()
	dir_name = od.getDirectory()
	print("Reading "+file_name)
	print("in directory "+dir_name)	
	return dir_name, file_name
Ejemplo n.º 4
0
def open_image():
    """
	opens an image, returns an imagePlus object and its name in that order
	"""
    # Prompt user for the input image file.
    print "open_image begin"
    op = OpenDialog("Choose input image...", "")

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

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

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

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

    print "open_image finis"
    return inputImp, inputPrefix, inputDirPath
def get_path():
	od = OpenDialog("Choose Spinning disk  file", None)
	srcDir = od.getDirectory()
	if srcDir is None:
		# User canceled the dialog
		sys.exit(0)
	file = os.path.join(srcDir, od.getFileName())
	return srcDir,file
Ejemplo n.º 6
0
def main():
	from ij.io import OpenDialog
	od=OpenDialog("Select a slide scanner file")

	filepath = od.getPath()
	print(filepath)
	
	open_files_and_roi(filepath)
Ejemplo n.º 7
0
def input_file_location_chooser(default_directory, filt='*.tif', message=None):
    if message == None:
        message = 'Choose original file...'
    od = OpenDialog(message, default_directory, filt)
    file_path = od.getPath()
    if file_path is None:
        raise IOError('no input file chosen')
    return file_path
Ejemplo n.º 8
0
def ChooseImageFile(image_type):
	od = OpenDialog("Choose %s image"%image_type, None)
	file_name = od.getFileName()
	dir_name = od.getDirectory()
	full_path = os.path.join(dir_name,file_name)
	print("Opening %s"%full_path)
	imp = IJ.openImage(full_path)
	return imp
def file_location_chooser(default_directory):
    """choose folder locations and prepare output folder"""
    # input
    od = OpenDialog('Choose original file...', default_directory, '*.tif')
    file_path = od.getPath()
    if file_path is None:
        raise IOError('no input file chosen')
    return file_path
def ui_get_input_file():
    """Ask user for input file and process results."""
    dialog = OpenDialog("Choose a 'MATL_Mosaic.log' file")
    fname = dialog.getFileName()
    if (fname is None):
        log.warn('No input file selected!')
        return((None, None))
    base = dialog.getDirectory()
    return((base, fname))
Ejemplo n.º 11
0
def file_location_chooser(default_directory):
	"""choose input data location"""
	od = OpenDialog('Choose original file...', 
					default_directory, 
					'*.tif');
	file_path = od.getPath();
	if file_path is None:
		raise IOError('no input file chosen');
	return file_path;
Ejemplo n.º 12
0
def openAtFolder(event):
    if 0 == path.getText().find("http"):
        IJ.showMessage("Can't open folder: it's an URL")
        return
    directory = os.path.dirname(path.getText())
    od = OpenDialog("Open", directory, None)
    filepath = od.getPath()
    if filepath:
        IJ.open(filepath)
Ejemplo n.º 13
0
def openImp():
    '''function that calls an OpenDialog and returns filePath and imp'''
    od = OpenDialog("Open movie", "")
    filePath = path.join(od.getDirectory(), od.getFileName())
    if path.splitext(od.getFileName())[1] == ".tif" :  #on .dv, use LOCI
        imp = Opener().openImage(filePath)
    if path.splitext(od.getFileName())[1] == ".dv":
        IJ.run("Bio-Formats Importer", "open=["+filePath+"] autoscale color_mode=Grayscale view=Hyperstack stack_order=XYCZT")
        imp = IJ.getImage()
    return filePath, imp
Ejemplo n.º 14
0
def select_file(self):
	global img_paths, opened_imgs 
	path = OpenDialog('Select an image file').getPath();
	if(path): 
		shortened_path = path[path.rindex('/')+1:];
		print(shortened_path);
		img_paths[shortened_path] = path;
		opened_imgs.append(IJ.openImage(path));
		opened_imgs[-1].show();
		dropdown.addItem(shortened_path);
	else:
		print("file not selected/found")
Ejemplo n.º 15
0
def get_metadata_table_filepath():
    """Get a the metadata template filename"""
    d = GenericDialog("Metadata Template")
    d.addMessage("Please choose a metadata template")
    d.enableYesNoCancel("OK", "Cancel")
    d.hideCancelButton()
    d.showDialog()
    if d.wasOKed():
        od = OpenDialog("Metadata File")
        return os.path.join(od.getDirectory(), od.getFileName())
    else:
        return
Ejemplo n.º 16
0
def MultiFileDialog(title):
  #hide/show debug prints
  verbose = 0
  # Choose image file(s) to open
  fc = JFileChooser()
  fc.setMultiSelectionEnabled(True)
  fc.setDialogTitle(title)

  sdir = OpenDialog.getDefaultDirectory()
  if sdir!=None:
    fdir = File(sdir)
  if fdir!=None:
    fc.setCurrentDirectory(fdir)
  
  returnVal = fc.showOpenDialog(IJ.getInstance())
  if returnVal!=JFileChooser.APPROVE_OPTION:
    return
  files = fc.getSelectedFiles()

  paths = []
  for i in range(len(files)):
      paths.append(os.path.join(files[i].getParent(), files[i].getName()))
      
  if verbose > 0:
    for i in range(len(files)):
      path = os.path.join(files[i].getParent(), files[i].getName())
      print "Path: " + path
  
  return paths
Ejemplo n.º 17
0
def MultiFileDialog(title):
    #hide/show debug prints
    verbose = 0
    # Choose image file(s) to open
    fc = JFileChooser()
    fc.setMultiSelectionEnabled(True)
    fc.setDialogTitle(title)

    sdir = OpenDialog.getDefaultDirectory()
    if sdir != None:
        fdir = File(sdir)
    if fdir != None:
        fc.setCurrentDirectory(fdir)

    returnVal = fc.showOpenDialog(IJ.getInstance())
    if returnVal != JFileChooser.APPROVE_OPTION:
        return
    files = fc.getSelectedFiles()

    paths = []
    for i in range(len(files)):
        paths.append(os.path.join(files[i].getParent(), files[i].getName()))

    if verbose > 0:
        for i in range(len(files)):
            path = os.path.join(files[i].getParent(), files[i].getName())
            print "Path: " + path

    return paths
Ejemplo n.º 18
0
def get_metadata(params):
    """get image metadata, either from the image file or from acquisition-time metadata"""
    if params.metadata_source == "Image metadata":
        try:
            reader = ImageReader()
            ome_meta = MetadataTools.createOMEXMLMetadata()
            reader.setMetadataStore(ome_meta)
            reader.setId(params.input_image_path)
            reader.close()
            params.setFrameInterval(
                ome_meta.getPixelsTimeIncrement(0).value())
            params.setIntervalUnit(
                ome_meta.getPixelsTimeIncrement(0).unit().getSymbol())
            params.setPixelPhysicalSize(
                ome_meta.getPixelsPhysicalSizeX(0).value())
            params.setPixelSizeUnit(
                ome_meta.getPixelsPhysicalSizeX(0).unit().getSymbol())
            params.setMetadataSourceFile(None)
        except Exception as e:
            print(e.message)
            mbui.warning_dialog([
                "There was a problem getting metadata from the image: ",
                e.message,
                "Please consider using acquisition metadata instead (click OK). ",
                "Or, quit the analysis run and investigate image metadata by hand. "
            ])
            params.setMetadataSource("Acquisition metadata")
    if params.metadata_source == "Acquisition metadata":
        od = OpenDialog('Choose acquisition metadata file...',
                        os.path.dirname(params.input_image_path), '*.txt')
        file_path = od.getPath()
        if file_path is None:
            raise IOError('no metadata file chosen')
        acq_metadata_dict = import_iq3_metadata(file_path)
        try:
            params.setFrameInterval(acq_metadata_dict['frame_interval'])
        except KeyError:
            params.setFrameInterval(1.0)
        try:
            params.setIntervalUnit(acq_metadata_dict['time_unit'])
        except KeyError:
            params.setIntervalUnit('frames')
        params.setPixelPhysicalSize(acq_metadata_dict['x_physical_size'])
        params.setPixelSizeUnit(acq_metadata_dict['x_unit'])
        params.setMetadataSourceFile(file_path)
    return params
Ejemplo n.º 19
0
def getImgs():
	op = OpenDialog("Choose Filepath Data...")
	filepath = op.getDirectory()
	filelist = os.listdir(filepath)
	bf_imgs = []
	pi_imgs = []
	for i in filelist:
		# Find brightfield images and append to bf_imgs
		if 'bf' in i:
			bf_imgs.append(i)
			# Find corresponding PI images
			COMS = i.split('bf')
			# Add corresponding PI images to pi_imgs IFF the corresponding name exists in the directory
			test_name = COMS[0] + 'pi' + COMS[1]
			if test_name in filelist:
				pi_imgs.append(test_name)
	return bf_imgs, pi_imgs, filepath
Ejemplo n.º 20
0
def getThresholds():
	thresholds = {}
	
	gd = GenericDialog("Threshold options")
	gd.addChoice("How would you like to set your thresholds?", ["default", "use threshold csv file"], "default")
	gd.showDialog()

	choice = gd.getNextChoice()
	log.write("Option: " + choice + "\n")

	if choice == "use threshold csv file":
		path = OpenDialog("Open the thresholds csv file")
		log.write("File used: " + path.getPath() + "\n")
		with open(path.getPath()) as csvfile:
			reader = csv.DictReader(csvfile)
			for row in reader:
				thresholds = row
	return thresholds
Ejemplo n.º 21
0
def getNames():
	names = {}
	
	gd = GenericDialog("Naming options")
	gd.addChoice("How would you like to name your results for each well?", ["default", "use name convention csv file"], "default")
	gd.showDialog()

	choice = gd.getNextChoice()

	log.write("Option: " + choice + "\n")

	if choice == "use name convention csv file":
		path = OpenDialog("Open the names csv file")
		log.write("File used: " + path.getPath() + "\n")
		
		with open(path.getPath()) as csvfile:
			reader = csv.DictReader(csvfile)
			for row in reader:
				names[row['Row']] = row 
	
	return names
def GUI(active):
    # GUI to select file and select input/output folders
    if not active:
        sourcedir = "D:\\JPA\\wt2"
        sourcefile = "D:\\JPA\\wt2.czi"
        targetdir = "D:\\JPA\\wt2"
        XMLinput = "D:\\JPA\\wt2.mvl"
    else:
        od = OpenDialog("Select CZI Zeiss file", None)
        soucedir = od.getDirectory()
        sourcefile = od.getFileName()
        od = OpenDialog("Select MVL Zeiss file", None)
        XMLdir = od.getDirectory()
        XMLfile = od.getFileName()
        XMLinput = os.path.join(XMLdir, XMLfile)
        targetdir = DirectoryChooser(
            "Choose destination folder").getDirectory()
        sourcedir = os.path.join(soucedir, sourcefile)
	# Create some global variables
    global INpath
    INpath = sourcedir
    global source
    source = sourcefile
    global OUTpath
    OUTpath = targetdir
    global XMLzeiss
    XMLzeiss = XMLinput
Ejemplo n.º 23
0
def get_config_file(folder):
    '''Returns the config file name.'''
    # Get list of files in the selected directory.
    files = os.listdir(folder)

    # Check if a config file is present in folder.
    if default_config in files:
        dialog = GenericDialog('Default config file found!')
        dialog.addMessage('Use this file for the analysis?\n \n%s' % os.path.join(folder, default_config))
        dialog.enableYesNoCancel()
        dialog.showDialog()
        if dialog.wasCanceled():
            return None
        elif dialog.wasOKed():
            return default_config
        else:
            open_dialog = OpenDialog('Select a config file', folder, default_config)
            return open_dialog.getFileName()
    else:
        # Ask user to select a config file.
        open_dialog = OpenDialog('Select a config file', folder, default_config)
        return open_dialog.getFileName()
Ejemplo n.º 24
0
def getNames():
    info = []

    gd = GenericDialog("Naming options")
    gd.addChoice("How would you like to output your results?",
                 ["default", "use information csv file"], "default")
    gd.showDialog()

    choice = gd.getNextChoice()

    log.write("Option: " + choice + "\n")

    if choice == "use information csv file":
        path = OpenDialog("Open the names csv file")
        log.write("File used: " + path.getPath() + "\n")

        with open(path.getPath()) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                info.append(row)

    return info
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
def FolderDialog(title, folder):
  fc = JFileChooser()
  fc.setMultiSelectionEnabled(False)
  fc.setDialogTitle(title)
  fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  fc.setAcceptAllFileFilterUsed(False);
  if folder ==None:
    sdir = OpenDialog.getDefaultDirectory()
  else:
    sdir = folder
  if sdir!=None:
    fdir = File(sdir)
  if fdir!=None:
    fc.setCurrentDirectory(fdir)
  returnVal = fc.showOpenDialog(IJ.getInstance())
  if returnVal!=JFileChooser.APPROVE_OPTION:
    return
  folder = fc.getSelectedFile();
  path = os.path.join(folder.getParent(), folder.getName())
  return path
def getImgRoiDir():

    gui = GenericDialogPlus(
        "Select directories to process images and ROI sets to apply")

    default_dir = OpenDialog.getDefaultDirectory()
    gui.addDirectoryField("Choose a iamge folder to be processed", default_dir)
    gui.addDirectoryField("Choose a ROI set folder to apply", default_dir)

    gui.showDialog()

    if gui.wasOKed():

        img_dir = gui.getNextString()
        if not img_dir.endswith(os.sep):
            img_dir = img_dir + os.sep

        roi_dir = gui.getNextString()
        if not roi_dir.endswith(os.sep):
            roi_dir = roi_dir + os.sep

        return img_dir, roi_dir
Ejemplo n.º 28
0
import re
import os
from ij.io import DirectoryChooser
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ

dc = DirectoryChooser("Choose directory with image tiles you want to stitch...")
sourceDir = dc.getDirectory()

opener = OpenDialog("Select DMI metadata file...",sourceDir,"tile_info.txt")
metadata_file = opener.getPath()

gd = GenericDialog("Input image name...")
gd.addStringField("Image_prefix:","IMGid")
gd.addMessage("Input directory: " + sourceDir)
gd.showDialog()
img_name = gd.getNextString()
outputPath = sourceDir + img_name + "_seq"

if sourceDir is not None and metadata_file is not None:
	
	## computes tiling information from DMI metadata
	metadata = IJ.openAsString(metadata_file)
	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+)')
Ejemplo n.º 29
0
    
if __name__ == '__main__':

  print("#\n# Elastix registration\n#")
    
  #
  # GET PARAMETERS
  #
  print("#\n# Parameters\n#")

  #
  # Load gui parameters
  #

  od = OpenDialog("Select parameter file (press CANCEL if you don't have one)", None)
  f = od.getPath()
  
  if f:
    print('loading parameters from file')
    f = open(f, 'r'); p_gui = pickle.load(f); f.close()
  else:
    print('starting from default parameters')
    # make parameter structure if it has not been loaded
    p_gui = {}
    # exposed to GUI
    p_gui['expose_to_gui'] = {'value': ['input_folder', 'reg_exp', 'HDF5_data_set_name', 
    'output_folder', 'output_format', 
    'output_bit_depth', 'map_to_zero', 'map_to_max', 'binning',
    'binning_x','binning_y','binning_z','save_xyz_projections','save_volume_data']}
    p_gui['input_folder'] = {'choices': '', 'value': 'C:\\Users\\acquifer\\Desktop\\882-reg3', 'type': 'folder'}
Ejemplo n.º 30
0
#filename = os.path.basename(srcpath)
# print(filename)
# parentdirectory = os.path.dirname(srcpath)
#basename = os.path.splitext(filename)[0]
# print(basename)
#imp = IJ.openImage(srcpath)
# imp = IJ.getImage()

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

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

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

# get image size, dimensions, nChannels
width = imp.getWidth()
from ij.io import OpenDialog
from ij.io import FileSaver
from ij.gui import WaitForUserDialog
from ij.plugin import MontageMaker

empty = "/home/bic/rthomas/Desktop/Link to 12CellLinesPaper/emptymontage.tif"

files = []

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

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

path = OpenDialog("Open the filenames csv file")

with open(path.getPath()) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        files.append(row)

for sets in files:
    name = ""

    for filename in sets:
        if os.path.isfile(inputDirectory + filename):
            imp = IJ.openImage(inputDirectory + filename)
        else:
            imp = IJ.openImage(empty)
        imp.show()
Ejemplo n.º 32
0
    table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                            "enter")
    table.getActionMap().put("enter", OpenImageFromTableCell())
    #
    return model, table, regex_field, frame


def launch(model):
    def run():
        makeUI(model)

    return run


if txt_file is None:
    od = OpenDialog("Choose a text file listing file paths")
    txt_file = od.getPath()

if txt_file:
    model = TableModel(txt_file)
    SwingUtilities.invokeLater(launch(model))

# FOR THE I2K WORKSHOP:
# Enable changing text font size in all components by control+shift+(plus|equals)/minus
components = []
tables = []
frames = []


def addFontResizing():
    global frames
Ejemplo n.º 33
0
 def browse(self, event):
     od = OpenDialog("Select Position", "")
     filePath = path.join(od.getDirectory(), od.getFileName())
     self.pathField.text = filePath    
Ejemplo n.º 34
0
#see https://www.ini.uzh.ch/~acardona/fiji-tutorial/#s1 for help!!
#labels can be set using roiManager
#use with genFIJI_ROIs.m
from ij import IJ
from ij.gui import Roi, OvalRoi
from ij.plugin.frame import RoiManager
from ij.io import OpenDialog
import os

roiManager = RoiManager.getRoiManager()
fileSelection = OpenDialog("Select the positions file")
fileString = IJ.openAsString(fileSelection.getPath())
dataRows = fileString.split("\n")

#print fileString
#print fileSelection.getPath(), 
#print fileSelection.getFileName()
#Use names as labels in roiManager menu (more>>>)
#Save manually as well
imp = IJ.getImage()

rowIter = 0 

for row in dataRows:
	if len(row)>0:
		spotDataList = row.split("\t")
		spotData = [float(x) for x in spotDataList]
		topLeftX = spotData[1] - spotData[4]
		topLeftY = spotData[2] - spotData[4]
		diameter = 2*spotData[4]
		spotRoi = OvalRoi(topLeftX,topLeftY,diameter,diameter)
Ejemplo n.º 35
0
        	xCalLength = xLength*xUnits
        	xScale = float(xCalLength)/float(xNoE)
    return xScale

def writeData(location_w_name, data):
	f = open(location_w_name, 'wt')
	try:
		writer = csv.writer(f)
		writer.writerow([';Cyto#,CytoLabel,CytoArea,CytoMea,CytoXM,CytoYM,CytoPerim.,CytoMajor,CytoMinor,CytoAngle,CytoCirc.,CytoAR,CytoRound,CytoSolidity,Nuc#,NucLabel,NucArea,NucMea,NucXM,NucYM,NucPerim.,NucMajor,NucMinor,NucAngle,NucCirc.,NucAR,NucRound,NucSolidity,Scale,CytoRadius,NucRadius,NCR'])
		for i in data:
			writer.writerow(i[0][0].split('\t') + i[1][0].split('\t') + [str(i[2])] + [str(i[3])] + [str(i[4])] + [str(i[5])])
	finally:
		f.close()
	return True

op = OpenDialog("Choose Filepath Data...")
filepath = op.getDirectory()
filelist = os.listdir(filepath)
metadata = []
imgsdata = []
for i in filelist:
	if i.split('_')[-1] == 'Properties.xml':
		metadata.append(i)
	if i.split('.')[-1] == 'tif':
		imgsdata.append(i.split('_')[0])

imgsdata = getUniques(imgsdata)
metadata = getUniques(metadata)
data = []

for i in imgsdata:
		titles = WindowManager.getImageTitles()
		p = re.compile(r'^Result')
		for title in titles:
			m = p.search(title)
			if m is not None:
				computedImage = WindowManager.getImage(title)
				computedImage.close()

		IJ.showStatus("Computing...")
		computedImage = reduce(self.addImages,imgList)
		computedImage.show()
		IJ.showStatus("Ready")


## Main body of script
opener = OpenDialog("Select parent LSM file...")
parentLSMFilePath = opener.getPath()
if (parentLSMFilePath is not None):
	stackInfo = parse_tile_info_file(parentLSMFilePath + "_tiles/tile_info.txt")
	channelTexts = map(lambda x: str(x), filter(lambda x:os.path.isfile(parentLSMFilePath+"_tiles/objects/C"+str(x)+".objects.keep.unique.csv"),range(1,stackInfo[0]+1)))
	gd = GenericDialog("Specify parameters...")
	gd.addChoice("Which_channel",channelTexts,channelTexts[0])
	gd.showDialog()
	if gd.wasOKed():
		channel = int(gd.getNextChoice())

		## Obtains global coordinate system for tiles
		scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif")

		## Parses each of the object files
		objectDB = [[] for x in range(4)]
Ejemplo n.º 37
0
##########################################################################
# Tomar una imagen abierta en una ventana
##########################################################################
def getImage(title):
	IJ.selectWindow(title)
	return IJ.getImage() 



##########################################################################
# Main function
##########################################################################


#Selección de la imagen de entrada
od = OpenDialog("Select the image stack...", None)  
filename = od.getFileName()
if filename is None:  
	sys.exit()
inputdir = od.getDirectory()
filepath = inputdir + filename  

resultsFileStats = inputdir+"aux_3D_OC_Stats"

#se abren las opciones de stack
img = IJ.openImage( filepath )#por algún motivo no se carga el objeto ImagePlus en la salida imp
img = IJ.getImage()#línea agregada para obtener el objeto ImagePlus en la variable imp
#imp.show()
img.setTitle( "X0" )

#me quedo con el canal que tiene la cilia que por lo general es el verde (canal C1)
Ejemplo n.º 38
0
			continue

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

		i += 1

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

	srcDir = OpenDialog('Select a text file with your folders to batch process')
	print srcDir
	if srcDir:
		print srcDir.getDirectory()
		print srcDir.getFileName()
		fullPath = srcDir.getDirectory() + srcDir.getFileName()
		opentextfile(fullPath)
		# run()
	else:
		bPrintLog('Cancelled by user', 0)
		
Ejemplo n.º 39
0
from ij import IJ, ImagePlus, ImageStack
from ij.process import FloatProcessor  
from array import zeros  
from ij.io import OpenDialog 
from ij.plugin.frame import RoiManager
import os

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

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

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

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

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

refImp = IJ.openImage(refpath)
Ejemplo n.º 40
0
def open_Octopus_file():

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

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

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

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

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

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

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

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

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

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

	# sort the file numbers
	sorted_filenums = sorted(filenums)

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


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

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

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

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

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

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

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

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

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

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

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


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

		else:
			break

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

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

	return True
from ij import IJ, ImagePlus, ImageStack
from ij.process import ImageStatistics as IS
from ij.gui import Plot as Plot
from ij.gui import PlotWindow as PlotWindow
from ij.io import OpenDialog
#from loci.plugins.util import BFVirtualStack

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

		IJ.log("time focus " + str(time.clock() - timestart))
		IJ.run("Collect Garbage")
		
		#IJ.run("Close all forced")
		#IJ.run("Clear Results")
		
	except BaseException, err:
Ejemplo n.º 43
0
Archivo: dog.py Proyecto: bpavie/DOG
LIMIT_SPHERE_PER_MESH=3495 #Limit of number of icospheres per Mesh

#############################
# USER PARAMETERS TO CHANGE
#############################
#Diameter in microns
cellDiameter=3.0
# The minimum intensity for a peak to be considered
minPeak=0
#Use point(1), icosphere(2), or icosphere but limited to the first 3495 points in X (3)
plotType=USE_POINT
# diameter Cell visualization
cellIcosophere=3.0

#Open the image and duplicate it to get an 8 Bits version use to plot
od = OpenDialog("Open image file", None)
srcFile = od.getPath()
srcDir = od.getDirectory()
imp = BF.openImagePlus(srcFile)[0]
imp8Bits = imp.duplicate()
ImageConverter(imp8Bits).convertToGray8()
print "Image " + srcFile + " open successfully!"
#Create the coordinate.txt file to ouput the point coordinate
coordinateFile = open(srcDir + "coordinate.txt", "w")
print "Created " +srcDir + "coordinate.txt"
# If minPeak is set to 0, set it to automatically.
if minPeak == 0:
	minPeak = AutoThresholder().getThreshold("Percentile", imp.getStatistics().histogram); 

#Get the pixel calibration
cal=imp.getCalibration()
Ejemplo n.º 44
0
def generateDeconvolutionScriptUI(srcDir,
                                  tgtDir,
                                  calibration,
                                  preCropAffines,
                                  ROI,
                                  postCropAffines):
  """
  Open an UI to automatically generate a script to:
  1. Register the views of each time point TM folder, and deconvolve them.
  2. Register deconvolved time points to each other, for a range of consecutive time points.

  Will ask for the file path to the kernel file,
  and also for the range of time points to process,
  and for the deconvolution iterations for CM00-CM01, and CM02-CM03.
  """

  template = """
# AUTOMATICALLY GENERATED - %s

import sys, os
sys.path.append("%s")
from lib.isoview import deconvolveTimePoints
from mpicbg.models import RigidModel3D, TranslationModel3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL

# The folder with the sequence of TM\d+ folders, one per time point in the 4D series.
# Each folder should contain 4 KLB files, one per camera view of the IsoView microscope.
srcDir = "%s"

# A folder to save deconvolved images in, and CSV files describing features, point matches and transformations
targetDir = "%s"

# Path to the volume describing the point spread function (PSF)
kernelPath = "%s"

calibration = [%s] # An array with 3 floats (identity--all 1.0--because the coarse affines, that is,
                   # the camera transformations, already include the scaling to isotropy computed using the original calibration.

# The transformations of each timepoint onto the camera at index zero.
def cameraTransformations(dims0, dims1, dims2, dims3, calibration):
  return {
    0: [%s],
    1: [%s],
    2: [%s],
    3: [%s]
  }

# Deconvolution parameters
paramsDeconvolution = {
  "blockSizes": None, # None means the image size + kernel size. Otherwise specify like e.g. [[128, 128, 128]] for img in images]
  "CM_0_1_n_iterations": %i,
  "CM_2_3_n_iterations": %i,
}

# Joint dictionary of parameters
params = {}
params.update(paramsDeconvolution)

# A region of interest for each camera view, for cropping after registration but prior to deconvolution
roi = ([%s], # array of 3 integers, top-left coordinates
       [%s]) # array of 3 integers, bottom-right coordinates

# All 4 cameras relative to CM00
fineTransformsPostROICrop = \
   [[1, 0, 0, 0,
     0, 1, 0, 0,
     0, 0, 1, 0],
    [%s],
    [%s],
    [%s]]

deconvolveTimePoints(srcDir, targetDir, kernelPath, calibration,
                    cameraTransformations, fineTransformsPostROICrop,
                    params, roi, fine_fwd=True, subrange=range(%i, %i))
  """

  od = OpenDialog("Choose kernel file", srcDir)
  kernel_path = od.getPath()
  if not kernel_path:
    JOptionPane.showMessageDialog(None, "Can't proceed without a filepath to the kernel", "Alert", JOptionPane.ERROR_MESSAGE)
    return

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  msg = ["Edit parameters, then push the button",
         "to generate a script that, when run,",
         "will execute the deconvolution for each time point",
         "saving two 3D stacks per time point as ZIP files",
         "in the target directory under subfolder 'deconvolved'.",
         "Find the script in a new Script Editor window.",
         " "]
  gc.gridy = -1 # init
  for line in msg:
    label = JLabel(line)
    gc.anchor = GBC.WEST
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.gridheight = 1
    gb.setConstraints(label, gc)
    panel.add(label)

  strings = [["Deconvolution iterations",
              "CM_0_1_n_iterations", "CM_2_3_n_iterations"],
             ["Range",
              "First time point", "Last time point"]]
  params = {"CM_0_1_n_iterations": 5,
            "CM_2_3_n_iterations": 7,
            "First time point": 0,
            "Last time point": -1} # -1 means last
  insertFloatFields(panel, gb, gc, params, strings)

  def asString(affine):
    matrix = zeros(12, 'd')
    affine.toArray(matrix)
    return ",".join(imap(str, matrix))

  def generateScript(event):
    script = template % (str(datetime.now()),
                         filter(lambda path: path.endswith("IsoView-GCaMP"), sys.path)[-1],
                         srcDir,
                         tgtDir,
                         kernel_path,
                         ", ".join(imap(str, calibration)),
                         asString(preCropAffines[0]),
                         asString(preCropAffines[1]),
                         asString(preCropAffines[2]),
                         asString(preCropAffines[3]),
                         params["CM_0_1_n_iterations"],
                         params["CM_2_3_n_iterations"],
                         ", ".join(imap(str, ROI[0])),
                         ", ".join(imap(str, ROI[1])),
                         asString(postCropAffines[1]),
                         asString(postCropAffines[2]),
                         asString(postCropAffines[3]),
                         params["First time point"],
                         params["Last time point"])
    tab = None
    for frame in JFrame.getFrames():
      if str(frame).startswith("org.scijava.ui.swing.script.TextEditor["):
        try:
          tab = frame.newTab(script, "python")
          break
        except:
          print sys.exc_info()
    if not tab:
      try:
        now = datetime.now()
        with open(os.path.join(System.getProperty("java.io.tmpdir"),
                               "script-%i-%i-%i_%i:%i.py" % (now.year, now.month, now.day,
                                                             now.hour, now.minute)), 'w') as f:
          f.write(script)
      except:
        print sys.exc_info()
        print script
  

  gen = JButton("Generate script")
  gen.addActionListener(generateScript)
  gc.anchor = GBC.CENTER
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(gen, gc)
  panel.add(gen)

  frame = JFrame("Generate deconvolution script")
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
Ejemplo n.º 45
0
from ij import IJ
from ij.io import OpenDialog
from loci.formats import ImageReader
from loci.formats import MetadataTools

# open file
od = OpenDialog("Choose a file");
filepath = od.getPath()
print("Image path: " + filepath);

# use bio-formats to extract information
reader = ImageReader()
omeMeta = MetadataTools.createOMEXMLMetadata()
reader.setMetadataStore(omeMeta)
reader.setId(filepath)

seriesCount = reader.getSeriesCount()
print "Series count:",seriesCount
reader.close()


    print directories
    for filename in sorted(filenames):
      #print filenames
      if not ((".tif" in filename)):
        continue
      elif (("--fiji-out" in filename)):
        continue
      else:
        #print root
        #print directories
        #print filename
        analyze(root, filename)
        

  
          
if __name__ == '__main__':
  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/almfscreen/tischer/Henning/2015-11-04--data/2_subset"
  
  #if None != foldername:
  #  print "foldername = "+foldername
  getFilesAndAnalyze(foldername)
  #imp = IJ.getImage()
  #analyze(imp)
import re
import os
import shutil
from ij.gui import NonBlockingGenericDialog
from ij.gui import MessageDialog
from ij.io import OpenDialog
from ij import IJ
from ij import WindowManager
from ij import ImagePlus
from ij.plugin import ChannelSplitter

od = OpenDialog("Select LSM file to work on...")
imagePath = od.getPath()
if (imagePath is not None):
	tileDir = imagePath + "_tiles/"
	if (os.path.exists(tileDir)):
		metadata = IJ.openAsString(tileDir+"tile_info.txt")

		## Creates directory to store analysis files
		if not os.path.exists(tileDir + "objects"):
			os.mkdir(tileDir + "objects")
	
		## Analyzes the tile metadata
		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)
Ejemplo n.º 48
0
from __future__ import print_function

import os

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

#from loci.plugins import BF

#path = '/Users/cudmore/box/data/sami/Cell_1/1_5ADVMLEG1L1.oir'
path = '/Users/cudmore/box/data/sami/200108/WT_Female/Cell_8/8_5ADVMLEG1L1_ch2.tif'

# ask user for file. I do not know how to handle when users hits cancel??? Script will just fail
if path is None or not os.path.isfile(path):
    notUsedBy_oxs = 'Open a _ch2.tif file'
    path = OpenDialog(notUsedBy_oxs).getPath()
    if path is None:
        exit()

print('    user selected path:', path)
fileName = os.path.basename(path)

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

# save channel 1
windowName = 'C1-' + fileName
IJ.selectWindow(windowName)
windowName_notSure = ij.WindowManager.getImage(windowName)
Ejemplo n.º 49
0
def regBf(fn=None, imp=None, refId=None):
    """ 
        Register a time series stack to a specified reference slice, 
            from a file (imported by BioFormat) or a stack ImagePlus.
        Returns a registered ImagePlus.
        The stack must have only 1 z layer.
        refId is in the format of [int channel, int slice, int frame]
            If no refId is supplied, will use the first slice [1,1,1]

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

    """

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

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

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

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

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

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

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

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

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

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

    tr = TurboReg_()

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

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

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

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

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

        # toRegImp.flush()

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

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

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

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

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

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

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

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

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

    return imp2
from ij import IJ, ImagePlus  #load the FIJI modules
from ij.io import FileSaver
from ij.io import OpenDialog
import os
#from ij.measure import ResultsTable
from fiji.threshold import Auto_Threshold

IJ.run("Clear Results")

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

print filename
print directory
print path

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

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

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

#imp2 = IJ.getImage()
Ejemplo n.º 51
0
def filechooser():
    od = OD("Choose image data file...")
    return (od.getPath(), od.getFileName(), od.getDirectory())
Ejemplo n.º 52
0
        for spot in ls:
            values = [spot.ID(), trackID, spot.getFeature('FRAME'), \
                spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')]
            for i in range(nChannels):
                values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1)))
                
            IJ.log(rowStr % tuple(values))
            l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8])
            wr.writerow(l1)
    
    myfile.close()
    IJ.selectWindow("Merged")
    IJ.run("Close")

    
od = OpenDialog("Time Laps Images", "")
firstDir = od.getDirectory()
fileList = os.listdir(firstDir)

if "DisplaySettings.json" in fileList:
    fileList.remove("DisplaySettings.json")
if ".DS_Store" in fileList:  
    fileList.remove(".DS_Store")  

totalCount = []
i = 1
for fileName in fileList:
    currentFile = firstDir + fileName
    print(firstDir)
    IJ.run("Bio-Formats Importer", "open=" + currentFile + " autoscale color_mode=Composite view=Hyperstack stack_order=XYCZT")
    track()
import os
import math
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ
from ij import WindowManager

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

	# Asks for parameters
	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Start tile:",1,0)
	gd.addNumericField("Finish tile:",9,0)
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addNumericField("Step size (higher is faster but uses more memory):",10,0)
	gd.showDialog()
	startTile = int(gd.getNextNumber())
	finishTile = int(gd.getNextNumber())
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
	stepSize = int(gd.getNextNumber())
	def runOnFile(self, afile, show = True, jobnr = None):
		afile = str(afile)
		if afile == '' or afile is None:
			od = OpenDialog("Choose image file", None)
			if od.getFileName() == None:
				return
			afile = os.path.join(od.getDirectory(), od.getFileName())
		if '.log' in afile:
			return
		
		try:
			zk = ZeissKeys()
			msg = Message()
			print "Hi"
			if self.jobs is None:
				IJ.showMessage("You need to first set the parameters")
			
			if all([job['pip']=='None' for job in self.jobs]):
				IJ.showMessage("Nothing to do! At least on job different than None") 
				return 0
			
			#create a copy otherwise self.jobs gets overwritten
			jobs = copy.deepcopy(self.jobs)
			random.seed()
			
			#create a roiManager in case one is missing and reset it
			roim = RoiManager.getInstance()
			if roim == None:
				roim = RoiManager()
			roim.runCommand("reset")
			
			for i, job in enumerate(self.jobs):
				jobl = job #not really necessary
				if jobl['pip'] == 'None':
					continue
				self.JOBS_DICT[jobl['pip']] + jobl['task'] + "_" 
				
				if jobnr is not None:
					if jobnr == i:
						#force opening
						imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']), 1)
					else: 
						continue
				else:
					imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']))
				print imageDef
				jobl['channel'] = int(jobl['channel'])
				
				if imageDef is None:
					continue
				#clean up registry for errors
				IJ.log("Clean up errorMsg registry")
				IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_errormsg+" value=[""] windows=REG_SZ")
				
				[imageC, pixelSize, filepath, filename] = imageDef
				if jobl['channel'] > len(imageC):
					raise IOError('Expecting at least ' + str(jobl['channel']) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
				
				self.rois = [None]*self.nrOfJobs
				self.Segs = [None]*self.nrOfJobs
				self.Procs = [None]*self.nrOfJobs
				#switch color to Cyan for better visibility
				IJ.run(imageC[jobl['channel']-1], "Cyan", "")

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

				#write values to registry
				try:
					executeTask_Weka(validParticles, **jobl)
				except Exception, err:
					self.exitWithError(str(err))
					return
				
				if self.rois[i] is None:
					imageC[jobl['channel']-1].show()
					self.Segs[i].show()
					self.Procs[i].show()
					continue
				if validParticles is None:
					particle = []
				else:
					particle = [part[0] for part in validParticles]
				imgOut = autTool.createOutputImg(imageC[jobl['channel']-1], self.rois[i], particle)
				
				imgOut.show()	
				self.saveOutputImg(imgOut, filepath, i+1)			
				
			IJ.run("Collect Garbage", "")
from ij.process import LUT
from java.awt import Color

## Function definitions
def make_image_binary(theImage):
	for z in range(1,theImage.getNSlices()+1):
		theImage.setSlice(z)
		theProcessor = theImage.getProcessor()
		for x in range(theImage.getWidth()):
			for y in range(theImage.getHeight()):
				if theProcessor.getPixel(x,y) > 0:
					theProcessor.putPixel(x,y,255)
	return theImage

## Main body of script
od = OpenDialog("Select parent LSM file to work on...")
parentLSMFilePath = od.getPath()
if (parentLSMFilePath is not None):
	try:
		if not os.path.isdir(parentLSMFilePath + "_tiles/objects/"):
			os.mkdir(parentLSMFilePath + "_tiles/objects/")
		if not os.path.isdir(parentLSMFilePath + "_tiles/surfaces/"):
			os.mkdir(parentLSMFilePath + "_tiles/surfaces/")
		if not os.path.isdir(parentLSMFilePath + "_tiles/maps/"):
			os.mkdir(parentLSMFilePath + "_tiles/maps/")
	except:
		print "Error making output directory"
		
	## Opens a tile to get number of channels in the image
	params = ("open=["+ parentLSMFilePath + "_tiles/tile_1.ome.tif] " + 
			"color_mode=Default view=Hyperstack stack_order=XYCZT")
Ejemplo n.º 56
0
import sys.path
# from java.lang.System import getProperty
 
print(sys.path)
# extend the search path by $FIJI_ROOT/bin/
path.append('/home/ehrenfeu/.local/lib/python2.7')
path.append('/home/ehrenfeu/.local/lib/python2.7/site-packages/volpy')
# path.append('C:\\Devel\\imcf_toolbox\\lib\\python2.7')
# path.append('C:\\Devel\\imcf_toolbox\\lib\\python2.7\\volpy')

import fluoview as fv
from log import log, set_loglevel

# set_loglevel(1)

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

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

mf = base + 'MATL_Mosaic.log'

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

  log("#\n# Elastix registration\n#")
    
  #
  # GET PARAMETERS
  #
  
  od = OpenDialog("Select parameter file (press CANCEL if you don't have one)", None)
  f = od.getPath()
  
  if f:
    print('loading parameters from file')
    f = open(f, 'r'); p_gui = pickle.load(f); f.close()
  else:
    print('starting from default parameters')
    # make parameter structure if it has not been loaded
    p_gui = {}
    # exposed to GUI
    p_gui['expose_to_gui'] = {'value': ['version','input_folder', 'output_folder', 'output_format', 'channels', 'ch_ref', 'reference_image_index', 'transformation', 
                          'image_background_value', 'mask_file', 'mask_roi', 'maximum_number_of_iterations', 'image_pyramid_schedule', 'step_sizes',
                          'number_of_spatial_samples', 'elastix_binary_file', 'transformix_binary_file']}
    
    IJ.log("Operating system: "+get_os_version())
    if(get_os_version() == "windows 10"): 
      p_gui['input_folder'] = {'choices': '', 'value': 'C:\\Users', 'type': 'folder'}
      p_gui['output_folder'] = {'choices': '', 'value': 'C:\\Users', 'type': 'folder'}
    elif (get_os_version() == "mac os x"):
      p_gui['input_folder'] = {'choices': '', 'value': '/Users/tischi/Documents/fiji-registration/example-data/2d-affine/', 'type': 'folder'}
      p_gui['output_folder'] = {'choices': '', 'value': '/Users/tischi/Documents/fiji-registration/example-data/2d-affine--fiji/', 'type': 'folder'}
    elif (get_os_version() == "linux"):
      p_gui['input_folder'] = {'choices': '', 'value': '/g/almfspim', 'type': 'folder'}
      p_gui['output_folder'] = {'choices': '', 'value': '/g/almfspim', 'type': 'folder'}
    else:
      p_gui['input_folder'] = {'choices': '', 'value': '', 'type': 'folder'}
      p_gui['output_folder'] = {'choices': '', 'value': '', 'type': 'folder'}

    p_gui['version'] = {'choices': ['HenningNo5','Sandbox'], 'value': 'HenningNo5', 'type': 'string'}
    p_gui['output_format'] = {'choices': ['mha','h5'], 'value': 'h5', 'type': 'string'}
    p_gui['image_dimensions'] = {'choices': '', 'value': 3, 'type': 'int'} 
    p_gui['channels'] = {'choices': '', 'value': 'ch0', 'type': 'string'}
    p_gui['ch_ref'] = {'choices': '', 'value': 'ch0', 'type': 'string'}
    p_gui['reference_image_index'] = {'choices': '', 'value': 0, 'type': 'int'}
    p_gui['transformation'] = {'choices': ['TranslationTransform', 'EulerTransform', 'AffineTransform'], 'value': 'TranslationTransform', 'type': 'string'}
    p_gui['image_background_value'] = {'choices': '', 'value': 'minimum_of_reference_image', 'type': 'string'}
    p_gui['mask_file'] = {'choices': '', 'value': '', 'type': 'file'}
    p_gui['mask_roi'] = {'choices': '', 'value': '10,10,10,100,100,100', 'type': 'string'}
    p_gui['maximum_number_of_iterations'] = {'choices': '', 'value': 100, 'type': 'int'}
    p_gui['image_pyramid_schedule'] = {'choices': '', 'value': '40,40,10;4,4,1', 'type': 'string'}
    p_gui['step_sizes'] = {'choices': '', 'value': '4;0.4', 'type': 'string'}
    p_gui['number_of_spatial_samples'] = {'choices': '', 'value': 'auto', 'type': 'string'}    

    if(get_os_version() == "windows 10"): 
      p_gui['elastix_binary_file'] = {'choices': '', 'value': 'C:\\Program Files\\elastix_v4.8\\elastix', 'type': 'file'}
      p_gui['transformix_binary_file'] = {'choices': '', 'value': 'C:\\Program Files\\elastix_v4.8\\transformix', 'type': 'file'}
    elif (get_os_version() == "mac os x"):
      p_gui['elastix_binary_file'] = {'choices': '', 'value': '/Users/tischi/Downloads/elastix_macosx64_v4.8/bin/elastix', 'type': 'file'}
      p_gui['transformix_binary_file'] = {'choices': '', 'value': '/Users/tischi/Downloads/elastix_macosx64_v4.8/bin/transformix', 'type': 'file'}
    elif (get_os_version() == "linux"):
      p_gui['elastix_binary_file'] = {'choices': '', 'value': '/g/almf/software/bin/run_elastix.sh', 'type': 'file'}
      p_gui['transformix_binary_file'] = {'choices': '', 'value': '/g/almf/software/bin/run_transformix.sh', 'type': 'file'}
    else:
      p_gui['elastix_binary_file'] = {'choices': '', 'value': '', 'type': 'file'}
      p_gui['transformix_binary_file'] = {'choices': '', 'value': '', 'type': 'file'}
      
    p_gui['number_of_resolutions'] = {'value': ''}
    p_gui['elastix_parameter_file'] = {'value': ''}

  #
  # Expose parameters to users
  #
  p_gui = get_parameters(p_gui)
  if not p_gui:
    log("Dialog was cancelled")
    return
    
  #
  # Create derived paramters
  #
  p_gui['number_of_resolutions'] = {'value': len(p_gui['image_pyramid_schedule']['value'].split(";"))}
  p_gui['elastix_parameter_file'] = {'value': os.path.join(p_gui['output_folder']['value'], 'elastix-parameters.txt')}
  
  #
  # Create output folder if it does not exist
  #
  
  ensure_empty_dir(p_gui['output_folder']['value'])
   
  #
  # Save gui parameters
  #
  
  f = open(os.path.join(p_gui['output_folder']['value'], 'fiji-elastix-gui-parameters.txt'), 'w')
  pickle.dump(p_gui, f)
  f.close()
   
  #
  # Reformat gui parameters into actual parameters
  # 
  
  p = {}
  for k in p_gui.keys():
    p[k] = p_gui[k]['value']
  
  p['channels'] = p_gui['channels']['value'].split(","); p['channels'] = map(str, p['channels'])
  if  p_gui['mask_roi']['value']:
  	p['mask_roi'] = p_gui['mask_roi']['value'].split(","); p['mask_roi'] = map(int, p['mask_roi'])  
  else:
    p['mask_roi'] = None
 
  #
  # DETERMINE INPUT FILES
  #

  print(p['input_folder'])
  
  if not ( os.path.exists(p['input_folder']) ):
  	IJ.showMessage("The selected input folder doesn't seem to exist.\nPlease check the spelling.");
  	return;
  	
  tbModel = TableModel(p['input_folder'])
  files = get_file_list(p['input_folder'], '(.*).tif')
  	
  #
  # INIT INTERACTIVE TABLE
  #
  
  tbModel.addFileColumns('Reference','IMG')
  
  for ch in p["channels"]:
    tbModel.addFileColumns('Input_'+ch,'IMG')
  
  for ch in p["channels"]:
    tbModel.addFileColumns('Transformed_'+ch,'IMG')

  # store transformation file path
  tbModel.addFileColumns('Transformation','TXT')
  
  
  sorted_files = sorted(files)
  print("#\n# Files to be analyzed\n#")
  for ch in p["channels"]:
    iDataSet = 0
    for afile in sorted_files:
      if ch in afile.split(os.sep)[-1]:
        if ch == p["channels"][0]:
          tbModel.addRow()
          print(str(iDataSet)+": "+afile)
        tbModel.setFileAbsolutePath(afile, iDataSet, "Input_"+ch,"IMG")
        iDataSet = iDataSet + 1

  # have any files been found?
  if( iDataSet == 0 ):
  	IJ.showMessage("No matching file could be found; maybe the selected channels are incorrect?!");
  	return;
  		
  frame=ManualControlFrame(tbModel)
  #frame.setVisible(True)
  
  #
  # Inspect reference image file to determine some of the parameters and create a mask file
  #
  
  print(p['reference_image_index'])
  print(tbModel.getRowCount())
  if p['reference_image_index'] > tbModel.getRowCount():
  	IJ.showMessage("Your reference image index is larger than the number of valid files in the selected folder.\n" +
  	"Possible reasons could be:\n" +
  	"- the (case-sensitive) spelling of your channels is not correct and no files could be found \n" +
  	"- you typed a too high number for the reference image ID; please note that the ID is zero-based => if you have 74 images in the folder the highest ID is 73 and the lowest is 0"
  	);
  	return
  
  p['reference_image'] = tbModel.getFileAbsolutePathString(p['reference_image_index'], "Input_"+p['ch_ref'], "IMG")
  imp = IJ.openImage(p['reference_image'])
  
  stats = StackStatistics(imp)
  if p['image_background_value'] == 'minimum_of_reference_image':
    p['image_background_value'] = stats.min
  else:
    p['image_background_value'] = int(p['image_background_value'])
  p['image_dimensions'] = imp.getNDimensions()
  p['voxels_in_image'] = stats.longPixelCount

  p['maximum_step_length'] = max(1, int(imp.getWidth()/500))

  
  #
  # Stepsize management
  #
  # Not used in version=HenningNo5	
  
  # a_k =  a / (k + A)^alpha; where k is the time-point
  # the actual step-size is a product of ak and the gradient measured in the image
  # the gradients are typically larger in finer resolutions levels and thus the step-size needs to be smaller, accordingly 

  

  p['SP_A'] = round( int(p['maximum_number_of_iterations']) * 0.1 ) # as recommended by the manual
  p['SP_alpha'] = 0.602 # as recommended by the manual

  
  #
  # Create mask file
  #

  if p['mask_roi']:
    if not p['mask_file']:
      p['mask_file'] = make_mask_file(p, imp) 
  
  if p['mask_file']:
    imp_mask = IJ.openImage(p['mask_file'])
    stats = StackStatistics(imp_mask)
    p['voxels_in_mask'] = int(stats.mean * stats.longPixelCount)
  else:
    p['voxels_in_mask'] = 'no mask'
    
  if p['mask_file']:
    p['image_sampler'] = 'RandomSparseMask'
  else:
    p['image_sampler'] = 'RandomCoordinate'
  
  #
  # Close images
  #
  
  imp.close()
  if p['mask_file']:
    imp_mask.close() 

  #
  # Number of spatial samples
  #

  if p['number_of_spatial_samples'] == 'auto':
    if p['voxels_in_mask'] == 'no mask':
      p['number_of_spatial_samples'] = int(min(3000, p['voxels_in_image']))
    else:
      p['number_of_spatial_samples'] = int(min(3000, p['voxels_in_mask']))
  else:
    p['number_of_spatial_samples'] = int(p['number_of_spatial_samples'])
  
  #
  # Log actual paramters 
  #

  for k in p.keys():
    log(k+": "+str(p[k]))
  
  #
  # Create elastix parameter file
  #

  if p['version'] == 'HenningNo5':
    make_parameter_file_version_HenningNo5(p)
  elif p['version'] == 'Sandbox':
    make_parameter_file_version_Sandbox(p)
  

  #
  # Compute transformations  
  #
  n_files = tbModel.getRowCount()
  
  # backwards from reference file
  previous_trafo = ""
  previous_transformed_image = ""
  #print("backwards")
  for i in range(p['reference_image_index'],-1,-1):
    # compute transformation and transform reference channel
    tbModel, previous_trafo, previous_transformed_image = compute_transformations(p['reference_image_index'], i, tbModel, p, p['output_folder'], previous_trafo, previous_transformed_image)    
    # apply transformation to all other channels
    tbModel = apply_transformation(i, tbModel, p, p['output_folder'])

  # forward from reference file
  previous_trafo = ""
  previous_transformed_image = ""
  #print("forward")
  for i in range(p['reference_image_index']+1,n_files,+1):
    # compute transformation and transform reference channel
    tbModel, previous_trafo, previous_transformed_image = compute_transformations(p['reference_image_index'], i, tbModel, p, p['output_folder'], previous_trafo, previous_transformed_image)    
    # apply transformation to all other channels
    tbModel = apply_transformation(i, tbModel, p, p['output_folder'])


  #
  # clean up
  #
  close_all_image_windows()
  
  #
  # analyze transformations over time
  #
  p['median_window'] = 3
  analyze_transformation_files(p, tbModel)
  
  #
  # show the interactive table
  #
  '''
  frame = ManualControlFrame(tbModel)
  frame.setVisible(True)
  '''
  
  print("done!")
Ejemplo n.º 58
0
sys.path.append(os.path.realpath(imctool_dir))

import imctools.imagej.library as lib


def view_image5d_ome(img, ome_meta):
    """

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

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

    img.show()


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


op = OpenDialog('Choose multichannel TIFF')
file = os.path.join(op.getDirectory(), op.getFileName())
load_and_view(file_name=file)
    
  return to_be_analyzed, p

    
if __name__ == '__main__':

  print("")
  print("#")
  print("# Beating Analysis")
  print("#")
  print("")
  
  #
  # GET INPUT FOLDER
  #
  od = OpenDialog("Click on one of the image files in the folder to be analysed", None)
  input_folder = od.getDirectory()
  if input_folder is None:
    sys.exit("No folder selected!")
    

  #
  # MAKE OUTPUT FOLDER
  #
  output_folder = input_folder[:-1]+"--fiji"
  if not os.path.isdir(output_folder):
    os.mkdir(output_folder)

  
  #
  # DETERMINE INPUT FILES