Пример #1
0
    def test_plugins_load_using_pairwise_stitching(self, ij_fixture):
        try:
            sj.jimport("plugin.Stitching_Pairwise")
        except TypeError:
            pytest.skip(
                "No Pairwise Stitching plugin available. Skipping test.")

        if not ij_fixture.legacy:
            pytest.skip("No original ImageJ. Skipping test.")
        if ij_fixture.ui().isHeadless():
            pytest.skip("No GUI. Skipping test.")

        macro = """
        newImage("Tile1", "8-bit random", 512, 512, 1);
        newImage("Tile2", "8-bit random", 512, 512, 1);
        """
        plugin = "Pairwise stitching"
        args = {"first_image": "Tile1", "second_image": "Tile2"}

        ij_fixture.script().run("macro.ijm", macro, True).get()
        ij_fixture.py.run_plugin(plugin, args)
        result_name = ij_fixture.WindowManager.getCurrentImage().getTitle()

        ij_fixture.script().run("macro.ijm", 'run("Close All");', True).get()

        assert result_name == "Tile1<->Tile2"
Пример #2
0
def detections_to_imagej(dataset,
                         detections: np.ndarray,
                         add_to_roi_manager=False):
    """
    Convert blob detections to ImageJ oval ROIs.
    Optionally add the ROIs to the RoiManager.
    """
    # get ImageJ resources
    ImagePlus = sj.jimport('ij.ImagePlus')
    OvalRoi = sj.jimport('ij.gui.OvalRoi')
    Overlay = sj.jimport('ij.gui.Overlay')
    ov = Overlay()

    # convert Dataset to ImagePlus
    imp = ij.convert().convert(dataset, ImagePlus)

    if add_to_roi_manager:
        RoiManager = sj.jimport('ij.plugin.frame.RoiManager')()
        rm = RoiManager.getRoiManager()

    for i in range(len(detections)):
        values = detections[i].tolist()
        y = values[0]
        x = values[1]
        r = values[2]
        d = r * 2
        roi = OvalRoi(x - r, y - r, d, d)
        imp.setRoi(roi)
        ov.add(roi)
        if add_to_roi_manager:
            rm.addRoi(roi)

    imp.setOverlay(ov)
    imp.getProcessor().resetMinAndMax()
    imp.show()
Пример #3
0
    def _get_imgplus(ij_fixture):
        """Get a 7D ImgPlus."""
        # get java resources
        Random = sj.jimport("java.util.Random")
        Axes = sj.jimport("net.imagej.axis.Axes")
        UnsignedByteType = sj.jimport(
            "net.imglib2.type.numeric.integer.UnsignedByteType")
        DatasetService = ij_fixture.get("net.imagej.DatasetService")

        # test image parameters
        foo = Axes.get("foo")
        bar = Axes.get("bar")
        shape = [13, 17, 5, 2, 3, 7, 11]
        axes = [Axes.X, Axes.Y, foo, bar, Axes.CHANNEL, Axes.TIME, Axes.Z]

        # create image
        dataset = DatasetService.create(UnsignedByteType(), shape,
                                        "fabulous7D", axes)
        imgplus = dataset.typedImg(UnsignedByteType())

        # fill the image with noise
        rng = Random(123456789)
        t = UnsignedByteType()

        for t in imgplus:
            t.set(rng.nextInt(256))

        return imgplus
Пример #4
0
def detections_to_bdv(image, detections: np.ndarray):
    """
    Display image and ROIs in BigDataViewer.
    """
    # get useful classes
    BdvFunctions = sj.jimport('bdv.util.BdvFunctions')
    BdvOptions = sj.jimport('bdv.util.BdvOptions')

    # show image
    BdvFunctions.show(image, 'test', BdvOptions.options().is2D())
