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 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
def run():
  projects = Project.getProjects()
  if projects is None or projects.isEmpty():
    IJ.log('No project open!')
    return
  ls = projects.get(0).getRootLayerSet()
  trees = ls.getZDisplayables(Treeline)
  trees.addAll(ls.getZDisplayables(AreaTree))
  if trees.isEmpty():
    IJ.log('No trees to process!')
    return
  dc = DirectoryChooser('Target folder')
  targetFolder = dc.getDirectory()
  if targetFolder is None:
    return # user canceled
  if targetFolder[len(targetFolder) -1] != '/':
    targetFolder += '/'
  fdir = File(targetFolder)
  for f in fdir.listFiles():
    if f.isHidden():
      continue
    yn = YesNoCancelDialog(IJ.getInstance(), "WARNING", "Folder not empty! Continue?")
    if yn.yesPressed():
      break
    else:
      return
  process(trees, targetFolder)
Exemplo n.º 5
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
Exemplo n.º 6
0
def run():
    helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \
               "and empty calibration infomation.\n\n" + \
               ">> Press OK to Select a directory of TIFF images."
    MessageDialog(IJ.getInstance(), "Empty Calibration Guide", helpText)

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

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

            imp = IJ.openImage(imgPath)
            imp.setCalibration(Calibration())
            ic = ImageConverter(imp)
            ic.convertToGray8()
            IJ.saveAsTiff(imp, outPath)
            print "removed calibration and saved to ", os.path.basename(
                outPath)
Exemplo n.º 7
0
def validate(target_folder):
  f = File(target_folder)
  if len(File(target_folder).list(Filter())) > 0:
    yn = YesNoCancelDialog(IJ.getInstance(), "Warning!", "Target folder is not empty! May overwrite files! Continue?")
    if yn.yesPressed():
      return True
    else:
      return False
  return True
def run():
    helpText = "This program will batch convert .swc files to " + \
               "SVG vector graphs.\n\n" + \
               ">> Press OK to Select a directory of .swc traces."
    MessageDialog(IJ.getInstance(),"Batch SWC to SVG Guide", helpText)


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

    swc_files = [ os.path.join(d,x) for x in os.listdir(d) if re.search('(?i)\.swc$',x) ]
     
    pafm = PathAndFillManager(10240, # width
                              10240, # height
                              1, # depth
                              1, # x spacing
                              1, # y spacing
                              1, # z spacing
                              "pixel")

    for swc_file in swc_files:
        out_file = swc_file + ".svg"
     
        if not pafm.importSWC(swc_file,False): # second parameter is ignoreCalibration
            IJ.error("Failed to load: "+swc_file)
     
        for i in range(pafm.size()):
            path = pafm.getPath(i)
            
            f = open(out_file, "wb")
            f.write(toSvgString_polyline(path))
            f.close()

            f = open(swc_file + "-path.svg", "wb")
            f.write(toSvgString_path(path))
            f.close()

            f = open(swc_file + "-points.csv",'wb')
            writer = csv.writer(f)
            writer.writerow(["x", "y"])
            writer.writerows(toListOfPoints(path))
            f.close()
