Exemplo n.º 1
0
 def test_09_05_get_active_image_display(self):
     svc = ij2.get_display_service(self.context)
     r = np.random.RandomState()
     r.seed(92)
     image = r.randint(0, 256, (11,13))
     ds = ij2.create_dataset(self.context, image, "Foo")
     svc.createDisplay("Foo", ds)
     ds = ij2.create_dataset(self.context, image, "Bar")
     display = svc.createDisplay("Bar", ds)
     svc.setActiveDisplay(display)
     self.assertEqual(svc.getActiveImageDisplay().getName(), "Bar")
Exemplo n.º 2
0
 def test_11_06_select_overlay(self):
     display_svc = ij2.get_display_service(self.context)
     overlay_svc = ij2.get_overlay_service(self.context)
     i, j = np.mgrid[0:15, 0:1900:100]
     image = i+j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = display_svc.createDisplay("Foo", ds)
     d2 = display_svc.createDisplay("Bar", ij2.create_dataset(self.context, image, "Bar"))
     mask = np.zeros(i.shape, bool)
     islice = slice(2,-3)
     jslice = slice(3,-4)
     mask[islice, jslice] = True
     overlay = ij2.create_overlay(self.context, mask)
     overlay_svc.addOverlays(display, J.make_list([overlay]))
     ij2.select_overlay(display.o, overlay)
Exemplo n.º 3
0
 def test_09_06_get_display_by_name(self):
     svc = ij2.get_display_service(self.context)
     r = np.random.RandomState()
     r.seed(92)
     image = r.randint(0, 256, (11,13))
     ds = ij2.create_dataset(self.context, image, "Foo")
     svc.createDisplay("Foo", ds)
     image = r.randint(0, 256, (14,12))
     ds2 = ij2.create_dataset(self.context, image, "Bar")
     display = svc.createDisplay("Bar", ds)
     svc.setActiveDisplay(display)
     display = svc.getDisplay("Foo")
     view = display.getActiveView()
     ds3 = ij2.wrap_interval(view.getData())
     self.assertSequenceEqual(ds3.dimensions(), [13, 11])
Exemplo n.º 4
0
    def run(self, workspace):
        '''Run the imageJ command'''
        image_set = workspace.image_set
        d = self.get_dictionary(workspace.image_set_list)
        if self.wants_to_set_current_image:
            input_image_name = self.current_input_image_name.value
            img = image_set.get_image(input_image_name, must_be_grayscale=True)
        else:
            img = None
        display_service = ij2.get_display_service(get_context())
        #
        # Run a command or macro on the first image of the set
        #
        if d.get(D_FIRST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_FIRST_IMAGE_SET)
        #
        # Install the input image as the current image
        #
        if img is not None:
            dataset = ij2.create_dataset(get_context(),
                                         img.pixel_data * IMAGEJ_SCALE,
                                         input_image_name)
            display = display_service.createDisplay(input_image_name, dataset)
            display_service.setActiveDisplay(display)

        self.do_imagej(workspace)
        #
        # Get the output image
        #
        if self.wants_to_get_current_image:
            output_image_name = self.current_output_image_name.value
            for attempt in range(4):
                display = display_service.getActiveImageDisplay()
                if display.o is not None:
                    break
                #
                # Possible synchronization problem with ImageJ 1.0
                # Possible error involving user changing window focus
                #
                import time
                time.sleep(.25)
            else:
                raise ValueError("Failed to retrieve active display")
            self.save_display_as_image(workspace, display, output_image_name)
        #
        # Execute the post-group macro or command
        #
        if d.get(D_LAST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_LAST_IMAGE_SET)
            #
            # Save the current ImageJ image after executing the post-group
            # command or macro
            #
            if (self.post_group_choice != CM_NOTHING
                    and self.wants_post_group_image):
                output_image_name = self.post_group_output_image.value
                output_image_name = self.current_output_image_name.value
                display = display_service.getActiveImageDisplay()
                self.save_display_as_image(workspace, display,
                                           output_image_name)
Exemplo n.º 5
0
 def test_09_03_set_active_display(self):
     svc = ij2.get_display_service(self.context)
     r = np.random.RandomState()
     r.seed(92)
     image = r.randint(0, 256, (11,13))
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = svc.createDisplay("Foo", ds)
     svc.setActiveDisplay(display)
Exemplo n.º 6
0
 def test_11_03_get_no_display_overlays(self):
     display_svc = ij2.get_display_service(self.context)
     overlay_svc = ij2.get_overlay_service(self.context)
     i, j = np.mgrid[0:15, 0:1900:100]
     image = i+j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = display_svc.createDisplay("Foo", ds)
     self.assertEqual(len(overlay_svc.getDisplayOverlays(display.o)), 0)