Пример #5
0
    def testPandasToTable(self):
        # Float table.
        columns = ["header1", "header2", "header3", "header4", "header5"]
        array = np.random.random(size=(7, 5))

        df = pd.DataFrame(array, columns=columns)
        table = to_java(df)

        assert_same_table(table, df)
        assert type(table) == jimport('org.scijava.table.DefaultFloatTable')

        # Int table.
        columns = ["header1", "header2", "header3", "header4", "header5"]
        array = np.random.random(size=(7, 5)) * 100
        array = array.astype('int')

        df = pd.DataFrame(array, columns=columns)
        table = to_java(df)

        assert_same_table(table, df)
        assert type(table) == jimport('org.scijava.table.DefaultIntTable')

        # Bool table.
        columns = ["header1", "header2", "header3", "header4", "header5"]
        array = np.random.random(size=(7, 5)) > 0.5

        df = pd.DataFrame(array, columns=columns)
        table = to_java(df)

        assert_same_table(table, df)
        assert type(table) == jimport('org.scijava.table.DefaultBoolTable')

        # Mixed table.
        columns = ["header1", "header2", "header3", "header4", "header5"]
        array = np.random.random(size=(7, 5))

        df = pd.DataFrame(array, columns=columns)

        # Convert column 0 to integer
        df.iloc[:, 0] = (df.iloc[:, 0] * 100).astype('int')
        # Convert column 1 to bool
        df.iloc[:, 1] = df.iloc[:, 1] > 0.5
        # Convert column 2 to string
        df.iloc[:, 2] = df.iloc[:, 2].to_string(index=False).split('\n')

        table = to_java(df)

        # Table types cannot be the same here, unless we want to cast.
        # assert_same_table(table, df)
        assert type(table) == jimport('org.scijava.table.DefaultGenericTable')
Пример #6
0
 def test_slice_int(self, ij_fixture, img):
     Views = sj.jimport("net.imglib2.view.Views")
     expected = Views.hyperSlice(img, 0, 0)
     actual = img[0]
     for i in range(3):
         for j in range(4):
             assert expected[i, j] == actual[i, j]
Пример #7
0
def get_dataframe(table):
    """
    Convert results table to pandas Dataframe.
    """
    Table = sj.jimport('org.scijava.table.Table')
    sci_table = ij.convert().convert(table, Table)

    return ij.py.from_java(sci_table)