Exemplo n.º 9
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
Exemplo n.º 10
0
def arrange():
	
	# Fiji JFrame Instance and Measurements
	IJ_FRAME = IJ.getInstance()
	IJ_WIDTH = IJ_FRAME.getWidth()
	IJ_HEIGHT = IJ_FRAME.getHeight()
	#
	
	# Display Screen Measurements
	SCREEN_DIMS = IJ_FRAME.getGraphicsConfiguration().getBounds()
	SCREEN_WIDTH = int(SCREEN_DIMS.getWidth())
	SCREEN_HEIGHT = int(SCREEN_DIMS.getHeight())
	print SCREEN_WIDTH, SCREEN_HEIGHT
	#
	
	SPECS = {
	#	Format:
	#	WINDOW : 	[x,	y,	w,	h]
	#
		ImageJ :		[SCREEN_WIDTH - IJ_WIDTH, 0, None, None],
		TextEditor :	[SCREEN_WIDTH-640, SCREEN_HEIGHT-540, 640, 540],
		RoiManager :	[0, 0, None, None],
		TextWindow :	[0, SCREEN_HEIGHT-320, 480, 320],
		Recorder :		[0, SCREEN_HEIGHT-320-120, 480, 320],
	}
	
	# the window is Fiji JFrame itself
	x,y,w,h = SPECS[ type(IJ_FRAME) ]
	IJ_FRAME.setLocation(x,y)
	#
	
	niws = WM.getNonImageWindows()
	print "%i non-image windows are open" % (len(niws))
	for win in niws:
		print type(win)
		x, y, w, h = SPECS[ type(win) ]
		if w == None:	w = win.getWidth()
		if h == None:	h = win.getHeight()
		win.setSize(w, h)
		win.setLocation(x, y)
Exemplo n.º 11
0
def run():
    helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \
               "and empty calibration infomation.\n\n" + \
               ">> Press OK to Select a directory of TIFF images."
    MessageDialog(IJ.getInstance(),"Empty Calibration Guide", helpText)

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

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

            imp = IJ.openImage(imgPath)
            imp.setCalibration(Calibration())
            ic = ImageConverter(imp)
            ic.convertToGray8()
            IJ.saveAsTiff(imp, outPath)
            print "removed calibration and saved to ", os.path.basename(outPath)
Exemplo n.º 12
0
  event_interfaces = set([])
  while len(classes) > 0:
    cl = classes.pop() # remove the last one
    if cl.isInterface() and list(cl.getInterfaces()).count(EventListener) > 0:
      event_interfaces.add(cl)
      continue
    # Else, search its superclass and its implemented interfaces
    sup = cl.getSuperclass()
    if sup:
      classes.append(sup)
    for interface in cl.getInterfaces():
      classes.append(interface)
  return event_interfaces

# ImageJ main window deals with KeyListener, so use it too to search for interfaces
obs = [canvas, IJ.getInstance()]
classes = map(lambda x: x.getClass(), obs)

# Add spying instances of each event interface to the image canvas
for i, interface in enumerate(findEventInterfaces(*classes)):
  # Find the method, if it exists, like "addMouseListener" for "MouseListener"
  adder = getattr(canvas, "add" + interface.getSimpleName(), None)
  if adder:
    # Dynamically create a class that implements the interface
    # with all its methods using the spyEvent function to print the event
    methods = {method.getName(): spyEvent for method in interface.getDeclaredMethods()}
    event_listener_class = type('EventInterface_%i' % i, # the name of the new class
                                (interface,), # the tuple of interfaces that it implements
                                methods) # the dictionary of method names vs functions
    adder(event_listener_class()) # add a new instance
  
Exemplo n.º 13
0
#!/bin/sh
''''exec "$(dirname "$0")"/../fiji --jython "$0" "$@" # (call again with fiji)'''

from java.awt import *
from ij3d import Image3DUniverse
from javax.media.j3d import Transform3D

from ij import IJ

if IJ.getInstance() == None:
	# called from the command line
	from ij import ImageJ, ImagePlus
	from ij.process import Blitter, ColorProcessor
	from java.lang import Math
	from sys import argv

	if len(argv) > 1:
		file = argv[1]
	else:
		file = "Stitching-overview.jpg"
	if len(argv) > 2:
		label = argv[2]
	else:
		label = ''
	ImageJ()
	screenshot = IJ.openImage(file)
	print "Opened", file, screenshot
else:
	screenshot = IJ.getImage()
	label = IJ.getString('Label:', '')
