Ejemplo n.º 1
0
def create_overlay(mask):
    '''Create a bitmask overlay from a numpy boolean array
    
    mask - boolean numpy array organized as i,j = y,x
    '''
    assert mask.ndim == 2
    mask = mask.transpose()
    strides = np.array([1, mask.shape[0]])
    
    imgFactory = J.make_instance(
        "net/imglib2/img/planar/PlanarImgFactory", "()V")
    bit_type = J.make_instance("net/imglib2/type/logic/BitType", "()V")
    img = J.call(
        imgFactory, "create", 
        "([JLnet/imglib2/type/NativeType;)Lnet/imglib2/img/planar/PlanarImg;",
        np.array(mask.shape), bit_type)
    
    J.static_call("net/imglib2/util/ImgUtil", 
                  "copy", "([ZI[ILnet/imglib2/img/Img;)V",
                  mask.flatten(), 0, strides, img)
    roi = J.make_instance(
        "net/imglib2/roi/BinaryMaskRegionOfInterest",
        "(Lnet/imglib2/img/Img;)V", img)
    overlay = J.make_instance(
        "imagej/data/roi/BinaryMaskOverlay",
        "(Lnet/imglib2/roi/BinaryMaskRegionOfInterest;)V", roi)
    return overlay
Ejemplo n.º 2
0
def create_dataset(context, pixel_data, name=None, axes=None):
    """Create a dataset from a numpy array
    
    pixel_data - numpy array where index 0 is the I or Y axis, index 1 is the
                 J or X axis and index 2, if it exists, is the channel axis.
                 
    name - optional name for the dataset
    """
    dataset_service = get_dataset_service(context)
    if axes is None:
        if pixel_data.ndim == 2:
            axes = [Axes().X, Axes().Y]
            pixel_data = pixel_data.transpose((1, 0))
        else:
            axes = [Axes().X, Axes().Y, Axes().CHANNEL]
            pixel_data = pixel_data.transpose((1, 0, 2))
    #
    # Create a dataset of the correct shape, with the correct axes.
    # We make a 64-bit floating point image.
    #
    dataset = dataset_service.create1(np.array(pixel_data.shape), name, axes, 64, True, True)
    imgplus = dataset.getImgPlus()
    #
    # Now use a copying utility to fill the imgplus with array data
    #
    strides = np.cumprod([1] + list(pixel_data.shape[:0:-1]))[::-1]
    J.static_call(
        "net/imglib2/util/ImgUtil", "copy", "([DI[ILnet/imglib2/img/Img;)V", pixel_data.flatten(), 0, strides, imgplus
    )
    return dataset
Ejemplo n.º 3
0
def create_dataset(context, pixel_data, name=None, axes=None):
    '''Create a dataset from a numpy array
    
    pixel_data - numpy array where index 0 is the I or Y axis, index 1 is the
                 J or X axis and index 2, if it exists, is the channel axis.
                 
    name - optional name for the dataset
    '''
    dataset_service = get_dataset_service(context)
    if axes is None:
        if pixel_data.ndim == 2:
            axes = [Axes().X, Axes().Y]
            pixel_data = pixel_data.transpose((1, 0))
        else:
            axes = [Axes().X, Axes().Y, Axes().CHANNEL]
            pixel_data = pixel_data.transpose((1, 0, 2))
    #
    # Create a dataset of the correct shape, with the correct axes.
    # We make a 64-bit floating point image.
    #
    dataset = dataset_service.create1(np.array(pixel_data.shape), name, axes,
                                      64, True, True)
    imgplus = dataset.getImgPlus()
    #
    # Now use a copying utility to fill the imgplus with array data
    #
    strides = np.cumprod([1] + list(pixel_data.shape[:0:-1]))[::-1]
    J.static_call("net/imglib2/util/ImgUtil", "copy",
                  "([DI[ILnet/imglib2/img/Img;)V", pixel_data.flatten(), 0,
                  strides, imgplus)
    return dataset
Ejemplo n.º 4
0
 def run(self, module,
         pre = None,
         post = None,
         separateThread = False,
         **kwargs):
     '''Run a module
     
     module - the module to run
     
     pre - list of PreprocessorPlugins to run before running module
     
     post - list of PostprocessorPlugins to run after running module
     
     *kwargs - names and values for input parameters
     '''
     input_map = J.get_dictionary_wrapper(
         J.make_instance('java/util/HashMap', '()V'))
     for k,v in kwargs.iteritems():
         input_map.put(k, v)
     if pre is not None:
         pre = J.static_call("java/util/Arrays", "asList",
                             "([Ljava/lang/Object;)Ljava/util/List;",
                             pre)
     if post is not None:
         post = J.static_call("java/util/Arrays", "asList",
                              "([Ljava/lang/Object;)Ljava/util/List;",
                              post)
     future = J.call(
         self.o, "run", 
         "(Limagej/ext/module/Module;Ljava/util/List;Ljava/util/List;Ljava/util/Map;)Ljava/util/concurrent/Future;",
         module, pre, post, input_map)
     return J.call(
         self.o, "waitFor", 
         "(Ljava/util/concurrent/Future;)Limagej/ext/module/Module;",
         future)
