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)
Exemplo 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)
Exemplo n.º 3
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
Exemplo n.º 4
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
Exemplo n.º 5
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)
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
Exemplo n.º 7
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
Exemplo n.º 8
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;
Exemplo n.º 9
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)
Exemplo n.º 10
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
Exemplo n.º 11
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
Exemplo n.º 12
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
import os
import math
from ij.io import OpenDialog
from ij.gui import GenericDialog
from ij import IJ
from ij import WindowManager

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

	# Asks for parameters
	gd = GenericDialog("Set Parameters...")
	gd.addNumericField("Start tile:",1,0)
	gd.addNumericField("Finish tile:",9,0)
	gd.addNumericField("Final disk space / Initial disk space:",0.25,2)
	gd.addNumericField("Step size (higher is faster but uses more memory):",10,0)
	gd.showDialog()
	startTile = int(gd.getNextNumber())
	finishTile = int(gd.getNextNumber())
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)
	stepSize = int(gd.getNextNumber())
from ij import IJ, ImagePlus  #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()
Exemplo n.º 15
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'}
    p_gui['reg_exp'] = {'choices': '', 'value': '.*--transformed.mha$', 'type': 'folder'}
Exemplo n.º 16
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
    containers = [
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()
        name = filename
		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)]
		objectDB[0] = parse_object_file_into_db(parentLSMFilePath+"_tiles/objects/C"+str(channel)+".objects.keep.contained.csv")
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)
Exemplo n.º 20
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)
Exemplo n.º 21
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)
Exemplo n.º 22
0
def filechooser():
    od = OD("Choose image data file...")
    return (od.getPath(), od.getFileName(), od.getDirectory())
Exemplo n.º 23
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()


# @ImagePlus imp

import json, os, csv
from ij import IJ
from ij.gui import WaitForUserDialog, PolygonRoi, Roi
from ij.io import OpenDialog

line_width = 1
default_edges_path = "C:\\Users\\dougk\\Desktop\\Membranes 2019-01-11 15-24-07.json"
od = OpenDialog('Select the edges file from previous analysis...',
                os.path.dirname(default_edges_path),
                os.path.basename(default_edges_path))
edges_file_path = od.getPath()
print(edges_file_path)
settings_file_name = "MembraneEvolutionAnalysisSettings.json"
# assume settings file and edges file are in the same directory...
settings_file_path = os.path.join(os.path.dirname(edges_file_path),
                                  settings_file_name)

f = open(edges_file_path, 'r')
try:
    edges_dct = json.loads(f.read())
finally:
    f.close()

# check if open image corresponds to selected edge data...
original_image_file = edges_dct[0]['input_image_title']
if imp.getTitle() is not original_image_file:
    WaitForUserDialog("WARNING!", (
        "Open image title is " + str(imp.getTitle()) +
        ", whilst edge file was generated on " + str(original_image_file) +
Exemplo n.º 25
0
        writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter'])
        writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2'])

    # save roi
    if rm.getCount() != 0:
        rm.runCommand('Save', os.path.join(result_path, 'Roi.zip'))

    zimp.close()
    imp.close()
    rm.close()
    zrt.reset()

if __name__ in ['__builtin__','__main__']:
    # ask file path via dialog
    open_file_dialog = OpenDialog('Opend file')
    path = open_file_dialog.getPath()

    # ask parameter via dialog
    parameter_dialog = GenericDialog('Parameter setting')
    parameter_dialog.addNumericField('Frame number', 1000,0)
    parameter_dialog.addNumericField('Frame rate (frame/s)', 100, 1)
    parameter_dialog.addChoice('Are motor rotation direction and cell rotation direction on image same?', 
                               ['Same', 'Different'], 'Same')
    parameter_dialog.showDialog()
    frame_number = int(parameter_dialog.getNextNumber())
    frame_rate = 100.0
    choice = parameter_dialog.getNextChoice()
    if choice == 'Same':
        CCW = 1
    else:
        CCW = -1
Exemplo n.º 26
0
Arquivo: dog.py Projeto: bpavie/DOG
#############################
# 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()
#Set Gaussian Sigma parameters for the Difference of Gaussian
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!")
Exemplo n.º 28
0
"""
insert_scale.py

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

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

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

op = OpenDialog("Select an image")

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

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

if __name__ in ['__builtin__', '__main__']:
	pass
	
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")
	IJ.run("Bio-Formats Importer", params)
Exemplo n.º 30
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+)')