Exemplo n.º 7
0
 def test_09_07_is_unique_name(self):
     svc = ij2.get_display_service(self.context)
     r = np.random.RandomState()
     r.seed(92)
     image = r.randint(0, 256, (11,13))
     ds = ij2.create_dataset(self.context, image, "Foo")
     svc.createDisplay("Foo", ds)
     self.assertTrue(svc.isUniqueName("Bar"))
     self.assertFalse(svc.isUniqueName("Foo"))
Exemplo n.º 8
0
 def test_06_01_get_mask_data(self):
     # Get the overlay data from a display
     #
     display_svc = ij2.get_display_service(self.context)
     overlay_svc = ij2.get_overlay_service(self.context)
     image = np.zeros((30, 30))
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = display_svc.createDisplay("Foo", ds)
     d2 = display_svc.createDisplay("Bar", ij2.create_dataset(self.context, image, "Bar"))
     overlay = J.run_script(
         """var o = new Packages.imagej.data.overlay.RectangleOverlay(context.getContext());
            o.setOrigin(5, 0);
            o.setOrigin(3, 1);
            o.setExtent(6, 0);
            o.setExtent(7, 1);
            o;""", dict(context=self.context))
     overlay_svc.addOverlays(display, J.make_list([overlay]))
     ij2.select_overlay(display.o, overlay)
     mask = ij2.create_mask(display)
     i, j = np.mgrid[0:mask.shape[0], 0:mask.shape[1]]
     np.testing.assert_equal(mask, (j >= 5) & (j < 11) & (i >= 3) & (i < 10))
Exemplo n.º 9
0
    def run(self, workspace):
        '''Run the imageJ command'''
        image_set = workspace.image_set
        d = self.get_dictionary(workspace.image_set_list)
        if self.wants_to_set_current_image:
            input_image_name = self.current_input_image_name.value
            img = image_set.get_image(input_image_name,
                                      must_be_grayscale = True)
        else:
            img = None
        display_service = ij2.get_display_service(get_context())
        #
        # Run a command or macro on the first image of the set
        #
        if d.get(D_FIRST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_FIRST_IMAGE_SET)
        #
        # Install the input image as the current image
        #
        if img is not None:
            dataset = ij2.create_dataset(get_context(), 
                                         img.pixel_data * IMAGEJ_SCALE,
                                         input_image_name)
            display = display_service.createDisplay(
                input_image_name, dataset)
            display_service.setActiveDisplay(display)

        self.do_imagej(workspace)
        #
        # Get the output image
        #
        if self.wants_to_get_current_image:
            output_image_name = self.current_output_image_name.value
            display = display_service.getActiveImageDisplay()
            self.save_display_as_image(workspace, display, output_image_name)
        #
        # Execute the post-group macro or command
        #
        if d.get(D_LAST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_LAST_IMAGE_SET)
            #
            # Save the current ImageJ image after executing the post-group
            # command or macro
            #
            if (self.post_group_choice != CM_NOTHING and
                self.wants_post_group_image):
                output_image_name = self.post_group_output_image.value
                output_image_name = self.current_output_image_name.value
                display = display_service.getActiveImageDisplay()
                self.save_display_as_image(workspace, display, output_image_name)
Exemplo n.º 10
0
 def test_05_06_create_dataset(self):
     i,j = np.mgrid[:7, :9]
     image = (i+j*10).astype(float)
     ds = ij2.create_dataset(self.context, image, "Foo")
     imgplus = ds.getImgPlus()
     script = """
     var ra=imgplus.randomAccess();
     ra.setPosition(x, 0);
     ra.setPosition(y, 1);
     ra.get().get()"""
     fn = np.frompyfunc(
         lambda x, y: J.run_script(script, 
                                   dict(imgplus=imgplus, x=x, y=y)), 2, 1)
     pixel_data = fn(j, i)
     np.testing.assert_array_equal(image, pixel_data)
Exemplo n.º 11
0
 def test_09_08_check_stride(self):
     # Rotate the image by 90 degrees to make sure the pixel copy
     # was properly strided
     #
     svc = ij2.get_display_service(self.context)
     i, j = np.mgrid[0:5, 0:70:10]
     image = i + j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = svc.createDisplay("Foo", ds)
     outputs = dict(display=None)
     self.run_command("imagej.core.commands.rotate.Rotate90DegreesLeft",
                      dict(display=display), outputs)
     display_out = ij2.wrap_display(outputs["display"])
     dataset = ij2.wrap_dataset(display_out.getActiveView().getData())
     image_out = dataset.get_pixel_data()
     self.assertSequenceEqual(image_out.shape, list(reversed(image.shape)))
     np.testing.assert_array_equal(np.rot90(image), image_out)
Exemplo n.º 12
0
 def test_09_08_check_stride(self):
     # Rotate the image by 90 degrees to make sure the pixel copy
     # was properly strided
     #
     svc = ij2.get_display_service(self.context)
     i, j = np.mgrid[0:5, 0:70:10]
     image = i+j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = svc.createDisplay("Foo", ds)
     outputs = dict(display=None)
     self.run_command("imagej.core.commands.rotate.Rotate90DegreesLeft",
                      dict(display=display),
                      outputs)
     display_out = ij2.wrap_display(outputs["display"])
     dataset = ij2.wrap_dataset(display_out.getActiveView().getData())
     image_out = dataset.get_pixel_data()
     self.assertSequenceEqual(image_out.shape, list(reversed(image.shape)))
     np.testing.assert_array_equal(np.rot90(image), image_out)
