コード例 #1
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
コード例 #2
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
コード例 #3
0
 class ImageDisplay(object):
     def __init__(self):
         self.o = display
     #
     # List<DataView> methods
     #
     size = J.make_method("size", "()I")
     isEmpty = J.make_method("isEmpty", "()Z")
     contains = J.make_method("contains", "(Ljava/lang/Object;)Z")
     def __iter__(self):
         return J.iterate_collection(self.o)
     toArray = J.make_method(
         "toArray", "()[Ljava/lang/Object;",
         fn_post_process=
         lambda o:[wrap_data_view(v) 
                   for v in J.get_env().get_object_array_elements(o)])
     addO = J.make_method("add", "(Ljava/lang/Object;)Z")
     removeO = J.make_method("remove", "(Ljava/lang/Object;)Z")
     clear = J.make_method("clear", "()V")
     get = J.make_method("get", "(I)Ljava/lang/Object;",
                         fn_post_process = wrap_data_view)
     set = J.make_method("set", "(ILjava/lang/Object;)V")
     addI = J.make_method("add", "(ILjava/lang/Object;)V")
     removeI = J.make_method("remove", "(I)V")
     #
     # Display methods
     #
     canDisplay = J.make_method(
         "canDisplay", "(Ljava/lang/Object;)Z",
         "Return true if display can display dataset")
     display = J.make_method(
         "display", "(Ljava/lang/Object;)V",
         "Display the given object")
     update = J.make_method("update", "()V",
                            "Signal display change")
     getName = J.make_method("getName", "()Ljava/lang/String;")
     setName = J.make_method("setName", "(Ljava/lang/String;)V")
     def close(self):
         '''Close the display
         
         This is run in the UI thread with synchronization.
         '''
         r = J.run_script(
             """new java.lang.Runnable() {
             run: function() { display.close(); }
             };
             """, dict(display=self.o))
         J.execute_runnable_in_main_thread(r, True)
     #
     # ImageDisplay methods
     #
     getActiveView = J.make_method(
         "getActiveView", "()Limagej/data/display/DataView;",
         fn_post_process=wrap_data_view)
     getActiveAxis = J.make_method(
         "getActiveAxis", "()Lnet/imglib2/meta/AxisType;")
     setActiveAxis = J.make_method(
         "setActiveAxis", "(Lnet/imglib2/meta/AxisType;)V")
     getCanvas = J.make_method(
         "getCanvas", "()Limagej/data/display/ImageCanvas;")
コード例 #4
0
ファイル: formatwriter.py プロジェクト: braniti/CellProfiler
def make_ome_tiff_writer_class():
    '''Return a class that wraps loci.formats.out.OMETiffWriter'''
    env = jutil.get_env()
    class_name = 'loci/formats/out/OMETiffWriter'
    klass = env.find_class(class_name)
    base_klass = env.find_class('loci/formats/IFormatWriter')
    IFormatWriter = make_iformat_writer_class(class_name)
    class OMETiffWriter(IFormatWriter):
        new_fn = jutil.make_new(class_name, '()V')
        def __init__(self):
            self.new_fn()
        setId = jutil.make_method('setId', '(Ljava/lang/String;)V', 
                                  'Sets the current file name.')
        close = jutil.make_method(
            'close','()V',
            'Closes currently open file(s) and frees allocated memory.')
        saveBytesIFD = jutil.make_method(
            'saveBytes', '(I[BLloci/formats/tiff/IFD;)V',
            '''save a byte array to an image channel
            
            index - image index
            bytes - byte array to save
            ifd - a loci.formats.tiff.IFD instance that gives all of the
                  IFD values associated with the channel''')
    return OMETiffWriter
コード例 #5
0
 class PixelType(object):
     '''Provide enums from ome.xml.model.enums.PixelType'''
     klass = jutil.get_env().find_class('ome/xml/model/enums/PixelType')
     INT8 = jutil.get_static_field(klass, 'INT8',
                                   'Lome/xml/model/enums/PixelType;')
     INT16 = jutil.get_static_field(klass, 'INT16',
                                    'Lome/xml/model/enums/PixelType;')
     INT32 = jutil.get_static_field(klass, 'INT32',
                                    'Lome/xml/model/enums/PixelType;')
     UINT8 = jutil.get_static_field(klass, 'UINT8',
                                    'Lome/xml/model/enums/PixelType;')
     UINT16 = jutil.get_static_field(klass, 'UINT16',
                                     'Lome/xml/model/enums/PixelType;')
     UINT32 = jutil.get_static_field(klass, 'UINT32',
                                     'Lome/xml/model/enums/PixelType;')
     FLOAT = jutil.get_static_field(klass, 'FLOAT',
                                    'Lome/xml/model/enums/PixelType;')
     BIT = jutil.get_static_field(klass, 'BIT',
                                  'Lome/xml/model/enums/PixelType;')
     DOUBLE = jutil.get_static_field(klass, 'DOUBLE',
                                     'Lome/xml/model/enums/PixelType;')
     COMPLEX = jutil.get_static_field(
         klass, 'COMPLEX', 'Lome/xml/model/enums/PixelType;')
     DOUBLECOMPLEX = jutil.get_static_field(
         klass, 'DOUBLECOMPLEX', 'Lome/xml/model/enums/PixelType;')
コード例 #6
0
ファイル: images.py プロジェクト: crschmidt/CellProfiler
def evaluate_url(filtr, url):
    '''Evaluate a URL using a setting's filter
    
    '''
    global filter_class, filter_method_id
    env = J.get_env()
    if filter_class is None:
        filter_class = env.find_class(
            "org/cellprofiler/imageset/filter/Filter")
        if filter_class is None:
            jexception = get_env.exception_occurred()
            raise J.JavaException(jexception)
        filter_method_id = env.get_static_method_id(
            filter_class, "filter", "(Ljava/lang/String;Ljava/lang/String;)Z")
        if filter_method_id is None:
            raise JavaError(
                "Could not find static method, org.cellprofiler.imageset.filter.Filter.filter(String, String)"
            )
    try:
        expression = filtr.value_text
        if isinstance(expression, unicode):
            expression = expression.encode("utf-8")
        if isinstance(url, unicode):
            url = url.encode("utf-8")
        return env.call_static_method(filter_class, filter_method_id,
                                      env.new_string_utf(expression),
                                      env.new_string_utf(url))
    except J.JavaException as e:
        if J.is_instance_of(
                e.throwable,
                "org/cellprofiler/imageset/filter/Filter$BadFilterExpressionException"
        ):
            raise
        return False