Пример #8
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """
    global BoundedSoftRefLoaderCache
    BoundedSoftRefLoaderCache = scyjava.jimport(
        'net.imglib2.cache.ref.BoundedSoftRefLoaderCache')
    global GuardedStrongRefLoaderCache
    GuardedStrongRefLoaderCache = scyjava.jimport(
        'net.imglib2.cache.ref.GuardedStrongRefLoaderCache')
    global SoftRefLoaderCache
    SoftRefLoaderCache = scyjava.jimport(
        'net.imglib2.cache.ref.SoftRefLoaderCache')
    global WeakRefLoaderCache
    WeakRefLoaderCache = scyjava.jimport(
        'net.imglib2.cache.ref.WeakRefLoaderCache')
Пример #9
0
 def test_step_not_enough_dims(self, ij_fixture, img):
     # Create a stepped img via Views
     Views = sj.jimport("net.imglib2.view.Views")
     steps = JArray(JLong)([2, 1, 1])
     expected = Views.subsample(img, steps)
     expected = Views.dropSingletonDimensions(expected)
     # Create a stepped img via slicing notation
     actual = img[::2]
     for i in range(3):
         for j in range(4):
             assert expected[i, j] == actual[i, j]
Пример #10
0
 def test_slice_and_step(self, ij_fixture, img):
     # Create a stepped img via Views
     Views = sj.jimport("net.imglib2.view.Views")
     intervaled = Views.hyperSlice(img, 0, 0)
     steps = JArray(JLong)([1, 2])
     expected = Views.subsample(intervaled, steps)
     # Create a stepped img via slicing notation
     actual = img[:1, :, ::2]
     for i in range(3):
         for j in range(2):
             assert expected[i, j] == actual[i, j]
Пример #11
0
 def img(self):
     # Create img
     ArrayImgs = sj.jimport("net.imglib2.img.array.ArrayImgs")
     img = ArrayImgs.bytes(2, 3, 4)
     # Insert a different value into each index
     tmp_val = 1
     cursor = img.cursor()
     while cursor.hasNext():
         cursor.next().set(tmp_val)
         tmp_val += 1
     # Return the new img
     return img
Пример #12
0
 def testGentle(self):
     Object = jimport('java.lang.Object')
     unknown_thing = Object()
     converted_thing = to_python(unknown_thing, gentle=True)
     assert type(converted_thing) == Object
     bad_conversion = None
     try:
         bad_conversion = to_python(unknown_thing)
     except:
         # NB: Failure is expected here.
         pass
     self.assertIsNone(bad_conversion)
Пример #13
0
def process(image,
            detections: np.ndarray,
            add_to_roi_manager=True,
            multimeasure=True):
    """
    Process the blob rois.
    """
    # get ImageJ resoures
    ImagePlus = sj.jimport('ij.ImagePlus')
    OvalRoi = sj.jimport('ij.gui.OvalRoi')
    Overlay = sj.jimport('ij.gui.Overlay')
    ov = Overlay()

    # convert image to imp
    imp = ij.convert().convert(image, ImagePlus)

    if add_to_roi_manager:
        rm = ij.RoiManager().getRoiManager()

    for i in range(len(detections)):
        values = detections[i].tolist()
        y = values[0]
        x = values[1]
        r = values[2]
        d = r * 2
        roi = OvalRoi(x - r, y - r, d, d)
        imp.setRoi(roi)
        ov.add(roi)
        if add_to_roi_manager:
            rm.addRoi(roi)

    imp.setOverlay(ov)
    imp.show()

    if rm != None and multimeasure:
        rm.runCommand(imp, "Measure")
        return ij.ResultsTable.getResultsTable()

    return None
Пример #14
0
    def test_top_hat(self, ij_fixture):
        ArrayList = sj.jimport("java.util.ArrayList")
        HyperSphereShape = sj.jimport(
            "net.imglib2.algorithm.neighborhood.HyperSphereShape")
        Views = sj.jimport("net.imglib2.view.Views")

        result = []
        correct_result = [0, 0, 0, 1000, 2000, 4000, 7000, 12000, 20000, 33000]

        input_array = np.array([[1000, 1000, 1000, 2000, 3000],
                                [5000, 8000, 13000, 21000, 34000]])
        output_array = np.zeros(input_array.shape)
        java_out = Views.iterable(ij_fixture.py.to_java(output_array))
        java_in = ij_fixture.py.to_java(input_array)
        shapes = ArrayList()
        shapes.add(HyperSphereShape(5))

        ij_fixture.op().morphology().topHat(java_out, java_in, shapes)
        itr = java_out.iterator()
        while itr.hasNext():
            result.append(itr.next().get())

        assert result == correct_result
Пример #15
0
    def _get_img():
        # Create img
        CreateNamespace = sj.jimport("net.imagej.ops.create.CreateNamespace")
        dims = JArray(JLong)([1, 2, 3, 4, 5])
        ns = ij_fixture.op().namespace(CreateNamespace)
        img = ns.img(dims)

        # Populate img with random data
        cursor = img.cursor()
        while cursor.hasNext():
            val = random.random()
            cursor.next().set(val)

        return img
Пример #16
0
def java_labeling(ij_fixture):

    img = np.zeros((4, 4), dtype=np.int32)
    img[:2, :2] = 6
    img[:2, 2:] = 3
    img[2:, :2] = 7
    img[2:, 2:] = 4
    img_java = ij_fixture.py.to_java(img)
    sets = [[], [1], [2], [1, 2], [2, 3], [3], [1, 4], [3, 4]]
    sets = [set(l) for l in sets]
    sets_java = ij_fixture.py.to_java(sets)

    ImgLabeling = sj.jimport("net.imglib2.roi.labeling.ImgLabeling")
    return ImgLabeling.fromImageAndLabelSets(img_java, sets_java)
Пример #17
0
    def test_image_math(self, ij_fixture):
        Views = sj.jimport("net.imglib2.view.Views")

        input_array = np.array([[1, 1, 2], [3, 5, 8]])
        result = []
        correct_result = [192, 198, 205, 192, 198, 204]
        java_in = Views.iterable(ij_fixture.py.to_java(input_array))
        java_out = (ij_fixture.op().image().equation(
            java_in,
            "64 * (Math.sin(0.1 * p[0]) + Math.cos(0.1 * p[1])) + 128"))

        itr = java_out.iterator()
        while itr.hasNext():
            result.append(itr.next().get())
        assert result == correct_result
Пример #18
0
    def test_plugins_load_using_pairwise_stitching(self, ij_fixture):
        macro = """
        newImage("Tile1", "8-bit random", 512, 512, 1);
        newImage("Tile2", "8-bit random", 512, 512, 1);
        """
        plugin = 'Pairwise stitching'
        args = {'first_image': 'Tile1', 'second_image': 'Tile2'}

        ij_fixture.script().run('macro.ijm', macro, True).get()
        ij_fixture.py.run_plugin(plugin, args)
        WindowManager = sj.jimport('ij.WindowManager')
        result_name = WindowManager.getCurrentImage().getTitle()

        ij_fixture.script().run('macro.ijm', 'run("Close All");', True).get()

        assert result_name == 'Tile1<->Tile2'
Пример #19
0
    def testStructureWithSomeUnsupportedItems(self):
        # Create Java data structure with some challenging items.
        Object = jimport('java.lang.Object')
        jmap = to_java({
            'list': ['a', Object(), 1],
            'set': {'x', Object(), 2},
            'object': Object(),
            'foo': 'bar'
        })
        self.assertEqual('java.util.LinkedHashMap', jclass(jmap).getName())

        # Convert it back to Python.
        pdict = to_python(jmap)
        l = pdict['list']
        self.assertEqual(pdict['list'][0], 'a')
        assert type(pdict['list'][1]) == Object
        assert pdict['list'][2] == 1
        assert 'x' in pdict['set']
        assert 2 in pdict['set']
        assert len(pdict['set']) == 3
        assert type(pdict['object']) == Object
        self.assertEqual(pdict['foo'], 'bar')
Пример #20
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """

    # java
    global Random
    Random = scyjava.jimport('java.util.Random')

    # imglib
    try:
        global Helpers
        Helpers = scyjava.jimport('net.imglib2.python.Helpers')
        global NumpyToImgLibConversions
        NumpyToImgLibConversions = scyjava.jimport(
            'net.imglib2.python.NumpyToImgLibConversions')
        global NumpyToImgLibConversionsWithStride
        NumpyToImgLibConversionsWithStride = scyjava.jimport(
            'net.imglib2.python.NumpyToImgLibConversionsWithStride')
        global Views
        Views = scyjava.jimport('net.imglib2.view.Views')
    except TypeError as e:
        _logger.error(
            "Failed to import ImgLib2 helper classes. Please ensure imglib2-imglyb is present on the classpath."
        )
        raise e

    # Guard
    global ReferenceGuardingRandomAccessibleInterval
    ReferenceGuardingRandomAccessibleInterval = scyjava.jimport(
        'net.imglib2.python.ReferenceGuardingRandomAccessibleInterval')

    global numpy_dtype_to_conversion_method
    numpy_dtype_to_conversion_method = {
        np.dtype('complex64'): NumpyToImgLibConversions.toComplexFloat,
        np.dtype('complex128'): NumpyToImgLibConversions.toComplexDouble,
        np.dtype('float32'): NumpyToImgLibConversions.toFloat,
        np.dtype('float64'): NumpyToImgLibConversions.toDouble,
        np.dtype('int8'): NumpyToImgLibConversions.toByte,
        np.dtype('int16'): NumpyToImgLibConversions.toShort,
        np.dtype('int32'): NumpyToImgLibConversions.toInt,
        np.dtype('int64'): NumpyToImgLibConversions.toLong,
        np.dtype('uint8'): NumpyToImgLibConversions.toUnsignedByte,
        np.dtype('uint16'): NumpyToImgLibConversions.toUnsignedShort,
        np.dtype('uint32'): NumpyToImgLibConversions.toUnsignedInt,
        np.dtype('uint64'): NumpyToImgLibConversions.toUnsignedLong
    }

    global numpy_dtype_to_conversion_with_stride_method
    numpy_dtype_to_conversion_with_stride_method = {
        np.dtype('complex64'):
        NumpyToImgLibConversionsWithStride.toComplexFloat,
        np.dtype('complex128'):
        NumpyToImgLibConversionsWithStride.toComplexDouble,
        np.dtype('float32'): NumpyToImgLibConversionsWithStride.toFloat,
        np.dtype('float64'): NumpyToImgLibConversionsWithStride.toDouble,
        np.dtype('int8'): NumpyToImgLibConversionsWithStride.toByte,
        np.dtype('int16'): NumpyToImgLibConversionsWithStride.toShort,
        np.dtype('int32'): NumpyToImgLibConversionsWithStride.toInt,
        np.dtype('int64'): NumpyToImgLibConversionsWithStride.toLong,
        np.dtype('uint8'): NumpyToImgLibConversionsWithStride.toUnsignedByte,
        np.dtype('uint16'): NumpyToImgLibConversionsWithStride.toUnsignedShort,
        np.dtype('uint32'): NumpyToImgLibConversionsWithStride.toUnsignedInt,
        np.dtype('uint64'): NumpyToImgLibConversionsWithStride.toUnsignedLong
    }

    global ReferenceGuard

    @JImplements(
        'net.imglib2.python.ReferenceGuardingRandomAccessibleInterval$ReferenceHolder'
    )
    class ReferenceGuard():
        def __init__(self, *args, **kwargs):
            self.args = args

    global GenericMouseMotionListener

    @JImplements('java.awt.event.MouseMotionListener')
    class GenericMouseMotionListener():
        def __init__(self,
                     mouse_dragged=lambda e: None,
                     mouse_moved=lambda e: None):
            self.mouse_dragged = mouse_dragged
            self.mouse_moved = mouse_moved

        @JOverride
        def mouseDragged(self, e):
            self.mouse_dragged(e)

        @JOverride
        def mouseMoved(self, e):
            self.mouse_moved(e)

    global RunnableFromFunc

    @JImplements('java.lang.Runnable')
    class RunnableFromFunc():
        def __init__(self, func):
            self.func = func

        @JOverride
        def run(self):
            _logger.debug('Running function %s', self.func)
            self.func()
