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)
def getModules(self): modules = J.call(o, "getModules", "()Ljava/util/List;") if modules is None: return [] module_iterator = J.call(modules, "iterator", "()Ljava/util/Iterator;") return [ModuleInfo(x) for x in J.iterate_java(module_iterator)]
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()
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")
def getModules(self): modules = J.call(o, "getModules", "()Ljava/util/List;") if modules is None: return [] module_iterator = J.call(modules, "iterator", "()Ljava/util/Iterator;") return [wrap_module_info(x) for x in J.iterate_java(module_iterator)]
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)
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)
def get_commands(): """Return a list of the available command strings""" script = """ new java.util.concurrent.Callable() { call: function() { importClass(Packages.ij.Menus, Packages.ij.IJ); var hashtable=Menus.getCommands(); if (hashtable==null) { IJ.run("pleaseignorethis"); hashtable = Menus.getCommands(); } return hashtable; } }; """ c = J.run_script(script, class_loader=get_user_loader()) hashtable = J.execute_callable_in_main_thread(c) 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()
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)
def setPixelsSizeX(self, x, imageIndex, binDataIndex): try: jutil.call(self.o, 'setPixelsSizeX', '(Lome/xml/model/primitives/PositiveInteger;I)V', PositiveInteger(x), imageIndex) except jutil.JavaException: jutil.call(self.o, 'setPixelsSizeX', '(Ljava/lang/Integer;II)V', x, imageIndex, binDataIndex)
def getIndex(self): index = J.call(self.o, "getIndex", "()Limagej/module/ModuleIndex;") index = J.get_collection_wrapper(index, wrap_module_info) index.getC = lambda c: J.get_collection_wrapper( J.call(index.o, "get", "(Ljava/lang/Class;)Ljava/util/List;", c), wrap_module_info ) index.getS = lambda class_name: index.getC(J.class_for_name(class_name)) return index
def setPixelsSizeY(self, y, imageIndex, binDataIndex): try: jutil.call(self.o, 'setPixelsSizeY', '(Lome/xml/model/primitives/PositiveInteger;I)V', PositiveInteger(y), imageIndex) except jutil.JavaException: jutil.call(self.o, 'setPixelsSizeY', '(Ljava/lang/Integer;II)V', y, imageIndex, binDataIndex)
def getIndex(self): index = J.call(self.o, "getIndex", "()Limagej/module/ModuleIndex;") index = J.get_collection_wrapper(index, wrap_module_info) index.getC = lambda c: J.get_collection_wrapper( J.call(index.o, "get", "(Ljava/lang/Class;)Ljava/util/List;", c ), wrap_module_info) index.getS = lambda class_name: \ index.getC(J.class_for_name(class_name)) return index
def getType(self): jtype = J.call(self.o, "getType", "()Ljava/lang/Class;") type_name = J.call(jtype, "getCanonicalName", "()Ljava/lang/String;") if field_mapping.has_key(type_name): return field_mapping[type_name] for class_instance, result in field_class_mapping(): if J.call(class_instance, "isAssignableFrom", "(Ljava/lang/Class;)Z", jtype): return result return None
def loadService(self, class_name): '''Load the service class with the given class name You can use this method to pick specific implementations such as the headless or Swing UI. class_name - class name in dotted form, e.g. java.lang.String ''' klass = J.class_for_name(class_name) J.call(self.o, 'loadService', '(Ljava/lang/Class;)V', klass)
def test_03_09_cw_get_method(self): sclass = J.class_for_name('java.lang.String') iclass = J.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = J.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [ iclass ]) self.assertEqual(J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [ sclass]) self.assertEqual(J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
def setLogicalChannelSamplesPerPixel(self, samplesPerPixel, imageIndex, channelIndex): 'For a particular LogicalChannel, sets number of channel components in the logical channel.' try: jutil.call(self.o, 'setChannelSamplesPerPixel', '(Lome/xml/model/primitives/PositiveInteger;II)V', PositiveInteger(samplesPerPixel), imageIndex, channelIndex) except jutil.JavaException: jutil.call(self.o, 'setLogicalChannelSamplesPerPixel', '(Ljava/lang/Integer;II)V', samplesPerPixel, imageIndex, channelIndex)
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")
def getActiveDisplay(self, klass=None): """Get the first display, optionally of the given type from the list klass - if not None, return the first display of this type, otherwise return the first display """ if klass is None: return wrap_display(J.call(self.o, "getActiveDisplay", "()Limagej/display/Display;")) else: return wrap_display( J.call(self.o, "getActiveDisplay", "(Ljava/lang/Class;)Limagej/display/Display;", klass) )
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")
def test_03_09_cw_get_method(self): sclass = J.class_for_name('java.lang.String') iclass = J.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = J.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [iclass]) self.assertEqual( J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [sclass]) self.assertEqual( J.to_string(J.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
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)
def test_08_01_create_overlay(self): r = np.random.RandomState() r.seed(81) mask = r.uniform(size=(23,10)) > .5 overlay = ij2.create_overlay(self.context, mask) roi = J.call(overlay, "getRegionOfInterest", "()Lnet/imglib2/roi/RegionOfInterest;") i = r.randint(0, 23, 10) j = r.randint(0, 10, 10) for ii, jj in zip(i, j): location = np.array([jj, ii], float) test = J.call(roi, "contains", "([D)Z", location) self.assertEqual(mask[ii, jj], test)
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);
def getActiveDisplay(self, klass=None): '''Get the first display, optionally of the given type from the list klass - if not None, return the first display of this type, otherwise return the first display ''' if klass is None: return wrap_display(J.call( self.o, "getActiveDisplay", "()Limagej/display/Display;")) else: return wrap_display(J.call( self.o, "getActiveDisplay", "(Ljava/lang/Class;)Limagej/display/Display;", klass))
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)
def setPixelsBigEndian(self, bigEndian, imageIndex, binDataIndex): '''Set the endianness for a particular image bigEndian - True for big-endian, False for little-endian imageIndex - index of the image in question from IFormatReader.get_index? binDataIndex - ??? ''' # Post loci_tools 4.2 try: jutil.call(self.o, 'setPixelsBinDataBigEndian', '(Ljava/lang/Boolean;II)V', bigEndian, imageIndex, binDataIndex) except jutil.JavaException: jutil.call(self.o, 'setPixelsBigEndian', '(Ljava/lang/Boolean;II)V', bigEndian, imageIndex, binDataIndex)
def test_03_11_cw_get_constructor(self): c = J.get_class_wrapper('java.lang.String') sclass = J.class_for_name('java.lang.String') constructor = c.getConstructor([sclass]) self.assertEqual( J.call(constructor, 'getName', '()Ljava/lang/String;'), 'java.lang.String')
def test_03_08_cw_get_field(self): c = J.get_class_wrapper('java.lang.String') field = c.getField('CASE_INSENSITIVE_ORDER') modifiers = J.call(field, 'getModifiers', '()I') static = J.get_static_field('java/lang/reflect/Modifier', 'STATIC', 'I') self.assertEqual((modifiers & static), static)
def test_03_07_cw_get_fields(self): c = J.get_class_wrapper('java.lang.String') fields = c.getFields() fields = J.get_env().get_object_array_elements(fields) self.assertEqual(len(fields), 1) self.assertEqual(J.call(fields[0], 'getName', '()Ljava/lang/String;'), "CASE_INSENSITIVE_ORDER")
def prepare_run(self, workspace): """Create an IPD for every url that passes the filter""" if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls ) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call(iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) file_list = [f for f, passes in zip(file_list, passes_filter) if passes] workspace.pipeline.set_filtered_file_list(file_list, self) return True
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
def prepare_run(self, workspace): '''Create an IPD for every url that passes the filter''' if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call(iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) file_list = [ f for f, passes in zip(file_list, passes_filter) if passes ] workspace.pipeline.set_filtered_file_list(file_list, self) return True
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
def test_10_08_eval_with_bindings(self): svc = ij2.get_script_service(self.context) factory = svc.getByName("ECMAScript") engine = factory.getScriptEngine() engine.put("a", 2) engine.evalS("var b = a+a;") self.assertEqual(J.call(engine.get("b"), "intValue", "()I"), 4)
def createDisplay(self, dataset): '''Create a display that contains the given dataset''' display = J.call( self.o, "createDisplay", "(Limagej/data/Dataset;)Limagej/display/ImageDisplay;", dataset.o) return wrap_display(display)
def test_03_10_cw_get_methods(self): c = J.get_class_wrapper('java.lang.String') mmm = J.get_env().get_object_array_elements(c.getMethods()) self.assertTrue( any([ J.call(m, 'getName', '()Ljava/lang/String;') == 'concat' for m in mmm ]))
def getService(self, class_name): """Get a service with the given class name class_name - class name in dotted form returns the class or None if no implementor loaded. """ klass = J.class_for_name(class_name) return J.call(self.o, "get", "(Ljava/lang/Class;)Lorg/scijava/service/Service;", klass)
def createDisplay(self, name, dataset): '''Create a display that contains the given dataset''' display = J.call( self.o, "createDisplay", "(Ljava/lang/String;Ljava/lang/Object;)Limagej/display/Display;", name, dataset.o) return wrap_display(display)
def getService(self, class_name): '''Get a service with the given class name class_name - class name in dotted form returns the class or None if no implementor loaded. ''' klass = J.class_for_name(class_name) return J.call(self.o, 'getService', '(Ljava/lang/Class;)Limagej/IService;', klass)
def getActiveImageDisplay(self): """Get the active imagej.data.display.ImageDisplay""" return wrap_display( J.call( self.o, "getActiveDisplay", "()Limagej/display/Display;", J.class_for_name("imagej.data.display.ImageDisplay"), ) )
def getService(self, class_name): '''Get a service with the given class name class_name - class name in dotted form returns the class or None if no implementor loaded. ''' klass = J.class_for_name(class_name) return J.call(self.o, 'getService', '(Ljava/lang/Class;)Limagej/service/Service;', klass)
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)
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)
def get_fields_and_parameters_from_iterator(parameters): iterator = J.call(parameters, 'iterator', '()L%(ITERATOR_CLASS)s;' % globals()) result = [] for jfield in J.iterate_java(iterator): field = J.get_field_wrapper(jfield) parameter = field.getAnnotation(PARAMETER_CLASS.replace('/','.')) if parameter is not None: parameter = get_parameter_wrapper(parameter) result.append((field, parameter)) return result
def get_image(imageprocessor_obj, do_scaling=False): """Retrieve the image from an ImageProcessor Returns the image as a numpy float array. """ # # The strategy is: # * Make a TypeConverter # * Ask the TypeConverter for a float ImageProcessor # * Get the pixels - should be a float array # type_converter = J.make_instance( "ij/process/TypeConverter", "(Lij/process/ImageProcessor;Z)V", imageprocessor_obj, do_scaling ) float_processor = J.call(type_converter, "convertToFloat", "([F)Lij/process/ImageProcessor;", None) jpixels = J.call(float_processor, "getPixels", "()Ljava/lang/Object;") pixels = J.get_env().get_float_array_elements(jpixels) height = J.call(imageprocessor_obj, "getHeight", "()I") width = J.call(imageprocessor_obj, "getWidth", "()I") pixels.shape = (height, width) return pixels
def get_fields_and_parameters_from_iterator(parameters): iterator = J.call(parameters, 'iterator', '()L%(ITERATOR_CLASS)s;' % globals()) result = [] for jfield in J.iterate_java(iterator): field = J.get_field_wrapper(jfield) parameter = field.getAnnotation(PARAMETER_CLASS.replace('/', '.')) if parameter is not None: parameter = get_parameter_wrapper(parameter) result.append((field, parameter)) return result
def make_bit_img(shape): '''Make an imglib img of BitType with the given shape shape - a sequence of image dimensions ''' 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(shape), bit_type) return img
def select_overlay(display, overlay, select=True): '''Select or deselect an overlay display - the overlay's display overlay - the overlay to select ''' for view in J.get_collection_wrapper(display, fn_wrapper=wrap_data_view): if J.call(overlay, "equals", "(Ljava/lang/Object;)Z", view.getData()): view.setSelected(select) break else: logger.info("Failed to select overlay")