コード例 #7
0
ファイル: images.py プロジェクト: akki201/CellProfiler
def evaluate_url(filtr, url):
    '''Evaluate a URL using a setting's filter
    
    '''
    global filter_class, filter_method_id
    env = J.get_env()
    if filter_class is None:
        filter_class = env.find_class("org/cellprofiler/imageset/filter/Filter")
        if filter_class is None:
            jexception = get_env.exception_occurred()
            raise J.JavaException(jexception)
        filter_method_id = env.get_static_method_id(
            filter_class,
            "filter", 
            "(Ljava/lang/String;Ljava/lang/String;)Z")
        if filter_method_id is None:
            raise JavaError("Could not find static method, org.cellprofiler.imageset.filter.Filter.filter(String, String)")
    try:
        expression = filtr.value_text
        if isinstance(expression, unicode):
            expression = expression.encode("utf-8")
        if isinstance(url, unicode):
            url = url.encode("utf-8")
        return env.call_static_method(
            filter_class, filter_method_id, 
            env.new_string_utf(expression), env.new_string_utf(url))
    except J.JavaException as e:
        if J.is_instance_of(
            e.throwable, "org/cellprofiler/imageset/filter/Filter$BadFilterExpressionException"):
            raise
        return False
コード例 #8
0
def make_ome_tiff_writer_class():
    """Return a class that wraps loci.formats.out.OMETiffWriter"""
    env = jutil.get_env()
    class_name = "loci/formats/out/OMETiffWriter"
    klass = env.find_class(class_name)
    base_klass = env.find_class("loci/formats/IFormatWriter")
    IFormatWriter = make_iformat_writer_class(class_name)

    class OMETiffWriter(IFormatWriter):
        new_fn = jutil.make_new(class_name, "()V")

        def __init__(self):
            self.new_fn()

        setId = jutil.make_method("setId", "(Ljava/lang/String;)V", "Sets the current file name.")
        close = jutil.make_method("close", "()V", "Closes currently open file(s) and frees allocated memory.")
        saveBytesIFD = jutil.make_method(
            "saveBytes",
            "(I[BLloci/formats/tiff/IFD;)V",
            """save a byte array to an image channel
            
            index - image index
            bytes - byte array to save
            ifd - a loci.formats.tiff.IFD instance that gives all of the
                  IFD values associated with the channel""",
        )

    return OMETiffWriter
コード例 #9
0
ファイル: images.py プロジェクト: Noiraud/CellProfiler
 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
コード例 #10
0
 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")
コード例 #11
0
def make_ome_tiff_writer_class():
    '''Return a class that wraps loci.formats.out.OMETiffWriter'''
    env = jutil.get_env()
    class_name = 'loci/formats/out/OMETiffWriter'
    klass = env.find_class(class_name)
    base_klass = env.find_class('loci/formats/IFormatWriter')
    IFormatWriter = make_iformat_writer_class(class_name)
    class OMETiffWriter(IFormatWriter):
        new_fn = jutil.make_new(class_name, '()V')
        def __init__(self):
            self.new_fn()
        setId = jutil.make_method('setId', '(Ljava/lang/String;)V', 
                                  'Sets the current file name.')
        close = jutil.make_method(
            'close','()V',
            'Closes currently open file(s) and frees allocated memory.')
        saveBytesIFD = jutil.make_method(
            'saveBytes', '(I[BLloci/formats/tiff/IFD;)V',
            '''save a byte array to an image channel
            
            index - image index
            bytes - byte array to save
            ifd - a loci.formats.tiff.IFD instance that gives all of the
                  IFD values associated with the channel''')
    return OMETiffWriter
コード例 #12
0
ファイル: formatreader.py プロジェクト: Amjadhpc/CellProfiler
 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)
コード例 #13
0
ファイル: test_jutil.py プロジェクト: braniti/CellProfiler
 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")
コード例 #14
0
 def test_03_05_cw_get_annotations(self):
     c = J.get_class_wrapper('java.security.Identity')
     annotations = c.getAnnotations()
     annotations = J.get_env().get_object_array_elements(annotations)
     self.assertEqual(len(annotations), 1)
     self.assertEqual(J.to_string(annotations[0]),
                      '@java.lang.Deprecated()')
コード例 #15
0
ファイル: images.py プロジェクト: vivianleung/CellProfiler
 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
コード例 #16
0
ファイル: formatreader.py プロジェクト: sammac/CellProfiler
 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)
コード例 #17
0
 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
         ]))
コード例 #18
0
ファイル: formatreader.py プロジェクト: drmono/CellProfiler
 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)
コード例 #19
0
ファイル: formatreader.py プロジェクト: sammac/CellProfiler
        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)
コード例 #20
0
ファイル: formatreader.py プロジェクト: drmono/CellProfiler
 def suffixSufficient(self):
     if self.get_class_name() == 'loci.formats.in.JPKReader':
         return True;
     env = jutil.get_env()
     klass = env.get_object_class(self.o)
     field_id = env.get_field_id(klass, "suffixSufficient", "Z")
     if field_id is None:
         return None
     return env.get_boolean_field(self.o, field_id)
コード例 #21
0
ファイル: formatreader.py プロジェクト: sammac/CellProfiler
 def suffixSufficient(self):
     if self.get_class_name() == 'loci.formats.in.JPKReader':
         return True
     env = jutil.get_env()
     klass = env.get_object_class(self.o)
     field_id = env.get_field_id(klass, "suffixSufficient", "Z")
     if field_id is None:
         return None
     return env.get_boolean_field(self.o, field_id)
コード例 #22
0
ファイル: formatreader.py プロジェクト: braniti/CellProfiler
 def suffixNecessary(self):
     if self.get_class_name() == "loci.formats.in.JPKReader":
         return True
     env = jutil.get_env()
     klass = env.get_object_class(self.o)
     field_id = env.get_field_id(klass, "suffixNecessary", "Z")
     if field_id is None:
         return None
     return env.get_boolean_field(self.o, field_id)