Пример #21
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """
    global PythonHelpers
    PythonHelpers = scyjava.jimport('net.imglib2.python.Helpers')

    # non-owning
    global _ByteUnsafe
    _ByteUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.ByteUnsafe')
    global _CharUnsafe
    _CharUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.CharUnsafe')
    global _DoubleUnsafe
    _DoubleUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.DoubleUnsafe')
    global _FloatUnsafe
    _FloatUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.FloatUnsafe')
    global _IntUnsafe
    _IntUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.IntUnsafe')
    global _LongUnsafe
    _LongUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.LongUnsafe')
    global _ShortUnsafe
    _ShortUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.ShortUnsafe')

    global _unsafe_for_dtype
    _unsafe_for_dtype = {
        np.dtype('complex64'): _FloatUnsafe,
        np.dtype('complex128'): _DoubleUnsafe,
        np.dtype('float32'): _FloatUnsafe,
        np.dtype('float64'): _DoubleUnsafe,
        np.dtype('int8'): _ByteUnsafe,
        np.dtype('int16'): _ShortUnsafe,
        np.dtype('int32'): _IntUnsafe,
        np.dtype('int64'): _LongUnsafe,
        np.dtype('uint8'): _ByteUnsafe,
        np.dtype('uint16'): _ShortUnsafe,
        np.dtype('uint32'): _IntUnsafe,
        np.dtype('uint64'): _LongUnsafe
    }

    # owning
    global _OwningByteUnsafe
    _OwningByteUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningByteUnsafe')
    global _OwningCharUnsafe
    _OwningCharUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningCharUnsafe')
    global _OwningDoubleUnsafe
    _OwningDoubleUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningDoubleUnsafe')
    global _OwningFloatUnsafe
    _OwningFloatUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningFloatUnsafe')
    global _OwningIntUnsafe
    _OwningIntUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningIntUnsafe')
    global _OwningLongUnsafe
    _OwningLongUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningLongUnsafe')
    global _OwningShortUnsafe
    _OwningShortUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.owning.OwningShortUnsafe')

    global _unsafe_owning_for_dtype
    _unsafe_owning_for_dtype = {
        np.dtype('complex64'): lambda size: _OwningFloatUnsafe(2 * size),
        np.dtype('complex128'): lambda size: _OwningDoubleUnsafe(2 * size),
        np.dtype('float32'): _OwningFloatUnsafe,
        np.dtype('float64'): _OwningDoubleUnsafe,
        np.dtype('int8'): _OwningByteUnsafe,
        np.dtype('int16'): _OwningShortUnsafe,
        np.dtype('int32'): _OwningIntUnsafe,
        np.dtype('int64'): _OwningLongUnsafe,
        np.dtype('uint8'): _OwningByteUnsafe,
        np.dtype('uint16'): _OwningShortUnsafe,
        np.dtype('uint32'): _OwningIntUnsafe,
        np.dtype('uint64'): _OwningLongUnsafe
    }

    global MakeAccessFunction

    @JImplements('java.util.function.LongFunction')
    class MakeAccessFunction():
        """
        Implements a java `LongFunction` that can be passed into `PythonHelpers.imgFromFunc` and
        `PythonHelpers.imgWithCellLoaderFromFunc`.
        """
        def __init__(self, func):
            self.func = func

        @JOverride
        def apply(self, index):
            access = self.func(index)
            return access
Пример #22
0
 def test_dtype(self, ij_fixture, img):
     assert hasattr(img, "dtype")
     ByteType = sj.jimport("net.imglib2.type.numeric.integer.ByteType")
     assert img.dtype == ByteType
Пример #23
0
def assert_permuted_rai_equal_to_source_rai(imgplus):
    # get java resources
    Axes = sj.jimport("net.imagej.axis.Axes")

    # define extra axes
    foo = Axes.get("foo")
    bar = Axes.get("bar")

    # permute the rai to python order
    axis_types = [axis.type() for axis in imgplus.dim_axes]
    permute_order = dims.prioritize_rai_axes_order(
        axis_types, dims._python_rai_ref_order())
    permuted_rai = dims.reorganize(imgplus, permute_order)

    # extract values for assertion
    oc = imgplus.dimensionIndex(Axes.CHANNEL)
    ox = imgplus.dimensionIndex(Axes.X)
    oy = imgplus.dimensionIndex(Axes.Y)
    oz = imgplus.dimensionIndex(Axes.Z)
    ot = imgplus.dimensionIndex(Axes.TIME)
    of = imgplus.dimensionIndex(foo)
    ob = imgplus.dimensionIndex(bar)

    nc = permuted_rai.dimensionIndex(Axes.CHANNEL)
    nx = permuted_rai.dimensionIndex(Axes.X)
    ny = permuted_rai.dimensionIndex(Axes.Y)
    nz = permuted_rai.dimensionIndex(Axes.Z)
    nt = permuted_rai.dimensionIndex(Axes.TIME)
    nf = permuted_rai.dimensionIndex(foo)
    nb = permuted_rai.dimensionIndex(bar)

    oc_len = imgplus.dimension(oc)
    ox_len = imgplus.dimension(ox)
    oy_len = imgplus.dimension(oy)
    oz_len = imgplus.dimension(oz)
    ot_len = imgplus.dimension(ot)
    of_len = imgplus.dimension(of)
    ob_len = imgplus.dimension(ob)

    nc_len = permuted_rai.dimension(nc)
    nx_len = permuted_rai.dimension(nx)
    ny_len = permuted_rai.dimension(ny)
    nz_len = permuted_rai.dimension(nz)
    nt_len = permuted_rai.dimension(nt)
    nf_len = permuted_rai.dimension(nf)
    nb_len = permuted_rai.dimension(nb)

    # assert the number of pixels of each dimension
    assert oc_len == nc_len
    assert ox_len == nx_len
    assert oy_len == ny_len
    assert oz_len == nz_len
    assert ot_len == nt_len
    assert of_len == nf_len
    assert ob_len == nb_len

    # get RandomAccess
    imgplus_access = imgplus.randomAccess()
    permuted_rai_access = permuted_rai.randomAccess()

    # assert pixels between source and permuted rai
    for c in range(oc_len):
        imgplus_access.setPosition(c, oc)
        permuted_rai_access.setPosition(c, nc)
        for x in range(ox_len):
            imgplus_access.setPosition(x, ox)
            permuted_rai_access.setPosition(x, nx)
            for y in range(oy_len):
                imgplus_access.setPosition(y, oy)
                permuted_rai_access.setPosition(y, ny)
                for z in range(oz_len):
                    imgplus_access.setPosition(z, oz)
                    permuted_rai_access.setPosition(z, nz)
                    for t in range(ot_len):
                        imgplus_access.setPosition(t, ot)
                        permuted_rai_access.setPosition(t, nt)
                        for f in range(of_len):
                            imgplus_access.setPosition(f, of)
                            permuted_rai_access.setPosition(f, nf)
                            for b in range(ob_len):
                                imgplus_access.setPosition(b, ob)
                                permuted_rai_access.setPosition(b, nb)
                                sample_name = f"C: {c}, X: {x}, Y: {y}, Z: {z}, T: {t}, F: {f}, B: {b}"
                                assert (imgplus_access.get() ==
                                        permuted_rai_access.get()), sample_name
Пример #24
0
 def test_slice_not_enough_dims(self, ij_fixture, img):
     Views = sj.jimport("net.imglib2.view.Views")
     expected = Views.hyperSlice(Views.hyperSlice(img, 0, 0), 0, 0)
     actual = img[0, 0]
     for i in range(4):
         assert expected[i] == actual[i]
Пример #25
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """
    Intervals = scyjava.jimport('net.imglib2.util.Intervals')
