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 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 create_planar_img(a): '''Create a PlanarImg from a numpy array a - numpy array. The values should be scaled to be between 0 and 255 returns a PlanarImg of double valueswith the same dimensions as the array. ''' a = a.astype(np.float64) creator = J.make_instance("net/imglib2/img/basictypeaccess/array/DoubleArray", "(I)V", 0) planar_img = J.make_instance( "net/imglib2/img/planar/PlanarImg", "(Lnet/imglib2/img/basictypeaccess/array/ArrayDataAccess;[JI)V", creator, np.array(a.shape), 1) 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) a.shape = (a.shape[0], a.shape[1], np.prod(a.shape[2:])) for i in range(a.shape[2]): copy_plane(i, a[:,:,i]) return planar_img
def create_planar_img(a): '''Create a PlanarImg from a numpy array a - numpy array. The values should be scaled to be between 0 and 255 returns a PlanarImg of double valueswith the same dimensions as the array. ''' a = a.astype(np.float64) creator = J.make_instance( "net/imglib2/img/basictypeaccess/array/DoubleArray", "(I)V", 0) planar_img = J.make_instance( "net/imglib2/img/planar/PlanarImg", "(Lnet/imglib2/img/basictypeaccess/array/ArrayDataAccess;[JI)V", creator, np.array(a.shape), 1) 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) a.shape = (a.shape[0], a.shape[1], np.prod(a.shape[2:])) for i in range(a.shape[2]): copy_plane(i, a[:, :, i]) return planar_img
def test_08_09_removeAll(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c2.add("Foo") c1.removeAll(c2) self.assertNotIn("Foo", c1)
def test_08_04_addAll(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2.addAll(c1.o) self.assertIn("Foo", c2)
def test_08_07_contains_all(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") self.assertFalse(c2.containsAll(c1.o)) c2 += c1 self.assertTrue(c2.containsAll(c1.o))
def test_08_09_removeAll(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c2.add("Foo") c1.removeAll(c2) self.assertNotIn("Foo", c1)
def test_08_04_addAll(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2.addAll(c1.o) self.assertIn("Foo", c2)
def test_08_07_contains_all(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") self.assertFalse(c2.containsAll(c1.o)) c2 += c1 self.assertTrue(c2.containsAll(c1.o))
def test_08_06__iadd__(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2 += c1 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c2) c2 += ["Hello", "World"] self.assertIn("Hello", c2) self.assertIn("World", c2)
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 test_08_05__add__(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c3 = c1 + c2 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c3) c4 = c3 + ["Hello", "World"] self.assertIn("Hello", c4) self.assertIn("World", c4)
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 test_08_06__iadd__(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2 += c1 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c2) c2 += ["Hello", "World"] self.assertIn("Hello", c2) self.assertIn("World", c2)
def test_08_05__add__(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c3 = c1 + c2 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c3) c4 = c3 + ["Hello", "World"] self.assertIn("Hello", c4) self.assertIn("World", c4)
def test_08_11_toArray(self): c1 = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") result = [J.to_string(x) for x in c1.toArray()] self.assertIn("Foo", result) self.assertIn("Bar", result)
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 __init__(self): env = jutil.get_env() class_name = 'loci/formats/ImageReader' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatReader') self.o = jutil.make_instance("loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "readers.txt", base_klass, klass) problem_classes = [ # BDReader will read all .tif files in an experiment if it's # called to load a .tif. # 'loci.formats.in.BDReader', # # MRCReader will read .stk files which should be read # by MetamorphReader # 'loci.formats.in.MRCReader' ] for problem_class in problem_classes: # Move to back klass = jutil.class_for_name(problem_class) self.remove_class(klass) self.add_class(klass)
def PositiveInteger(some_number): '''Return an instance of ome.xml.model.primitives.PositiveInteger some_number - the number to be wrapped up in the class ''' return jutil.make_instance('ome/xml/model/primitives/PositiveInteger', '(Ljava/lang/Integer;)V', some_number)
def test_08_03_contains(self): c = J.get_collection_wrapper(J.make_instance("java/util/HashSet", "()V")) c.add("Foo") self.assertTrue(c.contains("Foo")) self.assertFalse(c.contains("Bar")) self.assertIn("Foo", c) self.assertNotIn("Bar", c)
def test_08_01_wrap_collection(self): c = J.make_instance("java/util/HashSet", "()V") w = J.get_collection_wrapper(c) self.assertFalse(hasattr(w, "addI")) self.assertEqual(w.size(), 0) self.assertEqual(len(w), 0) self.assertTrue(w.isEmpty())
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 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 getColorModel(color_space, has_alpha=False, is_alpha_premultiplied = False, transparency = OPAQUE, transfer_type = TYPE_BYTE): '''Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT ''' jtransparency = jutil.get_static_field('java/awt/Transparency', transparency, 'I') jtransfer_type = jutil.get_static_field('java/awt/image/DataBuffer', transfer_type, 'I') return jutil.make_instance('java/awt/image/ComponentColorModel', '(Ljava/awt/color/ColorSpace;ZZII)V', color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type)
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 getColorModel( color_space, has_alpha=False, is_alpha_premultiplied=False, transparency=OPAQUE, transfer_type=TYPE_BYTE ): """Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT """ jtransparency = jutil.get_static_field("java/awt/Transparency", transparency, "I") jtransfer_type = jutil.get_static_field("java/awt/image/DataBuffer", transfer_type, "I") return jutil.make_instance( "java/awt/image/ComponentColorModel", "(Ljava/awt/color/ColorSpace;ZZII)V", color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type, )
def make_image_processor(array): """Create an image processor from the given image array - an array that will be cast to double. Values should be between 0 and 255 """ return J.make_instance("ij/process/FloatProcessor", "(II[D)V", array.shape[1], array.shape[0], array)
def allowOpenToCheckType(self, allow): '''Allow the "isThisType" function to open files For the cluster, you want to tell potential file formats not to open the image file to test if it's their format. ''' if not hasattr(self, "allowOpenToCheckType_method"): self.allowOpenToCheckType_method = None class_wrapper = jutil.get_class_wrapper(self.o) methods = class_wrapper.getMethods() for method in jutil.get_env().get_object_array_elements( methods): m = jutil.get_method_wrapper(method) if m.getName() in ('allowOpenToCheckType', 'setAllowOpenFiles'): self.allowOpenToCheckType_method = m if self.allowOpenToCheckType_method is not None: object_class = env.find_class('java/lang/Object') jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) boolean_value = jutil.make_instance('java/lang/Boolean', '(Z)V', allow) args = jutil.get_env().make_object_array(1, object_class) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) jutil.get_env().set_object_array_element( args, 0, boolean_value) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) self.allowOpenToCheckType_method.invoke(self.o, args)
def __init__(self): env = jutil.get_env() class_name = 'loci/formats/ImageReader' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatReader') self.o = jutil.make_instance( "loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "readers.txt", base_klass, klass) problem_classes = [ # BDReader will read all .tif files in an experiment if it's # called to load a .tif. # 'loci.formats.in.BDReader', # # MRCReader will read .stk files which should be read # by MetamorphReader # 'loci.formats.in.MRCReader' ] for problem_class in problem_classes: # Move to back klass = jutil.class_for_name(problem_class) self.remove_class(klass) self.add_class(klass)
def allowOpenToCheckType(self, allow): '''Allow the "isThisType" function to open files For the cluster, you want to tell potential file formats not to open the image file to test if it's their format. ''' if not hasattr(self, "allowOpenToCheckType_method"): self.allowOpenToCheckType_method = None class_wrapper = jutil.get_class_wrapper(self.o) methods = class_wrapper.getMethods() for method in jutil.get_env().get_object_array_elements(methods): m = jutil.get_method_wrapper(method) if m.getName() in ('allowOpenToCheckType', 'setAllowOpenFiles'): self.allowOpenToCheckType_method = m if self.allowOpenToCheckType_method is not None: object_class = env.find_class('java/lang/Object') jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) boolean_value = jutil.make_instance('java/lang/Boolean', '(Z)V', allow) args = jutil.get_env().make_object_array(1, object_class) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) jutil.get_env().set_object_array_element(args, 0, boolean_value) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) self.allowOpenToCheckType_method.invoke(self.o, args)
def test_08_03_contains(self): c = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c.add("Foo") self.assertTrue(c.contains("Foo")) self.assertFalse(c.contains("Bar")) self.assertIn("Foo", c) self.assertNotIn("Bar", c)
def test_08_11_toArray(self): c1 = J.get_collection_wrapper( J.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") result = [J.to_string(x) for x in c1.toArray()] self.assertIn("Foo", result) self.assertIn("Bar", result)
def make_image_processor(array): '''Create an image processor from the given image array - an array that will be cast to double. Values should be between 0 and 255 ''' return J.make_instance('ij/process/FloatProcessor', '(II[D)V', array.shape[1], array.shape[0], array)
def make_image_processor(array): '''Create an image processor from the given image array - an array that will be cast to double. Values should be between 0 and 255 ''' return J.make_instance( 'ij/process/FloatProcessor', '(II[D)V', array.shape[1], array.shape[0], array)
def make_imageplus_from_processor(title, processor): """Make an ImagePlus object from an ImageProcessor object title - the window title for the ImagePlus object processor - the ImageProcessor instance """ imageplus_obj = J.make_instance( "ij/ImagePlus", "(Ljava/lang/String;Lij/process/ImageProcessor;)V", title, processor ) return get_imageplus_wrapper(imageplus_obj)
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
def make_imageplus_from_processor(title, processor): '''Make an ImagePlus object from an ImageProcessor object title - the window title for the ImagePlus object processor - the ImageProcessor instance ''' imageplus_obj = J.make_instance( 'ij/ImagePlus', '(Ljava/lang/String;Lij/process/ImageProcessor;)V', title, processor) return get_imageplus_wrapper(imageplus_obj)
def __init__(self, path): self.stream = None if path.lower().startswith("omero:"): self.rdr = get_omero_reader() return self.rdr = None class_list = get_class_list() find_rdr_script = """ var classes = class_list.getClasses(); var rdr = null; var lc_filename = java.lang.String(filename.toLowerCase()); for (pass=0; pass < 3; pass++) { for (class_idx in classes) { var maybe_rdr = classes[class_idx].newInstance(); if (pass == 0) { if (maybe_rdr.isThisType(filename, false)) { rdr = maybe_rdr; break; } continue; } else if (pass == 1) { var suffixes = maybe_rdr.getSuffixes(); var suffix_found = false; for (suffix_idx in suffixes) { var suffix = java.lang.String(suffixes[suffix_idx]); suffix = suffix.toLowerCase(); if (lc_filename.endsWith(suffix)) { suffix_found = true; break; } } if (! suffix_found) continue; } if (maybe_rdr.isThisType(stream)) { rdr = maybe_rdr; break; } } if (rdr) break; } rdr; """ self.stream = jutil.make_instance( 'loci/common/RandomAccessInputStream', '(Ljava/lang/String;)V', path) filename = os.path.split(path)[1] IFormatReader = make_iformat_reader_class() jrdr = jutil.run_script( find_rdr_script, dict(class_list=class_list, filename=filename, stream=self.stream)) if jrdr is None: raise ValueError("Could not find a Bio-Formats reader for %s", path) self.rdr = IFormatReader() self.rdr.o = jrdr
def get_metadata_options(level): '''Get an instance of the MetadataOptions interface level - MINIMUM, NO_OVERLAYS or ALL to set the metadata retrieval level The object returned can be used in setMetadataOptions in a format reader. ''' jlevel = jutil.get_static_field('loci/formats/in/MetadataLevel', level, 'Lloci/formats/in/MetadataLevel;') return jutil.make_instance('loci/formats/in/DefaultMetadataOptions', '(Lloci/formats/in/MetadataLevel;)V', jlevel)
def execute_macro(macro_text): '''Execute a macro in ImageJ macro_text - the macro program to be run ''' interp = J.make_instance("ij/macro/Interpreter","()V"); J.execute_runnable_in_main_thread(J.run_script( """new java.lang.Runnable() { run: function() { interp.run(macro_text); }}""", dict(interp=interp, macro_text=macro_text)), synchronous=True)
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
def __init__(self, path): self.stream = None if path.lower().startswith("omero:"): self.rdr = get_omero_reader() return self.rdr = None class_list = get_class_list() find_rdr_script = """ var classes = class_list.getClasses(); var rdr = null; var lc_filename = java.lang.String(filename.toLowerCase()); for (pass=0; pass < 3; pass++) { for (class_idx in classes) { var maybe_rdr = classes[class_idx].newInstance(); if (pass == 0) { if (maybe_rdr.isThisType(filename, false)) { rdr = maybe_rdr; break; } continue; } else if (pass == 1) { var suffixes = maybe_rdr.getSuffixes(); var suffix_found = false; for (suffix_idx in suffixes) { var suffix = java.lang.String(suffixes[suffix_idx]); suffix = suffix.toLowerCase(); if (lc_filename.endsWith(suffix)) { suffix_found = true; break; } } if (! suffix_found) continue; } if (maybe_rdr.isThisType(stream)) { rdr = maybe_rdr; break; } } if (rdr) break; } rdr; """ self.stream = jutil.make_instance('loci/common/RandomAccessInputStream', '(Ljava/lang/String;)V', path) filename = os.path.split(path)[1] IFormatReader = make_iformat_reader_class() jrdr = jutil.run_script(find_rdr_script, dict(class_list = class_list, filename = filename, stream = self.stream)) if jrdr is None: raise ValueError("Could not find a Bio-Formats reader for %s", path) self.rdr = IFormatReader() self.rdr.o = jrdr
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_02_03_death_and_resurrection(self): '''Put an object into another in Java, delete it in Python and recover it''' np.random.seed(24) my_value = np.random.randint(0, 1000) jobj = J.make_instance("java/lang/Integer", "(I)V", my_value) integer_klass = self.env.find_class("java/lang/Integer") jcontainer = self.env.make_object_array(1, integer_klass) self.env.set_object_array_element(jcontainer, 0, jobj) del jobj gc.collect() jobjs = self.env.get_object_array_elements(jcontainer) jobj = jobjs[0] self.assertEqual(J.call(jobj, "intValue", "()I"), my_value)
def test_03_02_command_service_run(self): svc = ij2.get_command_service(self.context) module_infos = ij2.get_module_service(self.context).getModules() for module_info in module_infos: if module_info.getClassName() == \ 'imagej.core.commands.display.ShowLUT': d = J.get_map_wrapper(J.make_instance('java/util/HashMap', '()V')) future = svc.run(module_info.o, d.o) module = future.get() module = ij2.wrap_module(module) module.getOutput('output') break else: raise AssertionError("Could not find target module")
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 make_image_writer_class(): '''Return an image writer class for the given Java environment''' env = jutil.get_env() class_name = 'loci/formats/ImageWriter' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatWriter') IFormatWriter = make_iformat_writer_class(class_name) # # This uses the writers.txt file from inside the loci_tools.jar # class_list = jutil.make_instance("loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "writers.txt", base_klass, klass) class ImageWriter(IFormatWriter): new_fn = jutil.make_new(class_name, '(Lloci/formats/ClassList;)V') def __init__(self): self.new_fn(class_list) setId = jutil.make_method('setId', '(Ljava/lang/String;)V', 'Sets the current file name.') addStatusListener = jutil.make_method('addStatusListener', '()Lloci/formats/StatusListener;', 'Adds a listener for status update events.') close = jutil.make_method('close','()V', 'Closes currently open file(s) and frees allocated memory.') getFormat = jutil.make_method('getFormat', '()Ljava/lang/String;', 'Gets the name of this file format.') getNativeDataType = jutil.make_method('getNativeDataType', '()Ljava/lang/Class;', 'Returns the native data type of image planes for this reader, as returned by IFormatReader.openPlane(int, int, int, int, int) or IFormatWriter#saveData.') getStatusListeners = jutil.make_method('getStatusListeners', '()[Lloci/formats/StatusListener;', 'Gets a list of all registered status update listeners.') getSuffixes = jutil.make_method('getSuffixes', '()Ljava/lang/String;', 'Gets the default file suffixes for this file format.') getWriter = jutil.make_method('getWriter', '()Lloci/formats/IFormatWriter;', 'Gets the writer used to save the current file.') # getWriter = jutil.make_method('getWriter', '(Ljava/lang/Class)Lloci/formats/IFormatWriter;', # 'Gets the file format writer instance matching the given class.') # getWriter = jutil.make_method('getWriter', '(Ljava/lang/String;)Lloci/formats/IFormatWriter;', # 'Gets the writer used to save the given file.') getWriters = jutil.make_method('getWriters', '()[Lloci/formats/IFormatWriter;', 'Gets all constituent file format writers.') isThisType = jutil.make_method('isThisType', '(Ljava/lang/String;)Z', 'Checks if the given string is a valid filename for this file format.') removeStatusListener = jutil.make_method('removeStatusListener', '(Lloci/formats/StatusListener;)V', 'Saves the given byte array to the current file.') return ImageWriter
def run_batch_macro(macro_text, imp): '''Run a macro in batch mode macro_text - the macro program to be run imp - an image plus to become the active image returns the image plus that was the active image at the end of the run ''' script = """ new java.util.concurrent.Callable() { call: function() { return interp.runBatchMacro(macro_text, imp); } }; """ interp = J.make_instance("ij/macro/Interpreter", "()V") future = J.make_future_task( J.run_script(script, dict(interp=interp, macro_text=macro_text, imp=imp))) return J.execute_future_in_main_thread(future)
def create_img_plus(a, name): '''Create an ImagePlus from a numpy array a - numpy array. The values should be scaled to the range 0-255 name - a user-visible name for the image returns an ImagePlus. The metadata axes will be Y, X and channel (if 3-d) ''' x = J.get_static_field("net/imglib2/img/Axes", "X", "Lnet/imglib2/img/Axes;") y = J.get_static_field("net/imglib2/img/Axes", "Y", "Lnet/imglib2/img/Axes;") c = J.get_static_field("net/imglib2/img/Axes", "CHANNEL", "Lnet/imglib2/img/Axes;") img = create_planar_img(a) img_plus = J.make_instance( "net/imglib2/img/ImgPlus", "(Lnet/imglib2/img/Img;Ljava/lang/String;[Lnet/imglib2/img/Axis;)V", img, name, [y, x] if a.ndim == 2 else [y, x, c])
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