コード例 #23
0
ファイル: formatreader.py プロジェクト: sammac/CellProfiler
def make_image_reader_class():
    '''Return an image reader class for the given Java environment'''
    env = jutil.get_env()
    class_name = 'loci/formats/ImageReader'
    klass = env.find_class(class_name)
    base_klass = env.find_class('loci/formats/IFormatReader')
    IFormatReader = make_iformat_reader_class()
    class_list = get_class_list()

    class ImageReader(IFormatReader):
        new_fn = jutil.make_new(class_name, '(Lloci/formats/ClassList;)V')

        def __init__(self):
            self.new_fn(class_list.o)

        getFormat = jutil.make_method(
            'getFormat', '()Ljava/lang/String;',
            'Get a string describing the format of this file')
        getReader = jutil.make_method('getReader',
                                      '()Lloci/formats/IFormatReader;')

        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)

    return ImageReader
コード例 #24
0
ファイル: imagej2.py プロジェクト: akki201/CellProfiler
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
コード例 #25
0
ファイル: formatreader.py プロジェクト: braniti/CellProfiler
def make_image_reader_class():
    """Return an image reader class for the given Java environment"""
    env = jutil.get_env()
    class_name = "loci/formats/ImageReader"
    klass = env.find_class(class_name)
    base_klass = env.find_class("loci/formats/IFormatReader")
    IFormatReader = make_iformat_reader_class()
    class_list = get_class_list()

    class ImageReader(IFormatReader):
        new_fn = jutil.make_new(class_name, "(Lloci/formats/ClassList;)V")

        def __init__(self):
            self.new_fn(class_list.o)

        getFormat = jutil.make_method(
            "getFormat", "()Ljava/lang/String;", "Get a string describing the format of this file"
        )
        getReader = jutil.make_method("getReader", "()Lloci/formats/IFormatReader;")

        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)

    return ImageReader
コード例 #26
0
ファイル: windowmanager.py プロジェクト: braniti/CellProfiler
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")
コード例 #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')
コード例 #28
0
ファイル: windowmanager.py プロジェクト: drmono/CellProfiler
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')
コード例 #29
0
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
コード例 #30
0
def get_measurements_for_good_pipeline(nimages = 1, 
                                       group_numbers = None):
    '''Get an appropriately initialized measurements structure for the good pipeline'''
    path = os.path.join(example_images_directory(), "ExampleSBSImages")
    m = cpmeas.Measurements()
    if group_numbers is None:
        group_numbers = [1] * nimages
    group_indexes = [1]
    last_group_number = group_numbers[0]
    group_index = 1
    for group_number in group_numbers:
        if group_number == last_group_number:
            group_index += 1
        else:
            group_index = 1
        group_indexes.append(group_index)
    for i in range(1, nimages+1):
        filename = ("Channel2-%02d-%s-%02d.tif" % 
                    (i, "ABCDEFGH"[int((i-1) / 12)], ((i-1) % 12) + 1))
        url = pathname2url(os.path.join(path, filename))
        m[cpmeas.IMAGE, cpmeas.C_FILE_NAME + "_DNA", i] = filename
        m[cpmeas.IMAGE, cpmeas.C_PATH_NAME + "_DNA", i] = path
        m[cpmeas.IMAGE, cpmeas.C_URL+"_DNA", i] = url
        m[cpmeas.IMAGE, cpmeas.GROUP_NUMBER, i] = group_numbers[i-1]
        m[cpmeas.IMAGE, cpmeas.GROUP_INDEX, i] = group_indexes[i-1]
        jblob = J.run_script("""
        importPackage(Packages.org.cellprofiler.imageset);
        importPackage(Packages.org.cellprofiler.imageset.filter);
        var imageFile=new ImageFile(new java.net.URI(url));
        var imageFileDetails = new ImageFileDetails(imageFile);
        var imageSeries=new ImageSeries(imageFile, 0);
        var imageSeriesDetails = new ImageSeriesDetails(imageSeries, imageFileDetails);
        var imagePlane=new ImagePlane(imageSeries, 0, ImagePlane.ALWAYS_MONOCHROME);
        var ipd = new ImagePlaneDetails(imagePlane, imageSeriesDetails);
        var stack = ImagePlaneDetailsStack.makeMonochromeStack(ipd);
        var stacks = java.util.Collections.singletonList(stack);
        var keys = java.util.Collections.singletonList(imageNumber);
        var imageSet = new ImageSet(stacks, keys);
        imageSet.compress(java.util.Collections.singletonList("DNA"), null);
        """, dict(url=url, imageNumber = str(i)))
        blob = J.get_env().get_byte_array_elements(jblob)
        m[cpmeas.IMAGE, M_IMAGE_SET, i, blob.dtype] = blob
    pipeline = cpp.Pipeline()
    pipeline.loadtxt(StringIO(GOOD_PIPELINE))
    pipeline.write_pipeline_measurement(m)
    return m
        
コード例 #31
0
ファイル: formatwriter.py プロジェクト: braniti/CellProfiler
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
コード例 #32
0
def get_measurements_for_good_pipeline(nimages=1, group_numbers=None):
    '''Get an appropriately initialized measurements structure for the good pipeline'''
    path = os.path.join(example_images_directory(), "ExampleSBSImages")
    m = cpmeas.Measurements()
    if group_numbers is None:
        group_numbers = [1] * nimages
    group_indexes = [1]
    last_group_number = group_numbers[0]
    group_index = 1
    for group_number in group_numbers:
        if group_number == last_group_number:
            group_index += 1
        else:
            group_index = 1
        group_indexes.append(group_index)
    for i in range(1, nimages + 1):
        filename = ("Channel2-%02d-%s-%02d.tif" % (i, "ABCDEFGH"[int(
            (i - 1) / 12)], ((i - 1) % 12) + 1))
        url = pathname2url(os.path.join(path, filename))
        m[cpmeas.IMAGE, cpmeas.C_FILE_NAME + "_DNA", i] = filename
        m[cpmeas.IMAGE, cpmeas.C_PATH_NAME + "_DNA", i] = path
        m[cpmeas.IMAGE, cpmeas.C_URL + "_DNA", i] = url
        m[cpmeas.IMAGE, cpmeas.GROUP_NUMBER, i] = group_numbers[i - 1]
        m[cpmeas.IMAGE, cpmeas.GROUP_INDEX, i] = group_indexes[i - 1]
        jblob = J.run_script(
            """
        importPackage(Packages.org.cellprofiler.imageset);
        importPackage(Packages.org.cellprofiler.imageset.filter);
        var imageFile=new ImageFile(new java.net.URI(url));
        var imageFileDetails = new ImageFileDetails(imageFile);
        var imageSeries=new ImageSeries(imageFile, 0);
        var imageSeriesDetails = new ImageSeriesDetails(imageSeries, imageFileDetails);
        var imagePlane=new ImagePlane(imageSeries, 0, ImagePlane.ALWAYS_MONOCHROME);
        var ipd = new ImagePlaneDetails(imagePlane, imageSeriesDetails);
        var stack = ImagePlaneDetailsStack.makeMonochromeStack(ipd);
        var stacks = java.util.Collections.singletonList(stack);
        var keys = java.util.Collections.singletonList(imageNumber);
        var imageSet = new ImageSet(stacks, keys);
        imageSet.compress(java.util.Collections.singletonList("DNA"), null);
        """, dict(url=url, imageNumber=str(i)))
        blob = J.get_env().get_byte_array_elements(jblob)
        m[cpmeas.IMAGE, M_IMAGE_SET, i, blob.dtype] = blob
    pipeline = cpp.Pipeline()
    pipeline.loadtxt(StringIO(GOOD_PIPELINE))
    pipeline.write_pipeline_measurement(m)
    return m