Пример #26
0
 def test_slice_1d_negative(self, ij_fixture, img):
     Views = sj.jimport("net.imglib2.view.Views")
     expected = Views.hyperSlice(Views.hyperSlice(img, 0, 1), 0, 1)
     actual = img[-1, -2, :]
     for i in range(4):
         assert expected[i] == actual[i]
Пример #27
0
        pointer = ctypes.cast(address, ctypes.POINTER(ctype_conversions_imglib[imglib_type]))
        order = 'C'

        obj = np.ndarray.__new__(cls, buffer=np.ctypeslib.as_array(pointer, shape=shape), shape=shape, dtype=dtype)
        obj.setflags(write=True)
        obj.rai = rai
        return obj

    def __array_finalize__(self, obj):
        if obj is None:
            return
        self.rai = obj.rai


if __name__ == "__main__":
    ArrayImgs = scyjava.jimport('net.imglib2.img.array.ArrayImgs')
    UnsafeUtil = scyjava.jimport('net.imglib2.img.basictypelongaccess.unsafe.UnsafeUtil')
    Arrays = scyjava.jimport('java.util.Arrays')
    OwningFloatUnsafe = scyjava.jimport('net.imglib2.img.basictypelongaccess.unsafe.owning.OwningFloatUnsafe')
    Fraction = scyjava.jimport('net.imglib2.util.Fraction')
    LongStream = scyjava.jimport('java.util.stream.LongStream')

    shape = (2, 3, 4)
    n_elements = int(np.prod(shape))
    data_store = OwningFloatUnsafe(n_elements)
    dim_array = LongStream.of(*shape).toArray()
    print(Arrays.toString(dim_array))
    rai = util.Helpers.toArrayImg(jpype.JObject(util.Helpers.className(data_store), data_store), dim_array)
    # rai = ArrayImgs.floats( *shape )
    c = rai.cursor()
    count = 23