Exemplo n.º 13
0
 def test_11_07_get_selection_bounds(self):
     display_svc = ij2.get_display_service(self.context)
     overlay_svc = ij2.get_overlay_service(self.context)
     i, j = np.mgrid[0:15, 0:1900:100]
     image = i+j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = display_svc.createDisplay("Foo", ds)
     mask = np.zeros(i.shape, bool)
     islice = slice(2,-3)
     jslice = slice(3,-4)
     mask[islice, jslice] = True
     overlay = ij2.create_overlay(self.context, mask)
     overlay_svc.addOverlays(display, J.make_list([overlay]))
     ij2.select_overlay(display.o, overlay)
     rect = overlay_svc.getSelectionBounds(display)
     self.assertEqual(J.get_field(rect, "x", "D"), 3)
     self.assertEqual(J.get_field(rect, "y", "D"), 2)
     self.assertEqual(J.get_field(rect, "width", "D"), 11)
     self.assertEqual(J.get_field(rect, "height", "D"), 9)
Exemplo n.º 14
0
 def test_09_09_check_overlay(self):
     svc = ij2.get_display_service(self.context)
     r = np.random.RandomState()
     i, j = np.mgrid[0:11, 0:1300:100]
     image = i+j
     ds = ij2.create_dataset(self.context, image, "Foo")
     display = svc.createDisplay("Foo", ds)
     mask = np.zeros(image.shape, bool)
     mask[2:-1, 3:-4] = 1
     overlay = ij2.create_overlay(self.context, mask)
     ij2.get_overlay_service(self.context).addOverlays(
         display.o, J.make_list([overlay]))
     ij2.select_overlay(display.o, overlay)
     self.run_command("imagej.core.commands.imglib.CropImage",
                      dict(display=display), {})
     dataset = ij2.wrap_dataset(display.getActiveView().getData())
     image_out = dataset.get_pixel_data()
     self.assertSequenceEqual(image_out.shape, [7, 5])
     np.testing.assert_array_equal(image[2:-2, 3:-5], image_out)
Exemplo n.º 15
0
    def test_09_02_create_display(self):
        svc = ij2.get_display_service(self.context)
        r = np.random.RandomState()
        r.seed(92)
        image = r.randint(0, 256, (11,13))
        ds = ij2.create_dataset(self.context, image, "Foo")
        display = svc.createDisplay("Foo", ds)
        self.assertEqual(display.size(), 1)
        self.assertFalse(display.isEmpty())
        self.assertFalse(display.contains(None))
        views = display.toArray()
        self.assertEqual(len(views), 1)

        self.assertTrue(display.canDisplay(ds.o))
        display.update()
        self.assertEqual(display.getName(), "Foo")
        display.setName("Bar")
        self.assertEqual(display.getName(), "Bar")
        display.getActiveView()
        display.getActiveAxis()
        display.getCanvas()
        display.setActiveAxis(ij2.Axes().X)