Exemplo n.º 14
0
                f = open(home + '/.netrc')
                for line in f.readlines():
                    line = line.strip()
                    if line == 'machine ' + host:
                        found = True
                    elif found == False:
                        continue
                    elif line.startswith('login '):
                        user = line[6:]
                    elif line.startswith('password '):
                        password = line[9:]
                    elif line.startswith('machine '):
                        break
                f.close()
    
            if not client.isLoggedIn():
                if user != None and password != None:
                    client.logIn(user, password)
                    response = client.uploadPage(PAGE, result, 'Updated by plugin-list-parser')
                    if client.isLoggedIn():
                        client.logOut()
                    if not response:
                        print 'There was a problem with uploading', PAGE
                        if IJ.getInstance() == None:
                            sys.exit(1)
                else:
                    print 'No .netrc entry for', URL
                    if IJ.getInstance() == None:
                        sys.exit(1)
else:
    print result
Exemplo n.º 15
0
def quitIJ():
	global currentWindow
	IJ.getInstance().quit()
	currentWindow = None
Exemplo n.º 16
0
# Python05-4.py
# IJ BAR: https://github.com/tferr/Scripts#scripts
####################################################
# 5.4 Scripting ImageJ: Creating an empty image (IV)
####################################################

# What about changing the ROI properties (color, name
# name, dimensions, etc.) of the Rectangle created in
# the previous exercise? Lets ask ourselves about it:
from ij import IJ
import ij.gui.YesNoCancelDialog as dialog

# Let's prompt us for the question:
question_prompt = dialog(
    IJ.getInstance(),  # 1st argument: Parent frame
    "What about ROI properties?",  # 2nd argument: Dialog title
    "Can you change the ROI color, its name, etc?"  # 3rd argument: Dialog message
)  # see http://javadoc.imagej.net/ImageJ1/index.html?ij/gui/YesNoCancelDialog.html

# Let's get the answer:
if question_prompt.cancelPressed():  # Was the dialog canceled?
    IJ.showMessage("Refuse to answer? Are you tired?")
elif question_prompt.yesPressed():  # Was the answer "Yes"?
    IJ.showMessage("Cool. Go ahead!")
else:  # If none of the above, the remaining option was "No"
    IJ.showMessage("Hmmm... Did you look into the ij.gui.Roi API?")

# Tip 1: You will find useful methods in:
# - http://javadoc.imagej.net/ImageJ1/index.html?ij/gui/Roi.html
# - http://javadoc.imagej.net/ImageJ1/index.html?ij/ImagePlus.html
#
Exemplo n.º 17
0
def quitIJ():
	global currentWindow
	IJ.getInstance().quit()
	currentWindow = None
Exemplo n.º 18
0
from ij import IJ
from ij.plugin.frame import RoiManager
from ij.gui import PolygonRoi
from ij.gui import Roi
from java.awt import FileDialog

fd = FileDialog(IJ.getInstance(), "Open", FileDialog.LOAD)
fd.show()
file_name = fd.getDirectory() + fd.getFile()
print(file_name)

RM = RoiManager()
rm = RM.getRoiManager()

imp = IJ.getImage()

textfile = open(file_name, 'r')
for line in textfile:
    xy = map(int, line.rstrip().split(','))
    X = xy[::2]
    Y = xy[1::2]
    imp.setRoi(PolygonRoi(X, Y, Roi.POLYGON))
    #IJ.run(imp, "Convex Hull", "")
    roi = imp.getRoi()
    print roi
    rm.addRoi(roi)

rm.runCommand("Associate", "true")
rm.runCommand("Show All with labels")
                              1, # y spacing
                              1, # z spacing
                              "pixel")

    for swc_file in swc_files:
        out_file = swc_file + ".svg"
     
        if not pafm.importSWC(swc_file,False): # second parameter is ignoreCalibration
            IJ.error("Failed to load: "+swc_file)
     
        for i in range(pafm.size()):
            path = pafm.getPath(i)
            
            f = open(out_file, "wb")
            f.write(toSvgString_polyline(path))
            f.close()

            f = open(swc_file + "-path.svg", "wb")
            f.write(toSvgString_path(path))
            f.close()

            f = open(swc_file + "-points.csv",'wb')
            writer = csv.writer(f)
            writer.writerow(["x", "y"])
            writer.writerows(toListOfPoints(path))
            f.close()