コード例 #33
0
ファイル: images.py プロジェクト: crschmidt/CellProfiler
 def prepare_run(self, workspace):
     '''Create an IPD for every url that passes the filter'''
     if workspace.pipeline.in_batch_mode():
         return True
     if self.wants_filter:
         env = J.get_env()
         jexpression = env.new_string_utf(self.filter.value_text)
         filter_fn = J.make_static_call(
             "org/cellprofiler/imageset/filter/Filter", "filter",
             "(Ljava/lang/String;Ljava/lang/String;)Z")
         ipds = filter(
             lambda ipd: filter_fn(jexpression, env.new_string_utf(
                 ipd.url)), workspace.pipeline.image_plane_details)
     else:
         ipds = workspace.pipeline.image_plane_details
     workspace.pipeline.set_filtered_image_plane_details(ipds, self)
     return True
コード例 #34
0
ファイル: imagej2.py プロジェクト: braniti/CellProfiler
 def get_pixel_data(self, axes = None):
     imgplus = self.getImgPlus()
     pixel_data = get_pixel_data(imgplus)
     inv_axes = J.get_env().get_object_array_elements(self.getAxes())
     if axes is None:
         axes = [ Axes().Y, Axes().X]
         if len(inv_axes) > 2:
             axes.append(Axes().CHANNEL)
     transpose = []
     for axis in axes:
         matches = [i for i, inv_axis in enumerate(inv_axes)
                    if J.call(inv_axis, "equals", 
                              "(Ljava/lang/Object;)Z", axis)]
         if len(matches) != 1:
             raise ValueError("No match for %s axis" % J.to_string(axis))
         transpose.append(matches[0])
     return pixel_data.transpose(transpose)
コード例 #35
0
ファイル: images.py プロジェクト: akki201/CellProfiler
 def prepare_run(self, workspace):
     '''Create an IPD for every url that passes the filter'''
     if workspace.pipeline.in_batch_mode():
         return True
     if self.wants_filter:
         env = J.get_env()
         jexpression = env.new_string_utf(self.filter.value_text)
         filter_fn = J.make_static_call(
             "org/cellprofiler/imageset/filter/Filter",
             "filter", "(Ljava/lang/String;Ljava/lang/String;)Z")
         ipds = filter(
             lambda ipd:filter_fn(jexpression, env.new_string_utf(ipd.url)), 
             workspace.pipeline.image_plane_details)
     else:
         ipds = workspace.pipeline.image_plane_details
     workspace.pipeline.set_filtered_image_plane_details(ipds, self)
     return True
コード例 #36
0
 def get_pixel_data(self, axes=None):
     imgplus = self.getImgPlus()
     pixel_data = get_pixel_data(imgplus)
     inv_axes = J.get_env().get_object_array_elements(self.getAxes())
     if axes is None:
         axes = [Axes().Y, Axes().X]
         if len(inv_axes) > 2:
             axes.append(Axes().CHANNEL)
     transpose = []
     for axis in axes:
         matches = [
             i for i, inv_axis in enumerate(inv_axes) if J.call(
                 inv_axis, "equals", "(Ljava/lang/Object;)Z", axis)
         ]
         if len(matches) != 1:
             raise ValueError("No match for %s axis" %
                              J.to_string(axis))
         transpose.append(matches[0])
     return pixel_data.transpose(transpose)
コード例 #37
0
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
コード例 #38
0
 class FormatTools(object):
     '''A wrapper for loci.formats.FormatTools
     
     See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/FormatTools.html
     '''
     env = jutil.get_env()
     klass = env.find_class('loci/formats/FormatTools')
     CAN_GROUP = jutil.get_static_field(klass, 'CAN_GROUP','I')
     CANNOT_GROUP = jutil.get_static_field(klass, 'CANNOT_GROUP','I')
     DOUBLE = jutil.get_static_field(klass, 'DOUBLE','I')
     FLOAT = jutil.get_static_field(klass, 'FLOAT', 'I')
     INT16 = jutil.get_static_field(klass, 'INT16', 'I')
     INT32 = jutil.get_static_field(klass, 'INT32', 'I')
     INT8 = jutil.get_static_field(klass, 'INT8', 'I')
     MUST_GROUP = jutil.get_static_field(klass, 'MUST_GROUP', 'I')
     UINT16 = jutil.get_static_field(klass, 'UINT16', 'I')
     UINT32 = jutil.get_static_field(klass, 'UINT32', 'I')
     UINT8 = jutil.get_static_field(klass, 'UINT8', 'I')
     
     @classmethod
     def getPixelTypeString(cls, pixel_type):
         return jutil.static_call('loci/formats/FormatTools', 'getPixelTypeString', '(I)Ljava/lang/String;', pixel_type)
コード例 #39
0
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
コード例 #40
0
ファイル: formatreader.py プロジェクト: braniti/CellProfiler
 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;" "Ljava/lang/Class;)V",  # base  # 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"
     ]
     for problem_class in problem_classes:
         # Move to back
         klass = jutil.class_for_name(problem_class)
         self.remove_class(klass)
         self.add_class(klass)