Exemplo n.º 16
0
    def execute_advanced_command(self, workspace, command, d):
        '''Execute an advanced command

        command - name of the command
        d - dictionary to be used to find settings
        '''
        context = get_context()
        self.get_command_settings(command, d)
        wants_display = self.show_window
        if wants_display:
            workspace.display_data.input_images = input_images = []
            workspace.display_data.output_images = output_images = []
        key = command.get_unicode_value()
        node = command.get_selected_leaf()
        module_info = node[2]

        input_dictionary = J.get_map_wrapper(
            J.make_instance('java/util/HashMap', "()V"))
        display_dictionary = {}
        display_service = ij2.get_display_service(context)
        for setting, module_item in d[key]:
            if isinstance(setting, cps.ImageNameProvider):
                continue
            field_name = module_item.getName()
            field_type = module_item.getType()
            raw_type = J.call(module_item.o, "getType", "()Ljava/lang/Class;")
            if field_type in (ij2.FT_BOOL, ij2.FT_INTEGER, ij2.FT_FLOAT,
                              ij2.FT_STRING):
                input_dictionary.put(field_name, J.box(setting.value,
                                                       raw_type))
            elif field_type == ij2.FT_COLOR:
                assert isinstance(setting, cps.Color)
                red, green, blue = setting.to_rgb()
                jobject = J.make_instance("imagej/util/ColorRGB", "(III)V",
                                          red, green, blue)
                input_dictionary.put(field_name, jobject)
            elif field_type == ij2.FT_IMAGE:
                image_name = setting.value
                image = workspace.image_set.get_image(image_name)
                pixel_data = image.pixel_data * IMAGEJ_SCALE

                dataset = ij2.create_dataset(context, pixel_data, image_name)
                display = display_service.createDisplay(image_name, dataset)
                display_dictionary[module_item.getName()] = display
                if image.has_mask:
                    #overlay_name = "X" + uuid.uuid4().get_hex()
                    #image_dictionary[overlay_name] = image.mask
                    overlay = ij2.create_overlay(context, image.mask)
                    overlay_service = ij2.get_overlay_service(context)
                    overlay_service.addOverlays(display.o,
                                                J.make_list([overlay]))
                    ij2.select_overlay(display.o, overlay)
                input_dictionary.put(field_name, display.o)
                if wants_display:
                    input_images.append((image_name, image.pixel_data))
            elif field_type == ij2.FT_TABLE:
                table_name = setting.value
                table = workspace.object_set.get_type_instance(
                    IJ_TABLE_TYPE, table_name)
                input_dictionary.put(field_name, table)
            elif field_type == ij2.FT_FILE:
                jfile = J.make_instance("java/io/File",
                                        "(Ljava/lang/String;)V", setting.value)
                input_dictionary.put(field_name, jfile)
        command_service = ij2.get_command_service(get_context())
        future = command_service.run(module_info.o, input_dictionary.o)
        module = future.get()
        for setting, module_item in d[key]:
            if isinstance(setting, cps.ImageNameProvider):
                name = module_item.getName()
                output_name = setting.value
                if display_dictionary.has_key(name):
                    display = display_dictionary[name]
                else:
                    display = IJ2.wrap_display(module.getOutput(name))
                pixel_data = self.save_display_as_image(
                    workspace, display, output_name)

                if wants_display:
                    output_images.append((output_name, pixel_data))
        # Close any displays that we created.
        for display in display_dictionary.values():
            display.close()
Exemplo n.º 17
0
    def run(self, workspace):
        '''Run the imageJ command'''
        image_set = workspace.image_set
        d = self.get_dictionary(workspace.image_set_list)
        if self.wants_to_set_current_image:
            input_image_name = self.current_input_image_name.value
            img = image_set.get_image(input_image_name,
                                      must_be_grayscale = True)
        else:
            img = None
        display_service = ij2.get_display_service(get_context())
        #
        # Run a command or macro on the first image of the set
        #
        if d.get(D_FIRST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_FIRST_IMAGE_SET)
        #
        # Install the input image as the current image
        #
        if img is not None:
            dataset = ij2.create_dataset(get_context(), 
                                         img.pixel_data * IMAGEJ_SCALE,
                                         input_image_name)
            display = display_service.createDisplay(
                input_image_name, dataset)
            display_service.setActiveDisplay(display)

        self.do_imagej(workspace)
        #
        # Get the output image
        #
        if self.wants_to_get_current_image:
            output_image_name = self.current_output_image_name.value
            for attempt in range(4):
                display = display_service.getActiveImageDisplay()
                if display.o is not None:
                    break
                #
                # Possible synchronization problem with ImageJ 1.0
                # Possible error involving user changing window focus
                #
                import time
                time.sleep(.25)
            else:
                raise ValueError("Failed to retrieve active display")
            self.save_display_as_image(workspace, display, output_image_name)
        #
        # Execute the post-group macro or command
        #
        if d.get(D_LAST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_LAST_IMAGE_SET)
            #
            # Save the current ImageJ image after executing the post-group
            # command or macro
            #
            if (self.post_group_choice != CM_NOTHING and
                self.wants_post_group_image):
                output_image_name = self.post_group_output_image.value
                output_image_name = self.current_output_image_name.value
                display = display_service.getActiveImageDisplay()
                self.save_display_as_image(workspace, display, output_image_name)
Exemplo n.º 18
0
 def inject_image(self, pixels, name=None):
     '''inject an image into ImageJ for processing'''
     dataset = IJ2.create_dataset(pixels, name)
     display_service = IJ2.get_display_service(self.context)
     display = display_service.createDisplay(dataset)
     display_service.setActiveDisplay(display.o)