Ejemplo n.º 5
0
 def run(self, module_info,
         pre = None,
         post = None,
         **kwargs):
     '''Run a module
     
     module_info - the module_info of the module to run
     
     pre - list of PreprocessorPlugins to run before running module
     
     post - list of PostprocessorPlugins to run after running module
     
     *kwargs - names and values for input parameters
     '''
     input_map = J.make_map(kwargs)
     if pre is not None:
         pre = J.static_call("java/util/Arrays", "asList",
                             "([Ljava/lang/Object;)Ljava/util/List;",
                             pre)
     if post is not None:
         post = J.static_call("java/util/Arrays", "asList",
                              "([Ljava/lang/Object;)Ljava/util/List;",
                              post)
     future = J.call(
         self.o, "run", 
         "(Limagej/module/ModuleInfo;"
         "Ljava/util/List;"
         "Ljava/util/List;"
         "Ljava/util/Map;)"
         "Ljava/util/concurrent/Future;",
         module_info, pre, post, input_map)
     return J.call(
         self.o, "waitFor", 
         "(Ljava/util/concurrent/Future;)Limagej/module/Module;",
         future)
Ejemplo n.º 6
0
 def fn(command=command, options=options):
     if options is None:
         J.static_call("ij/IJ", "run", "(Ljava/lang/String;)V", command)
     else:
         J.static_call("ij/IJ", "run", 
                       "(Ljava/lang/String;Ljava/lang/String;)V",
                       command, options)
Ejemplo n.º 7
0
def create_dataset(pixel_data, name = None, axes = None):
    '''Create a dataset from a numpy array
    
    pixel_data - numpy array where index 0 is the I or Y axis, index 1 is the
                 J or X axis and index 2, if it exists, is the channel axis.
                 
    name - optional name for the dataset
    '''
    if axes is None:
        if pixel_data.ndim == 2:
            axes = [Axes().X, Axes().Y]
            pixel_data = pixel_data.transpose((1,0))
        else:
            axes = [Axes().X, Axes().Y, Axes().CHANNEL]
            pixel_data = pixel_data.transpose((1,0,2))
    #
    # Create a dataset of the correct shape, with the correct axes.
    # We make a 64-bit floating point image.
    #
    dataset = J.static_call(
        "imagej/data/Dataset",
        "create",
        "([JLjava/lang/String;[Lnet/imglib2/img/Axis;IZZ)Limagej/data/Dataset;",
        np.array(pixel_data.shape), name, axes, 64, True, True)
    dataset = wrap_dataset(dataset)
    imgplus = dataset.getImgPlus()
    #
    # Now use a copying utility to fill the imgplus with array data
    #
    strides = np.cumprod([1] + list(pixel_data.shape[:-1]))
    J.static_call("net/imglib2/util/ImgUtil", "copy",
                  "([DI[ILnet/imglib2/img/Img;)V",
                  pixel_data.flatten(), 0, strides, imgplus)
    return dataset
Ejemplo n.º 8
0
def create_overlay(mask):
    '''Create a bitmask overlay from a numpy boolean array
    
    mask - boolean numpy array organized as i,j = y,x
    '''
    assert mask.ndim == 2
    mask = mask.transpose()
    strides = np.array([1, mask.shape[0]])

    imgFactory = J.make_instance("net/imglib2/img/planar/PlanarImgFactory",
                                 "()V")
    bit_type = J.make_instance("net/imglib2/type/logic/BitType", "()V")
    img = J.call(
        imgFactory, "create",
        "([JLnet/imglib2/type/NativeType;)Lnet/imglib2/img/planar/PlanarImg;",
        np.array(mask.shape), bit_type)

    J.static_call("net/imglib2/util/ImgUtil", "copy",
                  "([ZI[ILnet/imglib2/img/Img;)V", mask.flatten(), 0, strides,
                  img)
    roi = J.make_instance("net/imglib2/roi/BinaryMaskRegionOfInterest",
                          "(Lnet/imglib2/img/Img;)V", img)
    overlay = J.make_instance(
        "imagej/data/roi/BinaryMaskOverlay",
        "(Lnet/imglib2/roi/BinaryMaskRegionOfInterest;)V", roi)
    return overlay
Ejemplo n.º 9
0
 def fn(command=command, options=options):
     if options is None:
         J.static_call("ij/IJ", "run", "(Ljava/lang/String;)V", command)
     else:
         J.static_call("ij/IJ", "run",
                       "(Ljava/lang/String;Ljava/lang/String;)V", command,
                       options)
Ejemplo n.º 10
0
def get_commands():
    '''Return a list of the available command strings'''
    hashtable = J.static_call('ij/Menus', 'getCommands',
                              '()Ljava/util/Hashtable;')
    if hashtable is None:
        #
        # This is a little bogus, but works - trick IJ into initializing
        #
        execute_command("pleaseignorethis")
        hashtable = J.static_call('ij/Menus', 'getCommands',
                                  '()Ljava/util/Hashtable;')
        if hashtable is None:
            return []
    keys = J.call(hashtable, "keys", "()Ljava/util/Enumeration;")
    keys = J.jenumeration_to_string_list(keys)
    values = J.call(hashtable, "values", "()Ljava/util/Collection;")
    values = [
        J.to_string(x) for x in J.iterate_java(
            J.call(values, 'iterator', "()Ljava/util/Iterator;"))
    ]

    class CommandList(list):
        def __init__(self):
            super(CommandList, self).__init__(keys)
            self.values = values

    return CommandList()