コード例 #41
0
def convert_pixels_to_buffer(pixels, pixel_type):
    '''Convert the pixels in the image into a buffer of the right pixel type
    
    pixels - a 2d monochrome or color image
    
    pixel_type - one of the OME pixel types
    
    returns a 1-d byte array
    '''
    if pixel_type in (ome.PT_UINT8, ome.PT_INT8, ome.PT_BIT):
        as_dtype = np.uint8
    elif pixel_type in (ome.PT_UINT16, ome.PT_INT16):
        as_dtype = "<u2"
    elif pixel_type in (ome.PT_UINT32, ome.PT_INT32):
        as_dtype = "<u4"
    elif pixel_type == ome.PT_FLOAT:
        as_dtype = "<f4"
    elif pixel_type == ome.PT_DOUBLE:
        as_dtype = "<f8"
    else:
        raise NotImplementedError("Unsupported pixel type: %d" % pixel_type)
    buf = np.frombuffer(np.ascontiguousarray(pixels, as_dtype).data, np.uint8)
    env = jutil.get_env()
    return env.make_byte_array(buf)
コード例 #42
0
def convert_pixels_to_buffer(pixels, pixel_type):
    """Convert the pixels in the image into a buffer of the right pixel type
    
    pixels - a 2d monochrome or color image
    
    pixel_type - one of the OME pixel types
    
    returns a 1-d byte array
    """
    if pixel_type in (ome.PT_UINT8, ome.PT_INT8, ome.PT_BIT):
        as_dtype = np.uint8
    elif pixel_type in (ome.PT_UINT16, ome.PT_INT16):
        as_dtype = "<u2"
    elif pixel_type in (ome.PT_UINT32, ome.PT_INT32):
        as_dtype = "<u4"
    elif pixel_type == ome.PT_FLOAT:
        as_dtype = "<f4"
    elif pixel_type == ome.PT_DOUBLE:
        as_dtype = "<f8"
    else:
        raise NotImplementedError("Unsupported pixel type: %d" % pixel_type)
    buf = np.frombuffer(np.ascontiguousarray(pixels, as_dtype).data, np.uint8)
    env = jutil.get_env()
    return env.make_byte_array(buf)
コード例 #43
0
ファイル: imageprocessor.py プロジェクト: drmono/CellProfiler
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
コード例 #44
0
 def getDimensions(self):
     'Returns the dimensions of this image: (width, height, nChannels, nSlices, nFrames)'
     jresult = J.call(self.o, 'getDimensions', '()[I')
     return J.get_env().get_int_array_elements(jresult)
コード例 #45
0
ファイル: metadata.py プロジェクト: crschmidt/CellProfiler
    def prepare_run(self, workspace):
        '''Initialize the pipeline's metadata'''
        if workspace.pipeline.in_batch_mode():
            return True

        file_list = workspace.file_list
        pipeline = workspace.pipeline
        ipds = pipeline.get_filtered_image_plane_details(workspace)
        extractor = self.build_extractor()
        max_series = 0
        max_index = 0
        for ipd in ipds:
            if ipd.series is not None:
                max_series = max(max_series, ipd.series)
            if ipd.index is not None:
                max_index = max(max_index, ipd.index)
        if max_series > 0:
            series_digits = int(np.log10(max_series)) + 1
        else:
            series_digits = 1
        if max_index > 0:
            index_digits = int(np.log10(max_index)) + 1
        else:
            index_digits = 1
        if max_series > 0 or max_index > 0:
            script = """
            importPackage(Packages.org.cellprofiler.imageset);
            extractor.addImagePlaneExtractor(new SeriesIndexMetadataExtractor(
                seriesDigits, indexDigits));
            """
            J.run_script(
                script,
                dict(extractor=extractor,
                     seriesDigits=series_digits,
                     indexDigits=index_digits))
        env = J.get_env()
        entry_set_class = env.find_class("java/util/Map$Entry")
        get_key_id = env.get_method_id(entry_set_class, "getKey",
                                       "()Ljava/lang/Object;")
        get_value_id = env.get_method_id(entry_set_class, "getValue",
                                         "()Ljava/lang/Object;")

        def wrap_entry_set(o):
            return (env.get_string_utf(env.call_method(o, get_key_id)),
                    env.get_string_utf(env.call_method(o, get_value_id)))

        #
        # Much of what appears below is optimized to avoid the cost of
        # "getting nice arguments" for the Java bridge. The IPDs should be
        # in alphabetical order which means that, for stacks, we can
        # save the results of OME-XML parsing in the Java ImageFile object.
        #
        extractor_class = env.find_class(
            "org/cellprofiler/imageset/ImagePlaneMetadataExtractor")
        extract_metadata_id = env.get_method_id(
            extractor_class, "extractMetadata",
            "(Ljava/lang/String;IILjava/lang/String;"
            "[Lorg/cellprofiler/imageset/filter/ImagePlaneDetails;"
            "[Lorg/cellprofiler/imageset/ImageFile;"
            ")Ljava/util/Iterator;")
        extract_metadata_if_id = env.get_method_id(
            extractor_class, "extractMetadata",
            "(Lorg/cellprofiler/imageset/ImageFile;II"
            "[Lorg/cellprofiler/imageset/filter/ImagePlaneDetails;"
            ")Ljava/util/Iterator;")
        ipd_class = env.find_class(
            "org/cellprofiler/imageset/filter/ImagePlaneDetails")
        if_class = env.find_class("org/cellprofiler/imageset/ImageFile")
        clear_xml_document_id = env.get_method_id(if_class, "clearXMLDocument",
                                                  "()V")
        pIPD = env.make_object_array(1, ipd_class)
        pIF = env.make_object_array(1, if_class)

        last_url = None
        last_if = None
        if_has_metadata = False
        for ipd in ipds:
            series, index = [
                x if x is not None else 0 for x in ipd.series, ipd.index
            ]
            if ipd.url != last_url:
                if if_has_metadata:
                    env.call_method(last_if, clear_xml_document_id)
                    x = env.exception_occurred()
                    if x is not None:
                        raise J.JavaException(x)
                    if_has_metadata = False
                xmlmetadata = file_list.get_metadata(ipd.url)
                if xmlmetadata is not None:
                    xmlmetadata = env.new_string_utf(xmlmetadata)
                    if_has_metadata = True
                metadata = env.call_method(extractor, extract_metadata_id,
                                           env.new_string_utf(ipd.url),
                                           int(series), int(index),
                                           xmlmetadata, pIPD, pIF)
                x = env.exception_occurred()
                if x is not None:
                    raise J.JavaException(x)
                last_url = ipd.url
                last_if = env.get_object_array_elements(pIF)[0]
            else:
                metadata = env.call_method(extractor,
                                           extract_metadata_if_id, last_if,
                                           int(series), int(index), pIPD)
                x = env.exception_occurred()
                if x is not None:
                    raise J.JavaException(x)

            ipd.metadata.update(J.iterate_java(metadata, wrap_entry_set))
            ipd.jipd = env.get_object_array_elements(pIPD)[0]
        if if_has_metadata:
            env.call_method(last_if, clear_xml_document_id)
            x = env.exception_occurred()
            if x is not None:
                raise J.JavaException(x)
        return True