Exemplo n.º 19
0
    def execute_advanced_command(self, workspace, command, d):
        '''Execute an advanced command

        command - name of the command
        d - dictionary to be used to find settings
        '''
        wants_display = workspace.frame is not None
        if wants_display:
            workspace.display_data.input_images = input_images = []
            workspace.display_data.output_images = output_images = []
        key = command.get_unicode_value()
        if bioformats.USE_IJ2:
            node = command.get_selected_leaf()
            module_info = node[2]
            module = IJ2.wrap_module(module_info.createModule())
            context = self.get_context()
            display_service = IJ2.get_display_service(context)
                
            display_dictionary = {}
            for setting, module_item in d[key]:
                field_type = module_item.getType()
                if isinstance(setting, cps.ImageNameProvider):
                    continue
                if field_type == IJ2.FT_BOOL:
                    value = J.make_instance("java/lang/Boolean",
                                            "(Z)V", setting.value)
                elif field_type == IJ2.FT_INTEGER:
                    value = J.make_instance("java/lang/Integer",
                                            "(I)V", setting.value)
                elif field_type == IJ2.FT_FLOAT:
                    value = J.make_instance("java/lang/Double",
                                            "(D)V", setting.value)
                elif field_type == IJ2.FT_STRING:
                    value = setting.value
                elif field_type == IJ2.FT_COLOR:
                    value = IJ2.make_color_rgb_from_html(setting.value)
                elif field_type == IJ2.FT_IMAGE:
                    image_name = setting.value
                    image = workspace.image_set.get_image(image_name)
                    dataset = IJ2.create_dataset(image.pixel_data,
                                                 setting.value)
                    display = display_service.createDisplay(dataset)
                    if image.has_mask:
                        overlay = IJ2.create_overlay(image.mask)
                        display.displayOverlay(overlay)
                    value = display
                    display_dictionary[module_item.getName()] = display
                    if wants_display:
                        input_images.append((image_name, image.pixel_data))
                module.setInput(module_item.getName(), value)
            module_service = IJ2.get_module_service(context)
            module_service.run(module)
            for setting, module_item in d[key]:
                if isinstance(setting, cps.ImageNameProvider):
                    name = module_item.getName()
                    output_name = setting.value
                    if display_dictionary.has_key(name):
                        display = display_dictionary[name]
                    else:
                        display = IJ2.wrap_display(module.getOutput(name))
                    ds = display_service.getActiveDataset(display)
                    pixel_data = ds.get_pixel_data()
                    image = cpi.Image(pixel_data)
                    workspace.image_set.add(output_name, image)
                    if wants_display:
                        output_images.append((output_name, pixel_data))
            for display in display_dictionary.values():
                panel = IJ2.wrap_display_panel(display.getDisplayPanel())
                panel.close()
        else:
            from imagej.imageplus import make_imageplus_from_processor
            from imagej.imageplus import get_imageplus_wrapper
            from imagej.imageprocessor import make_image_processor
            from imagej.imageprocessor import get_image
            
            command = command.value
            settings = d[command]
            classname = self.get_cached_commands()[command]
            plugin = M.get_plugin(classname)
            fp_in = P.get_input_fields_and_parameters(plugin)
            result = []
            image_set = workspace.image_set
            assert isinstance(image_set, cpi.ImageSet)
            for (field, parameter), setting in zip(fp_in, settings[:len(fp_in)]):
                field_type = P.get_field_type(field)
                label = parameter.label() or ""
                if field_type == P.FT_IMAGE:
                    image_name = setting.value
                    image = workspace.image_set.get_image(image_name,
                                                          must_be_grayscale = True)
                    pixel_data = (image.pixel_data * 255.0).astype(np.float32)
                    if wants_display:
                        input_images.append((image_name, pixel_data / 255.0))
                    processor = make_image_processor(pixel_data)
                    image_plus = make_imageplus_from_processor(image_name, processor)
                    field.set(plugin, image_plus)
                    del image_plus
                    del processor
                elif field_type == P.FT_INTEGER:
                    field.setInt(plugin, setting.value)
                elif field_type == P.FT_FLOAT:
                    field.setFloat(plugin, setting.value)
                elif field_type == P.FT_BOOL:
                    field.setBoolean(plugin, setting.value)
                else:
                    field.set(plugin, setting.value)
            #
            # There are two ways to run this:
            # * Batch - just call plugin.run()
            # * Interactive - use PlugInFunctions.runInteractively
            #
            if self.pause_before_proceeding:
                J.execute_runnable_in_main_thread(J.run_script(
                    """new java.lang.Runnable() { run:function() {
                        importClass(Packages.imagej.plugin.PlugInFunctions);
                        PlugInFunctions.runInteractively(plugin);
                    }};""", dict(plugin=plugin)), True)
            else:
                J.execute_runnable_in_main_thread(plugin, True)
            setting_idx = len(fp_in)
            fp_out = P.get_output_fields_and_parameters(plugin)
            for field, parameter in fp_out:
                field_type = P.get_field_type(field)
                if field_type == P.FT_IMAGE:
                    image_name = settings[setting_idx].value
                    setting_idx += 1
                    image_plus = get_imageplus_wrapper(field.get(plugin))
                    processor = image_plus.getProcessor()
                    pixel_data = get_image(processor).astype(np.float32) / 255.0
                    if wants_display:
                        output_images.append((image_name, pixel_data))
                    image = cpi.Image(pixel_data)
                    image_set.add(image_name, image)
Exemplo n.º 20
0
 def inject_image(self, pixels, name=None):
     '''inject an image into ImageJ for processing'''
     dataset = IJ2.create_dataset(pixels, name)
     display_service = IJ2.get_display_service(self.context)
     display = display_service.createDisplay(dataset)
     display_service.setActiveDisplay(display.o)