Ejemplo n.º 11
0
 def run(self, module_info, pre=None, post=None, **kwargs):
     '''Run a module
     
     module_info - the module_info of the module to run
     
     pre - list of PreprocessorPlugins to run before running module
     
     post - list of PostprocessorPlugins to run after running module
     
     *kwargs - names and values for input parameters
     '''
     input_map = J.make_map(kwargs)
     if pre is not None:
         pre = J.static_call("java/util/Arrays", "asList",
                             "([Ljava/lang/Object;)Ljava/util/List;",
                             pre)
     if post is not None:
         post = J.static_call("java/util/Arrays", "asList",
                              "([Ljava/lang/Object;)Ljava/util/List;",
                              post)
     future = J.call(
         self.o, "run", "(Limagej/module/ModuleInfo;"
         "Ljava/util/List;"
         "Ljava/util/List;"
         "Ljava/util/Map;)"
         "Ljava/util/concurrent/Future;", module_info, pre, post,
         input_map)
     return J.call(
         self.o, "waitFor",
         "(Ljava/util/concurrent/Future;)Limagej/module/Module;",
         future)
Ejemplo n.º 12
0
 def copy_plane(index, src):
     p = J.call(planar_img, "getPlane", "(I)Ljava/lang/Object;", index)
     dest = J.call(p, "getCurrentStorageArray", "()Ljava/lang/Object;")
     length = np.prod(src.shape)
     src = J.get_nice_arg(src, "[D")
     J.static_call("java/lang/System", "arraycopy",
                   "(Ljava/lang/Object;ILjava/lang/Object;II)V", src, 0,
                   dest, 0, length)
Ejemplo n.º 13
0
def update_never_remind():
    """Tell ImageJ never to remind us of updates
    
    Not as harsh as it sounds - this is done with headless preferences
    which go to /dev/null.
    """
    never = J.get_static_field("java/lang/Long", "MAX_VALUE", "J")
    J.static_call("imagej/updater/core/UpToDate", "setLatestNag", "(J)V", never)
Ejemplo n.º 14
0
def execute_command(command, options = None):
    '''Execute the named command within ImageJ'''
    if options is None:
        J.static_call("ij/IJ", "run", "(Ljava/lang/String;)V", command)
    else:
        J.static_call("ij/IJ", "run", 
                      "(Ljava/lang/String;Ljava/lang/String;)V",
                      command, options)
Ejemplo n.º 15
0
def execute_command(command, options=None):
    '''Execute the named command within ImageJ'''
    if options is None:
        J.static_call("ij/IJ", "run", "(Ljava/lang/String;)V", command)
    else:
        J.static_call("ij/IJ", "run",
                      "(Ljava/lang/String;Ljava/lang/String;)V", command,
                      options)
Ejemplo n.º 16
0
 def copy_plane(index, src):
     p = J.call(planar_img, "getPlane", "(I)Ljava/lang/Object;", index)
     dest = J.call(p, "getCurrentStorageArray", "()Ljava/lang/Object;")
     length = np.prod(src.shape)
     src = J.get_nice_arg(src, "[D")
     J.static_call("java/lang/System", "arraycopy",
                   "(Ljava/lang/Object;ILjava/lang/Object;II)V",
                   src, 0, dest, 0, length)
Ejemplo n.º 17
0
def update_never_remind():
    '''Tell ImageJ never to remind us of updates
    
    Not as harsh as it sounds - this is done with headless preferences
    which go to /dev/null.
    '''
    never = J.get_static_field("java/lang/Long", "MAX_VALUE", "J")
    J.static_call("imagej/updater/core/UpToDate", "setLatestNag", "(J)V",
                  never)
Ejemplo n.º 18
0
 def __exit__(self, type_class, value, traceback):
     if self.rdr is not None:
         self.rdr.close()
         del self.rdr.o
         del self.rdr
     if  self.stream is not None:
         jutil.call(self.stream, 'close', '()V')
     del self.stream
     #
     # Run the Java garbage collector here.
     #
     jutil.static_call("java/lang/System", "gc","()V")
Ejemplo n.º 19
0
 def __exit__(self, type_class, value, traceback):
     if self.rdr is not None:
         self.rdr.close()
         del self.rdr.o
         del self.rdr
     if self.stream is not None:
         jutil.call(self.stream, 'close', '()V')
     del self.stream
     #
     # Run the Java garbage collector here.
     #
     jutil.static_call("java/lang/System", "gc", "()V")
Ejemplo n.º 20
0
def execute_macro(macro_text):
    '''Execute a macro in ImageJ
    
    macro_text - the macro program to be run
    '''
    if sys.platform == "darwin":
        J.set_static_field("ij/macro/Interpreter", "batchMode", "Z", True)
        J.static_call("ij/IJ", "runMacro",
                      "(Ljava/lang/String;)Ljava/lang/String;", macro_text)
    else:
        show_imagej()
        interp = J.make_instance("ij/macro/Interpreter", "()V")
        J.call(interp, "run", "(Ljava/lang/String;)V", macro_text)
Ejemplo n.º 21
0
def get_pixel_data(img):
    """Get the pixel data from an image"""
    interval = wrap_interval(img)
    dims = interval.dimensions()
    #
    # Make a Java double array
    #
    a = np.zeros(np.prod(dims), np.float64)
    ja = J.get_env().make_double_array(np.ascontiguousarray(a))
    strides = np.cumprod([1] + dims[:0:-1]).astype(int)[::-1]
    J.static_call("net/imglib2/util/ImgUtil", "copy", "(Lnet/imglib2/img/Img;[DI[I)V", img, ja, 0, strides)
    a = J.get_env().get_double_array_elements(ja)
    a.shape = dims
    return a
Ejemplo n.º 22
0
def execute_macro(macro_text):
    '''Execute a macro in ImageJ
    
    macro_text - the macro program to be run
    '''
    if sys.platform == "darwin":
        J.set_static_field("ij/macro/Interpreter", "batchMode", "Z", True)
        J.static_call("ij/IJ", "runMacro", 
                      "(Ljava/lang/String;)Ljava/lang/String;",
                      macro_text)
    else:
        show_imagej();
        interp = J.make_instance("ij/macro/Interpreter","()V");
        J.call(interp, "run","(Ljava/lang/String;)V", macro_text);