Пример #28
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """

    global Accesses
    Accesses = scyjava.jimport('net.imglib2.img.basictypeaccess.Accesses')

    global ByteArray
    ByteArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.ByteArray')
    global CharArray
    CharArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.CharArray')
    global DoubleArray
    DoubleArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.DoubleArray')
    global FloatArray
    FloatArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.FloatArray')
    global IntArray
    IntArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.IntArray')
    global LongArray
    LongArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.LongArray')
    global ShortArray
    ShortArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.array.ShortArray')

    global VolatileByteArray
    VolatileByteArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileByteArray')
    global VolatileCharArray
    VolatileCharArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileCharArray')
    global VolatileDoubleArray
    VolatileDoubleArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileDoubleArray')
    global VolatileFloatArray
    VolatileFloatArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileFloatArray')
    global VolatileIntArray
    VolatileIntArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileIntArray')
    global VolatileLongArray
    VolatileLongArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileLongArray')
    global VolatileShortArray
    VolatileShortArray = scyjava.jimport(
        'net.imglib2.img.basictypeaccess.volatiles.array.VolatileShortArray')

    global ByteUnsafe
    ByteUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.ByteUnsafe')
    global CharUnsafe
    CharUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.CharUnsafe')
    global DoubleUnsafe
    DoubleUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.DoubleUnsafe')
    global FloatUnsafe
    FloatUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.FloatUnsafe')
    global IntUnsafe
    IntUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.IntUnsafe')
    global LongUnsafe
    LongUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.LongUnsafe')
    global ShortUnsafe
    ShortUnsafe = scyjava.jimport(
        'net.imglib2.img.basictypelongaccess.unsafe.ShortUnsafe')
Пример #29
0
 def disable_loci_logs():
     DebugTools = scyjava.jimport("loci.common.DebugTools")
     DebugTools.setRootLevel("WARN")
Пример #30
0
def _java_setup():
    """
    Lazy initialization function for Java-dependent data structures.
    Do not call this directly; use scyjava.start_jvm() instead.
    """

    global NativeType
    NativeType                = scyjava.jimport('net.imglib2.type.NativeType')

    global FloatType
    FloatType                 = scyjava.jimport('net.imglib2.type.numeric.real.FloatType')
    global DoubleType
    DoubleType                = scyjava.jimport('net.imglib2.type.numeric.real.DoubleType')
    global ByteType
    ByteType                  = scyjava.jimport('net.imglib2.type.numeric.integer.ByteType')
    global UnsignedByteType
    UnsignedByteType          = scyjava.jimport('net.imglib2.type.numeric.integer.UnsignedByteType')
    global ShortType
    ShortType                 = scyjava.jimport('net.imglib2.type.numeric.integer.ShortType')
    global UnsignedShortType
    UnsignedShortType         = scyjava.jimport('net.imglib2.type.numeric.integer.UnsignedShortType')
    global IntType
    IntType                   = scyjava.jimport('net.imglib2.type.numeric.integer.IntType')
    global UnsignedIntType
    UnsignedIntType           = scyjava.jimport('net.imglib2.type.numeric.integer.UnsignedIntType')
    global LongType
    LongType                  = scyjava.jimport('net.imglib2.type.numeric.integer.LongType')
    global UnsignedLongType
    UnsignedLongType          = scyjava.jimport('net.imglib2.type.numeric.integer.UnsignedLongType')

    global VolatileFloatType
    VolatileFloatType         = scyjava.jimport('net.imglib2.type.volatiles.VolatileFloatType')
    global VolatileDoubleType
    VolatileDoubleType        = scyjava.jimport('net.imglib2.type.volatiles.VolatileDoubleType')
    global VolatileByteType
    VolatileByteType          = scyjava.jimport('net.imglib2.type.volatiles.VolatileByteType')
    global VolatileUnsignedByteType
    VolatileUnsignedByteType  = scyjava.jimport('net.imglib2.type.volatiles.VolatileUnsignedByteType')
    global VolatileShortType
    VolatileShortType         = scyjava.jimport('net.imglib2.type.volatiles.VolatileShortType')
    global VolatileUnsignedShortType
    VolatileUnsignedShortType = scyjava.jimport('net.imglib2.type.volatiles.VolatileUnsignedShortType')
    global VolatileIntType
    VolatileIntType           = scyjava.jimport('net.imglib2.type.volatiles.VolatileIntType')
    global VolatileUnsignedIntType
    VolatileUnsignedIntType   = scyjava.jimport('net.imglib2.type.volatiles.VolatileUnsignedIntType')
    global VolatileLongType
    VolatileLongType          = scyjava.jimport('net.imglib2.type.volatiles.VolatileLongType')
    global VolatileUnsignedLongType
    VolatileUnsignedLongType  = scyjava.jimport('net.imglib2.type.volatiles.VolatileUnsignedLongType')