Exemplo n.º 21
0
    def run(self, workspace):
        """Run the imageJ command"""
        image_set = workspace.image_set
        d = self.get_dictionary(workspace.image_set_list)
        if self.wants_to_set_current_image:
            input_image_name = self.current_input_image_name.value
            img = image_set.get_image(input_image_name, must_be_grayscale=True)
            if self.show_window:
                workspace.display_data.image_sent_to_ij = img.pixel_data
        else:
            img = None
        display_service = ij2.get_display_service(get_context())
        #
        # Run a command or macro on the first image of the set
        #
        if d.get(D_FIRST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_FIRST_IMAGE_SET)
        ij1_mode = self.command_or_macro == CM_MACRO
        #
        # Install the input image as the current image
        #
        if img is not None:
            ijpixels = img.pixel_data * IMAGEJ_SCALE
            if ij1_mode:
                ij_processor = ijiproc.make_image_processor(ijpixels.astype("float32"))
                image_plus = ijip.make_imageplus_from_processor(input_image_name, ij_processor)
                ijwm.set_current_image(image_plus)
            else:
                dataset = ij2.create_dataset(get_context(), ijpixels, input_image_name)
                display = display_service.createDisplay(input_image_name, dataset)
                display_service.setActiveDisplay(display)

        self.do_imagej(workspace)
        #
        # Get the output image
        #
        if self.wants_to_get_current_image:
            output_image_name = self.current_output_image_name.value
            if ij1_mode:
                image_plus = ijwm.get_current_image()
                ij_processor = image_plus.getProcessor()
                pixels = ijiproc.get_image(ij_processor).astype("float32") / IMAGEJ_SCALE
                image = cpi.Image(pixels)
                workspace.image_set.add(output_image_name, image)
            else:
                for attempt in range(4):
                    display = display_service.getActiveImageDisplay()
                    if display.o is not None:
                        break
                    #
                    # Possible synchronization problem with ImageJ 1.0
                    # Possible error involving user changing window focus
                    #
                    import time

                    time.sleep(0.25)
                else:
                    raise ValueError("Failed to retrieve active display")
                pixels = self.save_display_as_image(workspace, display, output_image_name)
            if self.show_window:
                workspace.display_data.image_acquired_from_ij = pixels
        #
        # Execute the post-group macro or command
        #
        if d.get(D_LAST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_LAST_IMAGE_SET)
            #
            # Save the current ImageJ image after executing the post-group
            # command or macro
            #
            if self.post_group_choice != CM_NOTHING and self.wants_post_group_image:
                output_image_name = self.post_group_output_image.value
                if ij1_mode:
                    image_plus = ijwm.get_current_image()
                    ij_processor = image_plus.getProcessor()
                    pixels = ijiproc.get_image(ij_processor).astype("float32") / IMAGEJ_SCALE
                    image = cpi.Image(pixels, mask=mask)
                    workspace.image_set.add(output_image_name, image)
                else:
                    display = display_service.getActiveImageDisplay()
                    self.save_display_as_image(workspace, display, output_image_name)
Exemplo n.º 22
0
    def run(self, workspace):
        '''Run the imageJ command'''
        image_set = workspace.image_set
        d = self.get_dictionary(workspace.image_set_list)
        if self.wants_to_set_current_image:
            input_image_name = self.current_input_image_name.value
            img = image_set.get_image(input_image_name, must_be_grayscale=True)
            if self.show_window:
                workspace.display_data.image_sent_to_ij = img.pixel_data
        else:
            img = None
        display_service = ij2.get_display_service(get_context())
        #
        # Run a command or macro on the first image of the set
        #
        if d.get(D_FIRST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_FIRST_IMAGE_SET)
        ij1_mode = self.command_or_macro == CM_MACRO
        #
        # Install the input image as the current image
        #
        if img is not None:
            ijpixels = img.pixel_data * IMAGEJ_SCALE
            if ij1_mode:
                ij_processor = ijiproc.make_image_processor(
                    ijpixels.astype('float32'))
                image_plus = ijip.make_imageplus_from_processor(
                    input_image_name, ij_processor)
                ijwm.set_current_image(image_plus)
            else:
                dataset = ij2.create_dataset(get_context(), ijpixels,
                                             input_image_name)
                display = display_service.createDisplay(
                    input_image_name, dataset)
                display_service.setActiveDisplay(display)

        self.do_imagej(workspace)
        #
        # Get the output image
        #
        if self.wants_to_get_current_image:
            output_image_name = self.current_output_image_name.value
            if ij1_mode:
                image_plus = ijwm.get_current_image()
                ij_processor = image_plus.getProcessor()
                pixels = ijiproc.get_image(ij_processor).\
                    astype('float32') / IMAGEJ_SCALE
                image = cpi.Image(pixels)
                workspace.image_set.add(output_image_name, image)
            else:
                for attempt in range(4):
                    display = display_service.getActiveImageDisplay()
                    if display.o is not None:
                        break
                    #
                    # Possible synchronization problem with ImageJ 1.0
                    # Possible error involving user changing window focus
                    #
                    import time
                    time.sleep(.25)
                else:
                    raise ValueError("Failed to retrieve active display")
                pixels = self.save_display_as_image(workspace, display,
                                                    output_image_name)
            if self.show_window:
                workspace.display_data.image_acquired_from_ij = pixels
        #
        # Execute the post-group macro or command
        #
        if d.get(D_LAST_IMAGE_SET) == image_set.image_number:
            self.do_imagej(workspace, D_LAST_IMAGE_SET)
            #
            # Save the current ImageJ image after executing the post-group
            # command or macro
            #
            if (self.post_group_choice != CM_NOTHING
                    and self.wants_post_group_image):
                output_image_name = self.post_group_output_image.value
                if ij1_mode:
                    image_plus = ijwm.get_current_image()
                    ij_processor = image_plus.getProcessor()
                    pixels = ijiproc.get_image(ij_processor).\
                        astype('float32') / IMAGEJ_SCALE
                    image = cpi.Image(pixels, mask=mask)
                    workspace.image_set.add(output_image_name, image)
                else:
                    display = display_service.getActiveImageDisplay()
                    self.save_display_as_image(workspace, display,
                                               output_image_name)