Ejemplo n.º 23
0
def get_context():
    '''Get the ImageJ context
    
    This is a singleton ImageJ context. We need a singleton for now because
    of http://trac.imagej.net/ticket/1413
    This is an imagej.ImageJ, which at one point was the context.
    Call self.getContext() to get the org.scijava.Context which may be 
    what you want.
    '''
    global the_imagej_context
    if the_imagej_context is None:
        the_imagej_context = create_context(None)
        #
        # We have to turn off the updater and tell ImageJ to never call
        # System.exit. We have to tell ImageJ that we read the readme file.
        #
        # To Do: programatically turn off the updater and take control of
        #        the quitting and exit process.
        #
        max_value = J.run_script(
            "java.lang.Long.toString(java.lang.Long.MAX_VALUE);")
        prefs = [("imagej.updater.core.UpToDate", "latestNag", max_value),
                 ("imagej.core.options.OptionsMisc", "exitWhenQuitting",
                  "false")]
        plugin_service = the_imagej_context.getService(
            "org.scijava.plugin.PluginService")
        ui_interface = J.class_for_name("imagej.ui.UserInterface")
        script = """
        var result = java.lang.System.getProperty('ij.ui');
        if (! result) {
            var infos = pluginService.getPluginsOfType(ui_interface);
            if (infos.size() > 0) {
                result = infos.get(0).getClassName();
            }
        }
        result;"""
        ui_class = J.run_script(
            script,
            dict(pluginService=plugin_service, ui_interface=ui_interface))
        first_run = "firstRun-" + the_imagej_context.getVersion()
        if ui_class:
            prefs.append((ui_class, first_run, "false"))
        for class_name, key, value in prefs:
            c = J.class_for_name(class_name)
            J.static_call(
                "imagej/util/Prefs", "put",
                "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)V", c,
                key, value)
    return the_imagej_context
Ejemplo n.º 24
0
def get_pixel_data(img):
    '''Get the pixel data from an image'''
    interval = wrap_interval(img)
    dims = interval.dimensions()
    #
    # Make a Java double array
    #
    a = np.zeros(np.prod(dims), np.float64)
    ja = J.get_env().make_double_array(np.ascontiguousarray(a))
    strides = np.cumprod([1] + dims[:0:-1]).astype(int)[::-1]
    J.static_call("net/imglib2/util/ImgUtil", "copy",
                  "(Lnet/imglib2/img/Img;[DI[I)V", img, ja, 0, strides)
    a = J.get_env().get_double_array_elements(ja)
    a.shape = dims
    return a
Ejemplo n.º 25
0
def close_all_windows():
    """Close all ImageJ windows
    
    Hide the ImageJ windows so that they don't go through the Save dialog,
    then call the Window Manager's closeAllWindows to get the rest.
    """
    jimage_list = J.static_call("ij/WindowManager", "getIDList", "()[I")
    if jimage_list is None:
        return
    image_list = J.get_env().get_int_array_elements(jimage_list)
    for image_id in image_list:
        ip = J.static_call("ij/WindowManager", "getImage", "(I)Lij/ImagePlus;", image_id)
        ip = get_imageplus_wrapper(ip)
        ip.hide()
    J.static_call("ij/WindowManager", "closeAllWindows", "()Z")
Ejemplo n.º 26
0
def get_context():
    '''Get the ImageJ context
    
    This is a singleton ImageJ context. We need a singleton for now because
    of http://trac.imagej.net/ticket/1413
    This is an imagej.ImageJ, which at one point was the context.
    Call self.getContext() to get the org.scijava.Context which may be 
    what you want.
    '''
    global the_imagej_context
    if the_imagej_context is None:
        the_imagej_context = create_context(None)
        #
        # We have to turn off the updater and tell ImageJ to never call
        # System.exit. We have to tell ImageJ that we read the readme file.
        #
        # To Do: programatically turn off the updater and take control of
        #        the quitting and exit process.
        #
        max_value = J.run_script(
            "java.lang.Long.toString(java.lang.Long.MAX_VALUE);")
        prefs = [
            ("imagej.updater.core.UpToDate", "latestNag", max_value),
            ("imagej.core.options.OptionsMisc", "exitWhenQuitting", "false")]
        plugin_service = the_imagej_context.getService(
            "org.scijava.plugin.PluginService")
        ui_interface = J.class_for_name("imagej.ui.UserInterface")
        script = """
        var result = java.lang.System.getProperty('ij.ui');
        if (! result) {
            var infos = pluginService.getPluginsOfType(ui_interface);
            if (infos.size() > 0) {
                result = infos.get(0).getClassName();
            }
        }
        result;"""
        ui_class = J.run_script(script, dict(pluginService=plugin_service,
                                             ui_interface=ui_interface))
        first_run = "firstRun-"+the_imagej_context.getVersion()
        if ui_class:
            prefs.append((ui_class, first_run, "false"))
        for class_name, key, value in prefs:
            c = J.class_for_name(class_name)
            J.static_call(
                "imagej/util/Prefs", "put",
                "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)V",
                c, key, value)
    return the_imagej_context