コード例 #46
0
ファイル: imageplus.py プロジェクト: pombredanne/CellProfiler
 def getDimensions(self):
     "Returns the dimensions of this image: (width, height, nChannels, nSlices, nFrames)"
     jresult = J.call(self.o, "getDimensions", "()[I")
     return J.get_env().get_int_array_elements(jresult)
コード例 #47
0
 def fn(path=path, c=c, z=z, t=t, series=series, index=index,
        rescale=rescale, wants_max_intensity=wants_max_intensity,
        channel_names=channel_names):
     FormatTools = make_format_tools_class()
     ImageReader = make_image_reader_class()
     ChannelSeparator = make_reader_wrapper_class(
         "loci/formats/ChannelSeparator")
     
     #
     # Bioformats is more picky about slashes than Python
     #
     if sys.platform.startswith("win"):
         path = path.replace("/",os.path.sep)
     #
     # Bypass the ImageReader and scroll through the class list. The
     # goal here is to ask the FormatHandler if it thinks it could
     # possibly parse the file, then only give the FormatReader access
     # to the open file stream so it can't damage the file server.
     #
     
     env = jutil.get_env()
     class_list = get_class_list()
     stream = jutil.make_instance('loci/common/RandomAccessInputStream',
                                  '(Ljava/lang/String;)V', path)
     filename = os.path.split(path)[1]
     IFormatReader = make_iformat_reader_class()
     rdr = None
     for klass in env.get_object_array_elements(class_list.get_classes()):
         wclass = jutil.get_class_wrapper(klass, True)
         maybe_rdr = IFormatReader()
         maybe_rdr.o = wclass.newInstance()
         maybe_rdr.setGroupFiles(False)
         if maybe_rdr.suffixNecessary:
             if not maybe_rdr.isThisTypeSZ(filename, False):
                 continue
             if maybe_rdr.suffixSufficient:
                 rdr = maybe_rdr
                 break
         if (maybe_rdr.isThisTypeStream(stream)):
             rdr = maybe_rdr
             break
     if rdr is None:
         raise ValueError("Could not find a Bio-Formats reader for %s", path)
     mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
     rdr.setMetadataOptions(mdoptions)
     metadata = metadatatools.createOMEXMLMetadata()
     rdr.setMetadataStore(metadata)
     rdr.setId(path)
     width = rdr.getSizeX()
     height = rdr.getSizeY()
     pixel_type = rdr.getPixelType()
     little_endian = rdr.isLittleEndian()
     if pixel_type == FormatTools.INT8:
         dtype = np.char
         scale = 255
     elif pixel_type == FormatTools.UINT8:
         dtype = np.uint8
         scale = 255
     elif pixel_type == FormatTools.UINT16:
         dtype = '<u2' if little_endian else '>u2'
         scale = 65535
     elif pixel_type == FormatTools.INT16:
         dtype = '<i2' if little_endian else '>i2'
         scale = 65535
     elif pixel_type == FormatTools.UINT32:
         dtype = '<u4' if little_endian else '>u4'
         scale = 2**32
     elif pixel_type == FormatTools.INT32:
         dtype = '<i4' if little_endian else '>i4'
         scale = 2**32-1
     elif pixel_type == FormatTools.FLOAT:
         dtype = '<f4' if little_endian else '>f4'
         scale = 1
     elif pixel_type == FormatTools.DOUBLE:
         dtype = '<f8' if little_endian else '>f8'
         scale = 1
     max_sample_value = rdr.getMetadataValue('MaxSampleValue')
     if max_sample_value is not None:
         try:
             scale = jutil.call(max_sample_value, 'intValue', '()I')
         except:
             bioformats.logger.warning("WARNING: failed to get MaxSampleValue for image. Intensities may be improperly scaled.")
     if series is not None:
         rdr.setSeries(series)
     if index is not None:
         image = np.frombuffer(rdr.openBytes(index), dtype)
         if len(image) / height / width in (3,4):
             image.shape = (height, width, int(len(image) / height / width))
         else:
             image.shape = (height, width)
     elif rdr.isRGB() and rdr.isInterleaved():
         index = rdr.getIndex(z,0,t)
         image = np.frombuffer(rdr.openBytes(index), dtype)
         image.shape = (height, width, 3)
     elif c is not None and rdr.getRGBChannelCount() == 1:
         index = rdr.getIndex(z,c,t)
         image = np.frombuffer(rdr.openBytes(index), dtype)
         image.shape = (height, width)
     elif rdr.getRGBChannelCount() > 1:
         rdr.close()
         rdr = ImageReader()
         rdr.allowOpenToCheckType(False)
         rdr = ChannelSeparator(rdr)
         rdr.setGroupFiles(False)
         rdr.setId(path)
         red_image, green_image, blue_image = [
             np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)),dtype)
             for i in range(3)]
         image = np.dstack((red_image, green_image, blue_image))
         image.shape=(height,width,3)
     elif rdr.getSizeC() > 1:
         images = [np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)), dtype)
                   for i in range(rdr.getSizeC())]
         image = np.dstack(images)
         image.shape = (height, width, rdr.getSizeC())
         if not channel_names is None:
             metadata = metadatatools.MetadataRetrieve(metadata)
             for i in range(rdr.getSizeC()):
                 index = rdr.getIndex(z, 0, t)
                 channel_name = metadata.getChannelName(index, i)
                 if channel_name is None:
                     channel_name = metadata.getChannelID(index, i)
                 channel_names.append(channel_name)
     else:
         index = rdr.getIndex(z,0,t)
         image = np.frombuffer(rdr.openBytes(index),dtype)
         image.shape = (height,width)
         
     rdr.close()
     jutil.call(stream, 'close', '()V')
     del rdr
     #
     # Run the Java garbage collector here.
     #
     jutil.static_call("java/lang/System", "gc","()V")
     if rescale:
         image = image.astype(np.float32) / float(scale)
     if wants_max_intensity:
         return image, scale
     return image