Exemplo n.º 23
0
    def execute_advanced_command(self, workspace, command, d):
        '''Execute an advanced command

        command - name of the command
        d - dictionary to be used to find settings
        '''
        context = get_context()
        self.get_command_settings(command, d)
        wants_display = self.show_window
        if wants_display:
            workspace.display_data.input_images = input_images = []
            workspace.display_data.output_images = output_images = []
        key = command.get_unicode_value()
        node = command.get_selected_leaf()
        module_info = node[2]
        
        input_dictionary = J.get_map_wrapper(
            J.make_instance('java/util/HashMap', "()V"))
        display_dictionary = {}
        display_service = ij2.get_display_service(context)
        for setting, module_item in d[key]:
            if isinstance(setting, cps.ImageNameProvider):
                continue
            field_name = module_item.getName()
            field_type = module_item.getType()
            raw_type = J.call(module_item.o, "getType", "()Ljava/lang/Class;")
            if field_type in (ij2.FT_BOOL, ij2.FT_INTEGER, ij2.FT_FLOAT,
                              ij2.FT_STRING):
                input_dictionary.put(field_name, J.box(setting.value, raw_type))
            elif field_type == ij2.FT_COLOR:
                assert isinstance(setting, cps.Color)
                red, green, blue = setting.to_rgb()
                jobject = J.make_instance(
                    "imagej/util/ColorRGB", "(III)V", red, green, blue)
                input_dictionary.put(field_name, jobject)
            elif field_type == ij2.FT_IMAGE:
                image_name = setting.value
                image = workspace.image_set.get_image(image_name)
                pixel_data = image.pixel_data * IMAGEJ_SCALE
                
                dataset = ij2.create_dataset(
                    context, pixel_data, image_name)
                display = display_service.createDisplay(image_name, dataset)
                display_dictionary[module_item.getName()] = display 
                if image.has_mask:
                    #overlay_name = "X" + uuid.uuid4().get_hex()
                    #image_dictionary[overlay_name] = image.mask
                    overlay = ij2.create_overlay(context, image.mask)
                    overlay_service = ij2.get_overlay_service(context)
                    overlay_service.addOverlays(
                        display.o, J.make_list([overlay]))
                    ij2.select_overlay(display.o, overlay)
                input_dictionary.put(field_name, display.o)
                if wants_display:
                    input_images.append((image_name, image.pixel_data))
            elif field_type == ij2.FT_TABLE:
                table_name = setting.value
                table = workspace.object_set.get_type_instance(
                    IJ_TABLE_TYPE, table_name)
                input_dictionary.put(field_name, table)
            elif field_type == ij2.FT_FILE:
                jfile = J.make_instance(
                    "java/io/File", "(Ljava/lang/String;)V", setting.value)
                input_dictionary.put(field_name, jfile)
        command_service = ij2.get_command_service(get_context())
        future = command_service.run(module_info.o, input_dictionary.o)
        module = future.get()
        for setting, module_item in d[key]:
            if isinstance(setting, cps.ImageNameProvider):
                name = module_item.getName()
                output_name = setting.value
                if display_dictionary.has_key(name):
                    display = display_dictionary[name]
                else:
                    display = IJ2.wrap_display(module.getOutput(name))
                pixel_data = self.save_display_as_image(
                    workspace, display, output_name)
                
                if wants_display:
                    output_images.append((output_name, pixel_data))
        # Close any displays that we created.
        for display in display_dictionary.values():
            display.close()