Ejemplo n.º 27
0
def close_all_windows():
    '''Close all ImageJ windows
    
    Hide the ImageJ windows so that they don't go through the Save dialog,
    then call the Window Manager's closeAllWindows to get the rest.
    '''
    jimage_list = J.static_call('ij/WindowManager', 'getIDList', '()[I')
    if jimage_list is None:
        return
    image_list = J.get_env().get_int_array_elements(jimage_list)
    for image_id in image_list:
        ip = J.static_call('ij/WindowManager', 'getImage', 
                           '(I)Lij/ImagePlus;', image_id)
        ip = get_imageplus_wrapper(ip)
        ip.hide()
    J.static_call('ij/WindowManager', 'closeAllWindows', '()Z')
Ejemplo n.º 28
0
def get_current_image():
    """Get the WindowManager's current image
    
    returns a wrapped ImagePlus object
    """
    imageplus_obj = J.static_call("ij/WindowManager", "getCurrentImage", "()Lij/ImagePlus;")
    return get_imageplus_wrapper(imageplus_obj)
Ejemplo n.º 29
0
def getGrayColorSpace():
    """Get a Java object that represents an RGB color space
    
    See java.awt.color.ColorSpace: this returns the linear RGB color space
    """
    cs_gray = jutil.get_static_field("java/awt/color/ColorSpace", "CS_GRAY", "I")
    return jutil.static_call("java/awt/color/ColorSpace", "getInstance", "(I)Ljava/awt/color/ColorSpace;", cs_gray)
Ejemplo n.º 30
0
def show_imagej():
    '''Show the ImageJ user interface'''
    ij_obj = J.static_call("ij/IJ", "getInstance", "()Lij/ImageJ;")
    if ij_obj is None:
        ij_obj = J.make_instance("ij/ImageJ", "()V")
    J.call(ij_obj, "setVisible", "(Z)V", True)
    J.call(ij_obj, "toFront", "()V")
Ejemplo n.º 31
0
def createOMEXMLMetadata():
    '''Creates an OME-XML metadata object using reflection, to avoid direct 
    dependencies on the optional loci.formats.ome package.
    '''
    return jutil.static_call('loci/formats/MetadataTools',
                             'createOMEXMLMetadata',
                             '()Lloci/formats/meta/IMetadata;')
Ejemplo n.º 32
0
def show_imagej():
    '''Show the ImageJ user interface'''
    ij_obj = J.static_call("ij/IJ", "getInstance", "()Lij/ImageJ;")
    if ij_obj is None:
        ij_obj = J.make_instance("ij/ImageJ", "()V")
    J.call(ij_obj, "setVisible", "(Z)V", True)
    J.call(ij_obj, "toFront", "()V")
Ejemplo n.º 33
0
def close_all_windows():
    '''Close all ImageJ windows
    
    Hide the ImageJ windows so that they don't go through the Save dialog,
    then call the Window Manager's closeAllWindows to get the rest.
    '''
    jimage_list = J.static_call('ij/WindowManager', 'getIDList', '()[I')
    if jimage_list is None:
        return
    image_list = J.get_env().get_int_array_elements(jimage_list)
    for image_id in image_list:
        ip = J.static_call('ij/WindowManager', 'getImage', '(I)Lij/ImagePlus;',
                           image_id)
        ip = get_imageplus_wrapper(ip)
        ip.hide()
    J.static_call('ij/WindowManager', 'closeAllWindows', '()Z')
Ejemplo n.º 34
0
def get_current_image():
    '''Get the WindowManager's current image
    
    returns a wrapped ImagePlus object
    '''
    imageplus_obj = J.static_call('ij/WindowManager', 'getCurrentImage',
                                  '()Lij/ImagePlus;')
    return get_imageplus_wrapper(imageplus_obj)
Ejemplo n.º 35
0
def get_current_image():
    '''Get the WindowManager's current image
    
    returns a wrapped ImagePlus object
    '''
    imageplus_obj = J.static_call('ij/WindowManager','getCurrentImage',
                                  '()Lij/ImagePlus;')
    return get_imageplus_wrapper(imageplus_obj)
Ejemplo n.º 36
0
def make_color_rgb_from_html(s):
    '''Make an imagej.util.ColorRGB from an HTML color
    
    HTML colors have the form, #rrggbb or are one of the names
    from the CSS-3 colors.
    '''
    return J.static_call("fromHTMLColor", 
                         "(Ljava/lang/String;)Limagej/util/ColorRGB;", s)
Ejemplo n.º 37
0
def make_color_rgb_from_html(s):
    '''Make an imagej.util.ColorRGB from an HTML color
    
    HTML colors have the form, #rrggbb or are one of the names
    from the CSS-3 colors.
    '''
    return J.static_call("fromHTMLColor",
                         "(Ljava/lang/String;)Limagej/util/ColorRGB;", s)