コード例 #48
0
ファイル: test_jutil.py プロジェクト: braniti/CellProfiler
 def test_03_03_cw_get_classes(self):
     c = J.get_class_wrapper('java.lang.Number')
     classes = c.getClasses()
     self.assertEqual(len(J.get_env().get_object_array_elements(classes)), 0)
コード例 #49
0
ファイル: test_jutil.py プロジェクト: braniti/CellProfiler
 def test_03_05_cw_get_annotations(self):
     c = J.get_class_wrapper('java.security.Identity')
     annotations = c.getAnnotations()
     annotations = J.get_env().get_object_array_elements(annotations)
     self.assertEqual(len(annotations), 1)
     self.assertEqual(J.to_string(annotations[0]),'@java.lang.Deprecated()')
コード例 #50
0
ファイル: test_jutil.py プロジェクト: braniti/CellProfiler
 def test_03_06_cw_get_constructors(self):
     c = J.get_class_wrapper('java.lang.String')
     constructors = c.getConstructors()
     constructors = J.get_env().get_object_array_elements(constructors)
     self.assertEqual(len(constructors), 15)
コード例 #51
0
 def test_03_06_cw_get_constructors(self):
     c = J.get_class_wrapper('java.lang.String')
     constructors = c.getConstructors()
     constructors = J.get_env().get_object_array_elements(constructors)
     self.assertEqual(len(constructors), 15)
コード例 #52
0
ファイル: test_jutil.py プロジェクト: braniti/CellProfiler
 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]))
コード例 #53
0
 def test_03_03_cw_get_classes(self):
     c = J.get_class_wrapper('java.lang.Number')
     classes = c.getClasses()
     self.assertEqual(len(J.get_env().get_object_array_elements(classes)),
                      0)
コード例 #54
0
ファイル: formatreader.py プロジェクト: sammac/CellProfiler
def __load_using_bioformats(path, c, z, t, series, index, rescale,
                            wants_max_intensity, channel_names):
    FormatTools = make_format_tools_class()
    ImageReader = make_image_reader_class()
    ChannelSeparator = make_reader_wrapper_class(
        "loci/formats/ChannelSeparator")

    #
    # Bioformats is more picky about slashes than Python
    #
    if sys.platform.startswith("win"):
        path = path.replace("/", os.path.sep)
    #
    # Bypass the ImageReader and scroll through the class list. The
    # goal here is to ask the FormatHandler if it thinks it could
    # possibly parse the file, then only give the FormatReader access
    # to the open file stream so it can't damage the file server.
    #
    # Pass 0 - allow access to stream if reader believes it is the correct
    #          reader no matter what the file contents.
    # Pass 1 - allow access to stream if reader indicates that it supports
    #          files with this file's suffix.
    # Pass 2 - allow all readers access to the stream
    #

    env = jutil.get_env()
    with GetImageReader(path) as rdr:
        mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
        rdr.setMetadataOptions(mdoptions)
        rdr.setGroupFiles(False)
        metadata = metadatatools.createOMEXMLMetadata()
        rdr.setMetadataStore(metadata)
        rdr.setId(path)
        width = rdr.getSizeX()
        height = rdr.getSizeY()
        pixel_type = rdr.getPixelType()
        little_endian = rdr.isLittleEndian()
        if pixel_type == FormatTools.INT8:
            dtype = np.char
            scale = 255
        elif pixel_type == FormatTools.UINT8:
            dtype = np.uint8
            scale = 255
        elif pixel_type == FormatTools.UINT16:
            dtype = '<u2' if little_endian else '>u2'
            scale = 65535
        elif pixel_type == FormatTools.INT16:
            dtype = '<i2' if little_endian else '>i2'
            scale = 65535
        elif pixel_type == FormatTools.UINT32:
            dtype = '<u4' if little_endian else '>u4'
            scale = 2**32
        elif pixel_type == FormatTools.INT32:
            dtype = '<i4' if little_endian else '>i4'
            scale = 2**32 - 1
        elif pixel_type == FormatTools.FLOAT:
            dtype = '<f4' if little_endian else '>f4'
            scale = 1
        elif pixel_type == FormatTools.DOUBLE:
            dtype = '<f8' if little_endian else '>f8'
            scale = 1
        max_sample_value = rdr.getMetadataValue('MaxSampleValue')
        if max_sample_value is not None:
            try:
                scale = jutil.call(max_sample_value, 'intValue', '()I')
            except:
                bioformats.logger.warning(
                    "WARNING: failed to get MaxSampleValue for image. Intensities may be improperly scaled."
                )
        if series is not None:
            rdr.setSeries(series)
        if index is not None:
            image = np.frombuffer(rdr.openBytes(index), dtype)
            if len(image) / height / width in (3, 4):
                n_channels = int(len(image) / height / width)
                if rdr.isInterleaved():
                    image.shape = (height, width, n_channels)
                else:
                    image.shape = (n_channels, height, width)
                    image = image.transpose(1, 2, 0)
            else:
                image.shape = (height, width)
        elif rdr.isRGB() and rdr.isInterleaved():
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width, 3)
        elif c is not None and rdr.getRGBChannelCount() == 1:
            index = rdr.getIndex(z, c, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width)
        elif rdr.getRGBChannelCount() > 1:
            n_planes = rdr.getRGBChannelCount()
            rdr = ChannelSeparator(rdr)
            planes = [
                np.frombuffer(rdr.openBytes(rdr.getIndex(z, i, t)), dtype)
                for i in range(n_planes)
            ]
            if len(planes) > 3:
                planes = planes[:3]
            elif len(planes) < 3:
                # > 1 and < 3 means must be 2
                # see issue #775
                planes.append(np.zeros(planes[0].shape, planes[0].dtype))
            image = np.dstack(planes)
            image.shape = (height, width, 3)
        elif rdr.getSizeC() > 1:
            images = [
                np.frombuffer(rdr.openBytes(rdr.getIndex(z, i, t)), dtype)
                for i in range(rdr.getSizeC())
            ]
            image = np.dstack(images)
            image.shape = (height, width, rdr.getSizeC())
            if not channel_names is None:
                metadata = metadatatools.MetadataRetrieve(metadata)
                for i in range(rdr.getSizeC()):
                    index = rdr.getIndex(z, 0, t)
                    channel_name = metadata.getChannelName(index, i)
                    if channel_name is None:
                        channel_name = metadata.getChannelID(index, i)
                    channel_names.append(channel_name)
        elif rdr.isIndexed():
            #
            # The image data is indexes into a color lookup-table
            # But sometimes the table is the identity table and just generates
            # a monochrome RGB image
            #
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            if pixel_type in (FormatTools.INT16, FormatTools.UINT16):
                lut = rdr.get16BitLookupTable()
                lut = np.array([
                    env.get_short_array_elements(d)
                    for d in env.get_object_array_elements(lut)
                ]).transpose()
            else:
                lut = rdr.get8BitLookupTable()
                lut = np.array([
                    env.get_byte_array_elements(d)
                    for d in env.get_object_array_elements(lut)
                ]).transpose()
            image.shape = (height, width)
            if not np.all(lut == np.arange(lut.shape[0])[:, np.newaxis]):
                image = lut[image, :]
        else:
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width)

        rdr.close()
    if rescale:
        image = image.astype(np.float32) / float(scale)
    if wants_max_intensity:
        return image, scale
    return image