##############
run()
MessageDialog(IJ.getInstance(),"Batch SWC to SVG Guide", "Done")
Exemplo n.º 20
0
def check_fusion_settings(czi_path):
    """Check for fusion settings and asks confirmation to user if H5/XML fusion

    Parameters
    ----------
    czi_path : str
        Path to the CZI file

    Returns
    -------
    bool
        Bool for fusion
    str
        Method of RAM handling
    bool
        Bool for TIFF or H5/XML fusion
    """

    # Default values
    do_fusion = True
    fuse_tiff = True

    reader = ZeissCZIReader()
    m = DynamicMetadataOptions()
    m.setBoolean(ZeissCZIReader.ALLOW_AUTOSTITCHING_KEY, False)
    m.setBoolean(ZeissCZIReader.RELATIVE_POSITIONS_KEY, True)
    reader.setMetadataOptions(m)
    omeMeta = MetadataTools.createOMEXMLMetadata()
    reader.setMetadataStore(omeMeta)
    reader.setId(str(czi_path))

    nbr_tp = omeMeta.getTimestampAnnotationCount() + 1
    nbr_chnl = omeMeta.getChannelCount(0)

    # check the file size of the file to be fused and compare to the available RAM
    # h5_filesize = os.path.getsize(export_path_temp + ".h5")
    h5_filesize = os.path.getsize(czi_path) / 2
    free_memory = get_free_memory()

    print("h5 filesize " + convert_bytes(h5_filesize))
    print("free memory in ij " + convert_bytes(free_memory))

    # TODO: include in below calculation t_end, since only one t is fused at a time.
    if free_memory > (6 * h5_filesize / downsampling):
        ram_handling = "[Precompute Image]"
    else:
        ram_handling = "Virtual"
    print("fusion mode used " + str(ram_handling))

    # if autoselect_illuminations and nbr_ill > 1:
    #     ill_value = 2
    # else:
    #     ill_value = 1

    ram_requirement = 2 * h5_filesize / (nbr_tp * nbr_chnl * downsampling)
    print(ram_requirement)
    sufficient_ram = ram_requirement < free_memory / 10

    if not sufficient_ram:
        try:
            yn = YesNoCancelDialog(
                IJ.getInstance(),
                "Warning!",
                (
                    "File size is too big to use TIFF for fusion\n"
                    "Fusion will happen using H5/XML which might take weeks. Are you "
                    "sure you want to do fusion ?\n"
                    "All steps prior to fusion would still happen, allowing for manual "
                    "fusion and tile selection."
                ),
            )
            if yn.yesPressed():
                fuse_tiff = False
            else:
                do_fusion = False
        except Exception:
            # when running headless the above will raise a java.awt.HeadlessException,
            # so we simply fall back to the same behavior as if "No" was clicked:
            do_fusion = False
    return do_fusion, ram_handling, fuse_tiff
			if Verbose:
				IJ.log('... ' + str(xpos) + ', ' + str(ypos) + ', ' + str(zpos))
			outimp.getStack().getProcessor(int(zpos)+1).putPixel(int(xpos), int(ypos), i+1)
	return outimp
	
Verbose = False
if IJ.isMacro():
    opt = getArgument()# ImageJ specific function Macro.getOptions()
    if len(opt) == 0:
        opt = OPT_PLACEHOLDER
    IJ.log(opt)
    optA = opt.split()
    Number_of_Cluster = int(optA[0])
    Iteration = int(optA[1])
else:
   gd =  GenericDialog("KMean Points Clustering", IJ.getInstance())
   gd.addNumericField("Expected Number of Clusters", 4, 0)
   gd.addNumericField("Iterations", 10, 0)
   gd.showDialog()
   Number_of_Cluster = int(gd.getNextNumber())
   Iteration = int(gd.getNextNumber())
imp = IJ.getImage()
outimp = core(imp)
outimp.show()
IJ.run(outimp, "glasbey inverted", "")