Ejemplo n.º 38
0
 def test_01_09_jdictionary_to_string_dictionary(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     d = J.get_dictionary_wrapper(properties)
     pyd = J.jdictionary_to_string_dictionary(properties)
     keys = J.jenumeration_to_string_list(d.keys())
     for key in keys:
         value = J.to_string(d.get(key))
         self.assertEqual(pyd[key], value)
Ejemplo n.º 39
0
 def test_01_08_jenumeration_to_string_list(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     d = J.get_dictionary_wrapper(properties)
     keys = J.jenumeration_to_string_list(d.keys())
     enum = J.get_enumeration_wrapper(d.keys())
     for i in range(d.size()):
         key = J.to_string(enum.nextElement())
         self.assertEqual(key, keys[i])
Ejemplo n.º 40
0
def getGrayColorSpace():
    '''Get a Java object that represents an RGB color space
    
    See java.awt.color.ColorSpace: this returns the linear RGB color space
    '''
    cs_gray = jutil.get_static_field('java/awt/color/ColorSpace', 'CS_GRAY',
                                     'I')
    return jutil.static_call('java/awt/color/ColorSpace', 'getInstance',
                             '(I)Ljava/awt/color/ColorSpace;', cs_gray)
Ejemplo n.º 41
0
 def test_01_09_jdictionary_to_string_dictionary(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     d = J.get_dictionary_wrapper(properties)
     pyd = J.jdictionary_to_string_dictionary(properties)
     keys = J.jenumeration_to_string_list(d.keys())
     for key in keys:
         value = J.to_string(d.get(key))
         self.assertEqual(pyd[key], value)
Ejemplo n.º 42
0
 def test_01_08_jenumeration_to_string_list(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     d = J.get_dictionary_wrapper(properties)
     keys = J.jenumeration_to_string_list(d.keys())
     enum = J.get_enumeration_wrapper(d.keys())
     for i in range(d.size()):
         key = J.to_string(enum.nextElement())
         self.assertEqual(key, keys[i])
Ejemplo n.º 43
0
def get_bit_data(img):
    '''Get the pixel data from a binary mask
    
    returns a Numpy array of boolean type
    '''
    interval = wrap_interval(img)
    dims = interval.dimensions()
    #
    # Make a Java boolean array
    #
    a = np.zeros(np.prod(dims), np.float64)
    ja = J.get_env().make_boolean_array(np.ascontiguousarray(a))
    strides = np.cumprod([1] + dims[:0:-1]).astype(int)[::-1]
    J.static_call("net/imglib2/util/ImgUtil", "copy", 
                  "(Lnet/imglib2/img/Img;[ZI[I)V",
                  img, ja, 0, strides)
    a = J.get_env().get_boolean_array_elements(ja)
    a.shape = dims
    return a
Ejemplo n.º 44
0
def create_overlay(context, mask):
    """Create a bitmask overlay from a numpy boolean array
    
    mask - boolean numpy array organized as i,j = y,x
    """
    assert mask.ndim == 2
    mask = mask.transpose()
    strides = np.array([mask.shape[1], 1], int)
    img = make_bit_img(mask.shape)

    J.static_call("net/imglib2/util/ImgUtil", "copy", "([ZI[ILnet/imglib2/img/Img;)V", mask.flatten(), 0, strides, img)
    roi = J.make_instance("net/imglib2/roi/BinaryMaskRegionOfInterest", "(Lnet/imglib2/img/Img;)V", img)
    overlay = J.make_instance(
        "imagej/data/overlay/BinaryMaskOverlay",
        "(Lorg/scijava/Context;Lnet/imglib2/roi/BinaryMaskRegionOfInterest;)V",
        context.getContext(),
        roi,
    )
    return overlay
Ejemplo n.º 45
0
def getGrayColorSpace():
    '''Get a Java object that represents an RGB color space
    
    See java.awt.color.ColorSpace: this returns the linear RGB color space
    '''
    cs_gray = jutil.get_static_field('java/awt/color/ColorSpace',
                                           'CS_GRAY', 'I')
    return jutil.static_call('java/awt/color/ColorSpace', 'getInstance',
                             '(I)Ljava/awt/color/ColorSpace;',
                             cs_gray)
Ejemplo n.º 46
0
def create_overlay(context, mask):
    '''Create a bitmask overlay from a numpy boolean array
    
    mask - boolean numpy array organized as i,j = y,x
    '''
    assert mask.ndim == 2
    mask = mask.transpose()
    strides = np.array([mask.shape[1], 1], int)
    img = make_bit_img(mask.shape)

    J.static_call("net/imglib2/util/ImgUtil", "copy",
                  "([ZI[ILnet/imglib2/img/Img;)V", mask.flatten(), 0, strides,
                  img)
    roi = J.make_instance("net/imglib2/roi/BinaryMaskRegionOfInterest",
                          "(Lnet/imglib2/img/Img;)V", img)
    overlay = J.make_instance(
        "imagej/data/overlay/BinaryMaskOverlay",
        "(Lorg/scijava/Context;Lnet/imglib2/roi/BinaryMaskRegionOfInterest;)V",
        context.getContext(), roi)
    return overlay
Ejemplo n.º 47
0
 def test_01_06_get_enumeration_wrapper(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     keys = J.call(properties, "keys", "()Ljava/util/Enumeration;")
     enum = J.get_enumeration_wrapper(keys)
     has_java_vm_name = False
     while (enum.hasMoreElements()):
         key = J.to_string(enum.nextElement())
         if key == "java.vm.name":
             has_java_vm_name = True
     self.assertTrue(has_java_vm_name)
Ejemplo n.º 48
0
 def test_01_06_get_enumeration_wrapper(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     keys = J.call(properties, "keys", "()Ljava/util/Enumeration;")
     enum = J.get_enumeration_wrapper(keys)
     has_java_vm_name = False
     while(enum.hasMoreElements()):
         key = J.to_string(enum.nextElement())
         if key == "java.vm.name":
             has_java_vm_name = True
     self.assertTrue(has_java_vm_name)
Ejemplo n.º 49
0
def get_output_fields_and_parameters(plugin):
    '''Get the output parameters from a plugin
    
    plugin - a Runnable plugin with @parameter annotations
    
    returns a dictionary of field name and wrapped parameter
    '''
    parameters = J.static_call(
        PARAMETER_HANDLER_CLASS, 'getOutputParameters',
        '(L%(RUNNABLE_CLASS)s;)L%(ITERABLE_CLASS)s;' % globals(), plugin)
    return get_fields_and_parameters_from_iterator(parameters)
Ejemplo n.º 50
0
def get_output_fields_and_parameters(plugin):
    '''Get the output parameters from a plugin
    
    plugin - a Runnable plugin with @parameter annotations
    
    returns a dictionary of field name and wrapped parameter
    '''
    parameters = J.static_call(PARAMETER_HANDLER_CLASS,
                               'getOutputParameters',
                               '(L%(RUNNABLE_CLASS)s;)L%(ITERABLE_CLASS)s;' %
                               globals(), plugin)
    return get_fields_and_parameters_from_iterator(parameters)
Ejemplo n.º 51
0
 def fn():
     hashtable = J.static_call('ij/Menus', 'getCommands',
                               '()Ljava/util/Hashtable;')
     if hashtable is None:
         #
         # This is a little bogus, but works - trick IJ into initializing
         #
         execute_command("pleaseignorethis")
         hashtable = J.static_call('ij/Menus', 'getCommands',
                                   '()Ljava/util/Hashtable;')
         if hashtable is None:
             return []
     keys = J.call(hashtable, "keys", "()Ljava/util/Enumeration;")
     keys = J.jenumeration_to_string_list(keys)
     values = J.call(hashtable, "values", "()Ljava/util/Collection;")
     values = [J.to_string(x) for x in J.iterate_java(
         J.call(values, 'iterator', "()Ljava/util/Iterator;"))]
     class CommandList(list):
         def __init__(self):
             super(CommandList, self).__init__(keys)
             self.values = values
     return CommandList()
Ejemplo n.º 52
0
def create_mask(display):
    '''Create a binary mask from a sequence of overlays
    
    display - an image display
    
    returns a binary mask
    '''
    jmask = J.static_call(
        "org/cellprofiler/ijutils/OverlayUtils", "extractMask",
        "(Limagej/data/display/ImageDisplay;)Lnet/imglib2/img/Img;", display.o)
    if jmask is None:
        return None
    return get_bit_data(jmask)
Ejemplo n.º 53
0
def create_mask(display):
    '''Create a binary mask from a sequence of overlays
    
    display - an image display
    
    returns a binary mask
    '''
    jmask = J.static_call(
        "org/cellprofiler/ijutils/OverlayUtils",
        "extractMask",
        "(Limagej/data/display/ImageDisplay;)Lnet/imglib2/img/Img;",
        display.o)
    if jmask is None:
        return None
    return get_bit_data(jmask)
Ejemplo n.º 54
0
 def setPixelsDimensionOrder(self, dimension_order, imageIndex, binDataIndex):
     '''Set the dimension order for a series'''
     # Post loci_tools 4.2 - use ome.xml.model.DimensionOrder
     try:
         jdimension_order = jutil.static_call(
             'ome/xml/model/enums/DimensionOrder', 'fromString',
             '(Ljava/lang/String;)Lome/xml/model/enums/DimensionOrder;',
             dimension_order)
         jutil.call(self.o, 'setPixelsDimensionOrder',
                    '(Lome/xml/model/enums/DimensionOrder;I)V',
                    jdimension_order, imageIndex)
     except jutil.JavaException:
         jutil.call(self.o, 'setPixelsDimensionOrder',
                    '(Ljava/lang/String;II)V',
                    dimension_order, imageIndex, binDataIndex)
Ejemplo n.º 55
0
 def run(self,
         module,
         pre=None,
         post=None,
         separateThread=False,
         **kwargs):
     '''Run a module
     
     module - the module to run
     
     pre - list of PreprocessorPlugins to run before running module
     
     post - list of PostprocessorPlugins to run after running module
     
     *kwargs - names and values for input parameters
     '''
     input_map = J.get_dictionary_wrapper(
         J.make_instance('java/util/HashMap', '()V'))
     for k, v in kwargs.iteritems():
         input_map.put(k, v)
     if pre is not None:
         pre = J.static_call("java/util/Arrays", "asList",
                             "([Ljava/lang/Object;)Ljava/util/List;",
                             pre)
     if post is not None:
         post = J.static_call("java/util/Arrays", "asList",
                              "([Ljava/lang/Object;)Ljava/util/List;",
                              post)
     future = J.call(
         self.o, "run",
         "(Limagej/ext/module/Module;Ljava/util/List;Ljava/util/List;Ljava/util/Map;)Ljava/util/concurrent/Future;",
         module, pre, post, input_map)
     return J.call(
         self.o, "waitFor",
         "(Ljava/util/concurrent/Future;)Limagej/ext/module/Module;",
         future)
Ejemplo n.º 56
0
 def setPixelsDimensionOrder(self, dimension_order, imageIndex,
                             binDataIndex):
     '''Set the dimension order for a series'''
     # Post loci_tools 4.2 - use ome.xml.model.DimensionOrder
     try:
         jdimension_order = jutil.static_call(
             'ome/xml/model/enums/DimensionOrder', 'fromString',
             '(Ljava/lang/String;)Lome/xml/model/enums/DimensionOrder;',
             dimension_order)
         jutil.call(self.o, 'setPixelsDimensionOrder',
                    '(Lome/xml/model/enums/DimensionOrder;I)V',
                    jdimension_order, imageIndex)
     except jutil.JavaException:
         jutil.call(self.o, 'setPixelsDimensionOrder',
                    '(Ljava/lang/String;II)V', dimension_order, imageIndex,
                    binDataIndex)
Ejemplo n.º 57
0
 def test_01_07_get_dictionary_wrapper(self):
     properties = J.static_call("java/lang/System", "getProperties",
                                "()Ljava/util/Properties;")
     d = J.get_dictionary_wrapper(properties)
     self.assertTrue(d.size() > 10)
     self.assertFalse(d.isEmpty())
     keys = J.get_enumeration_wrapper(d.keys())
     values = J.get_enumeration_wrapper(d.elements())
     n_elems = d.size()
     for i in range(n_elems):
         self.assertTrue(keys.hasMoreElements())
         key = J.to_string(keys.nextElement())
         self.assertTrue(values.hasMoreElements())
         value = J.to_string(values.nextElement())
         self.assertEqual(J.to_string(d.get(key)), value)
     self.assertFalse(keys.hasMoreElements())
     self.assertFalse(values.hasMoreElements())
Ejemplo n.º 58
0
 def tearDownClass(cls):
     del cls.context
     J.static_call('java/lang/System', 'gc', '()V')
Ejemplo n.º 59
0
def start_cellprofiler_jvm():
    '''Start the Java VM with arguments appropriate for CellProfiler'''
    global logger

    if hasattr(sys, 'frozen'):
        if sys.platform != 'darwin':
            root_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
            bioformats_path = os.path.join(root_path, 'bioformats')
        else:
            bioformats_path = os.path.abspath(os.path.split(__file__)[0])
            root_path = os.path.split(bioformats_path)[0]
        imagej_path = os.path.join(root_path, 'imagej', 'jars')

        def sort_fn(a, b):
            aa, bb = [(0 if x.startswith("cellprofiler-java") else 1, x)
                      for x in a, b]
            return cmp(aa, bb)

        jar_files = [
            jar_filename for jar_filename in os.listdir(imagej_path)
            if jar_filename.lower().endswith(".jar")
        ]
        jar_files = sorted(jar_files, cmp=sort_fn)
    else:
        bioformats_path = os.path.abspath(os.path.split(__file__)[0])
        root_path = os.path.split(bioformats_path)[0]
        jar_files = get_cellprofiler_jars()
        imagej_path = os.path.join(root_path, 'imagej', 'jars')

    class_path = os.pathsep.join(
        [os.path.join(imagej_path, jar_file) for jar_file in jar_files])

    if os.environ.has_key("CLASSPATH"):
        class_path += os.pathsep + os.environ["CLASSPATH"]

    if (get_ij_plugin_directory() is not None
            and os.path.isdir(get_ij_plugin_directory())):
        plugin_directory = get_ij_plugin_directory()
        #
        # Add the plugin directory to pick up .class files in a directory
        # hierarchy.
        #
        class_path += os.pathsep + plugin_directory
        #
        # Add any .jar files in the directory
        #
        class_path += os.pathsep + os.pathsep.join([
            os.path.join(plugin_directory, jarfile)
            for jarfile in os.listdir(plugin_directory)
            if jarfile.lower().endswith(".jar")
        ])

    if sys.platform.startswith("win") and not hasattr(sys, 'frozen'):
        # Have to find tools.jar
        from cellprofiler.utilities.setup import find_jdk
        jdk_path = find_jdk()
        if jdk_path is not None:
            tools_jar = os.path.join(jdk_path, "lib", "tools.jar")
            class_path += os.pathsep + tools_jar
        else:
            logger.warning("Failed to find tools.jar")

    jvm_arg = [
        x.groups()[0] for x in
        [re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv]
        if x is not None
    ]
    if len(jvm_arg) > 0:
        jvm_arg = jvm_arg[0]
    else:
        jvm_arg = "512m"

    args = [
        r"-Djava.class.path=" + class_path,
        r"-Dloci.bioformats.loaded=true",
        #r"-verbose:class",
        #r"-verbose:jni",
        r"-Xmx%s" % jvm_arg
    ]
    #
    # Get the log4j logger setup from a file in the bioformats directory
    # if such a file exists.
    #
    log4j_properties = os.path.join(bioformats_path, "log4j.properties")
    if os.path.exists(log4j_properties):
        log4j_properties = "file:/" + log4j_properties.replace(
            os.path.sep, "/")
        args += [r"-Dlog4j.configuration=" + log4j_properties]
        init_logger = False
    else:
        init_logger = True

    if get_headless():
        # We're running silently, so don't change the Java preferences
        # The following definition uses a process-scope preferences factory
        args += [
            "-Djava.util.prefs.PreferencesFactory="
            "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"
        ]
    run_headless = (get_headless()
                    and not os.environ.has_key("CELLPROFILER_USE_XVFB"))
    run_headless = False

    logger.debug("JVM arguments: " + " ".join(args))
    jutil.start_vm(args, run_headless)
    logger.debug("Java virtual machine started.")
    jutil.attach()
    try:
        jutil.static_call("loci/common/Location", "cacheDirectoryListings",
                          "(Z)V", True)
    except:
        logger.warning(
            "Bioformats version does not support directory cacheing")

    #
    # Start the log4j logger to avoid error messages.
    #
    if init_logger:
        try:
            jutil.static_call("org/apache/log4j/BasicConfigurator",
                              "configure", "()V")
            log4j_logger = jutil.static_call("org/apache/log4j/Logger",
                                             "getRootLogger",
                                             "()Lorg/apache/log4j/Logger;")
            warn_level = jutil.get_static_field("org/apache/log4j/Level",
                                                "WARN",
                                                "Lorg/apache/log4j/Level;")
            jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V",
                       warn_level)
            del logger
            del warn_level
        except:
            logger.error("Failed to initialize log4j\n", exc_info=True)
    if not get_headless():
        jutil.activate_awt()
Ejemplo n.º 60
0
def run_imagej(*args):
    J.static_call("imagej/Main", "main", "([Ljava/lang/String;)V",
                  *[unicode(arg) for arg in args])