コード例 #55
0
def get_id_list():
    '''Get the list of IDs of open images'''
    jid_list = J.static_call('ij/WindowManager', 'getIDList', '()[I')
    return J.get_env().get_int_array_elements(jid_list)
コード例 #56
0
def get_id_list():
    '''Get the list of IDs of open images'''
    jid_list = J.static_call('ij/WindowManager', 'getIDList', '()[I')
    return J.get_env().get_int_array_elements(jid_list)
コード例 #57
0
ファイル: metadata.py プロジェクト: JDWarner/CellProfiler
 def prepare_run(self, workspace):
     '''Initialize the pipeline's metadata'''
     if workspace.pipeline.in_batch_mode():
         return True
     
     file_list = workspace.file_list
     pipeline = workspace.pipeline
     ipds = pipeline.get_filtered_image_plane_details(workspace)
     extractor = self.build_extractor()
     max_series = 0
     max_index = 0
     for ipd in ipds:
         if ipd.series is not None:
             max_series = max(max_series, ipd.series)
         if ipd.index is not None:
             max_index = max(max_index, ipd.index)
     if max_series > 0:
         series_digits = int(np.log10(max_series)) + 1
     else:
         series_digits = 1
     if max_index > 0:
         index_digits = int(np.log10(max_index)) + 1
     else:
         index_digits = 1
     if max_series > 0 or max_index > 0:
         script = """
         importPackage(Packages.org.cellprofiler.imageset);
         extractor.addImagePlaneExtractor(new SeriesIndexMetadataExtractor(
             seriesDigits, indexDigits));
         """
         J.run_script(script, dict(extractor = extractor,
                                   seriesDigits = series_digits,
                                   indexDigits = index_digits))
     env = J.get_env()
     entry_set_class = env.find_class("java/util/Map$Entry")
     get_key_id = env.get_method_id(entry_set_class, "getKey", "()Ljava/lang/Object;")
     get_value_id = env.get_method_id(entry_set_class, "getValue", "()Ljava/lang/Object;")
             
     def wrap_entry_set(o):
         return (env.get_string_utf(env.call_method(o, get_key_id)), 
                 env.get_string_utf(env.call_method(o, get_value_id)))
     #
     # Much of what appears below is optimized to avoid the cost of
     # "getting nice arguments" for the Java bridge. The IPDs should be
     # in alphabetical order which means that, for stacks, we can
     # save the results of OME-XML parsing in the Java ImageFile object.
     #
     extractor_class = env.find_class(
         "org/cellprofiler/imageset/ImagePlaneMetadataExtractor")
     extract_metadata_id = env.get_method_id(
         extractor_class,
         "extractMetadata",
         "(Ljava/lang/String;IILjava/lang/String;"
         "[Lorg/cellprofiler/imageset/filter/ImagePlaneDetails;"
         "[Lorg/cellprofiler/imageset/ImageFile;"
         ")Ljava/util/Iterator;")
     extract_metadata_if_id = env.get_method_id(
         extractor_class,
         "extractMetadata",
         "(Lorg/cellprofiler/imageset/ImageFile;II"
         "[Lorg/cellprofiler/imageset/filter/ImagePlaneDetails;"
         ")Ljava/util/Iterator;")
     ipd_class = env.find_class("org/cellprofiler/imageset/filter/ImagePlaneDetails")
     if_class = env.find_class("org/cellprofiler/imageset/ImageFile")
     clear_xml_document_id = env.get_method_id(
         if_class,
         "clearXMLDocument", "()V")
     pIPD = env.make_object_array(1, ipd_class)
     pIF = env.make_object_array(1, if_class)
     
     last_url = None
     last_if = None
     if_has_metadata = False
     for ipd in ipds:
         series, index = [x if x is not None else 0 
                          for x in ipd.series, ipd.index]
         if ipd.url != last_url:
             if if_has_metadata:
                 env.call_method(last_if, clear_xml_document_id)
                 x = env.exception_occurred()
                 if x is not None:
                     raise J.JavaException(x)
                 if_has_metadata = False
             xmlmetadata = file_list.get_metadata(ipd.url)
             if xmlmetadata is not None:
                 xmlmetadata = env.new_string_utf(xmlmetadata)
                 if_has_metadata = True
             metadata = env.call_method(extractor, extract_metadata_id,
                                        env.new_string_utf(ipd.url),
                                        int(series), int(index),
                                        xmlmetadata, pIPD, pIF)
             x = env.exception_occurred()
             if x is not None:
                 raise J.JavaException(x)
             last_url = ipd.url
             last_if = env.get_object_array_elements(pIF)[0]
         else:
             metadata = env.call_method(
                 extractor, extract_metadata_if_id,
                 last_if, int(series), int(index), pIPD)
             x = env.exception_occurred()
             if x is not None:
                 raise J.JavaException(x)
         
         ipd.metadata.update(J.iterate_java(metadata, wrap_entry_set))
         ipd.jipd = env.get_object_array_elements(pIPD)[0]
     if if_has_metadata:
         env.call_method(last_if, clear_xml_document_id)
         x = env.exception_occurred()
         if x is not None:
             raise J.JavaException(x)
     return True