Exemplo n.º 24
0
    def execute_advanced_command(self, workspace, command, d):
        '''Execute an advanced command

        command - name of the command
        d - dictionary to be used to find settings
        '''
        wants_display = workspace.frame is not None
        if wants_display:
            workspace.display_data.input_images = input_images = []
            workspace.display_data.output_images = output_images = []
        key = command.get_unicode_value()
        if bioformats.USE_IJ2:
            node = command.get_selected_leaf()
            module_info = node[2]
            module = IJ2.wrap_module(module_info.createModule())
            context = self.get_context()
            display_service = IJ2.get_display_service(context)

            display_dictionary = {}
            for setting, module_item in d[key]:
                field_type = module_item.getType()
                if isinstance(setting, cps.ImageNameProvider):
                    continue
                if field_type == IJ2.FT_BOOL:
                    value = J.make_instance("java/lang/Boolean", "(Z)V",
                                            setting.value)
                elif field_type == IJ2.FT_INTEGER:
                    value = J.make_instance("java/lang/Integer", "(I)V",
                                            setting.value)
                elif field_type == IJ2.FT_FLOAT:
                    value = J.make_instance("java/lang/Double", "(D)V",
                                            setting.value)
                elif field_type == IJ2.FT_STRING:
                    value = setting.value
                elif field_type == IJ2.FT_COLOR:
                    value = IJ2.make_color_rgb_from_html(setting.value)
                elif field_type == IJ2.FT_IMAGE:
                    image_name = setting.value
                    image = workspace.image_set.get_image(image_name)
                    dataset = IJ2.create_dataset(image.pixel_data,
                                                 setting.value)
                    display = display_service.createDisplay(dataset)
                    if image.has_mask:
                        overlay = IJ2.create_overlay(image.mask)
                        display.displayOverlay(overlay)
                    value = display
                    display_dictionary[module_item.getName()] = display
                    if wants_display:
                        input_images.append((image_name, image.pixel_data))
                module.setInput(module_item.getName(), value)
            module_service = IJ2.get_module_service(context)
            module_service.run(module)
            for setting, module_item in d[key]:
                if isinstance(setting, cps.ImageNameProvider):
                    name = module_item.getName()
                    output_name = setting.value
                    if display_dictionary.has_key(name):
                        display = display_dictionary[name]
                    else:
                        display = IJ2.wrap_display(module.getOutput(name))
                    ds = display_service.getActiveDataset(display)
                    pixel_data = ds.get_pixel_data()
                    image = cpi.Image(pixel_data)
                    workspace.image_set.add(output_name, image)
                    if wants_display:
                        output_images.append((output_name, pixel_data))
            for display in display_dictionary.values():
                panel = IJ2.wrap_display_panel(display.getDisplayPanel())
                panel.close()
        else:
            from imagej.imageplus import make_imageplus_from_processor
            from imagej.imageplus import get_imageplus_wrapper
            from imagej.imageprocessor import make_image_processor
            from imagej.imageprocessor import get_image

            command = command.value
            settings = d[command]
            classname = self.get_cached_commands()[command]
            plugin = M.get_plugin(classname)
            fp_in = P.get_input_fields_and_parameters(plugin)
            result = []
            image_set = workspace.image_set
            assert isinstance(image_set, cpi.ImageSet)
            for (field, parameter), setting in zip(fp_in,
                                                   settings[:len(fp_in)]):
                field_type = P.get_field_type(field)
                label = parameter.label() or ""
                if field_type == P.FT_IMAGE:
                    image_name = setting.value
                    image = workspace.image_set.get_image(
                        image_name, must_be_grayscale=True)
                    pixel_data = (image.pixel_data * 255.0).astype(np.float32)
                    if wants_display:
                        input_images.append((image_name, pixel_data / 255.0))
                    processor = make_image_processor(pixel_data)
                    image_plus = make_imageplus_from_processor(
                        image_name, processor)
                    field.set(plugin, image_plus)
                    del image_plus
                    del processor
                elif field_type == P.FT_INTEGER:
                    field.setInt(plugin, setting.value)
                elif field_type == P.FT_FLOAT:
                    field.setFloat(plugin, setting.value)
                elif field_type == P.FT_BOOL:
                    field.setBoolean(plugin, setting.value)
                else:
                    field.set(plugin, setting.value)
            #
            # There are two ways to run this:
            # * Batch - just call plugin.run()
            # * Interactive - use PlugInFunctions.runInteractively
            #
            if self.pause_before_proceeding:
                J.static_call('imagej/plugin/PlugInFunctions',
                              'runInteractively', '(Ljava/lang/Runnable)V',
                              plugin)
            else:
                J.call(plugin, 'run', '()V')
            setting_idx = len(fp_in)
            fp_out = P.get_output_fields_and_parameters(plugin)
            for field, parameter in fp_out:
                field_type = P.get_field_type(field)
                if field_type == P.FT_IMAGE:
                    image_name = settings[setting_idx].value
                    setting_idx += 1
                    image_plus = get_imageplus_wrapper(field.get(plugin))
                    processor = image_plus.getProcessor()
                    pixel_data = get_image(processor).astype(
                        np.float32) / 255.0
                    if wants_display:
                        output_images.append((image_name, pixel_data))
                    image = cpi.Image(pixel_data)
                    image_set.add(image_name, image)