def do_imagej(self, workspace, when=None): if when == D_FIRST_IMAGE_SET: choice = self.prepare_group_choice.value command = self.prepare_group_command macro = self.prepare_group_macro.value d = self.pre_command_settings_dictionary elif when == D_LAST_IMAGE_SET: choice = self.post_group_choice.value command = self.post_group_command macro = self.post_group_macro.value d = self.pre_command_settings_dictionary else: choice = self.command_or_macro.value command = self.command macro = self.macro.value d = self.command_settings_dictionary if choice == CM_COMMAND: self.execute_advanced_command(workspace, command, d) elif choice == CM_MACRO: macro = workspace.measurements.apply_metadata(macro) script_service = ij2.get_script_service(get_context()) factory = script_service.getByName(self.macro_language.value) engine = factory.getScriptEngine() engine.put("ImageJ", get_context()) result = engine.evalS(macro) if (choice != CM_NOTHING and (not cpprefs.get_headless()) and self.pause_before_proceeding): import wx wx.MessageBox("Please edit the image in ImageJ and hit OK to proceed", "Waiting for ImageJ")
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)
def do_imagej(self, workspace, when=None): if when == D_FIRST_IMAGE_SET: choice = self.prepare_group_choice.value command = self.prepare_group_command macro = self.prepare_group_macro.value d = self.pre_command_settings_dictionary elif when == D_LAST_IMAGE_SET: choice = self.post_group_choice.value command = self.post_group_command macro = self.post_group_macro.value d = self.pre_command_settings_dictionary else: choice = self.command_or_macro.value command = self.command macro = self.macro.value d = self.command_settings_dictionary if choice == CM_COMMAND: self.execute_advanced_command(workspace, command, d) elif choice == CM_MACRO: macro = workspace.measurements.apply_metadata(macro) script_service = ij2.get_script_service(get_context()) factory = script_service.getByName(self.macro_language.value) engine = factory.getScriptEngine() engine.put("ImageJ", get_context()) result = engine.evalS(macro) if (choice != CM_NOTHING and (not cpprefs.get_headless()) and self.pause_before_proceeding): import wx wx.MessageBox( "Please edit the image in ImageJ and hit OK to proceed", "Waiting for ImageJ")
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)
def on_show_imagej(self): """Show the ImageJ user interface This method shows the ImageJ user interface when the user presses the Show ImageJ button. """ logger.debug("Starting ImageJ UI") ui_service = ij2.get_ui_service(get_context()) if ui_service is not None and not ui_service.isVisible(): if cpprefs.get_headless(): # Silence the auto-updater in the headless preferences # ij2.update_never_remind() ui_service.createUI() elif ui_service is not None: ui = ui_service.getDefaultUI() J.execute_runnable_in_main_thread( J.run_script( """new java.lang.Runnable() { run: function() { ui.getApplicationFrame().setVisible(true); }}""", dict(ui=ui), ), True, )
def on_show_imagej(self): '''Show the ImageJ user interface This method shows the ImageJ user interface when the user presses the Show ImageJ button. ''' ui_service = ij2.get_ui_service(get_context()) if ui_service is not None and not ui_service.isVisible(): ui_service.createUI()
def get_choice_tree(self): '''Get the ImageJ command choices for the TreeChoice control The menu items are augmented with a third tuple entry which is the ModuleInfo for the command. ''' global cached_choice_tree global cached_commands if cached_choice_tree is not None: return cached_choice_tree tree = [] context = get_context() module_service = ij2.get_module_service(context) for module_info in module_service.getModules(): if module_info.getMenuRoot() != "app": continue logger.info("Processing module %s" % module_info.getClassName()) menu_path = module_info.getMenuPath() if menu_path is None or J.call(menu_path, "size", "()I") == 0: continue current_tree = tree # # The menu path is a collection of MenuEntry # for item in J.iterate_collection(menu_path): menu_entry = ij2.wrap_menu_entry(item) name = menu_entry.getName() weight = menu_entry.getWeight() matches = [node for node in current_tree if node[0] == name] if len(matches) > 0: current_node = matches[0] else: current_node = [name, [], None, weight] current_tree.append(current_node) current_tree = current_node[1] # mark the leaf. current_node[2] = module_info def sort_tree(tree): '''Recursively sort a tree in-place''' for node in tree: if node[1] is not None: sort_tree(node[1]) tree.sort(lambda node1, node2: cmp(node1[-1], node2[-1])) sort_tree(tree) cached_choice_tree = tree return cached_choice_tree
def on_show_imagej(self): '''Show the ImageJ user interface This method shows the ImageJ user interface when the user presses the Show ImageJ button. ''' logger.debug("Starting ImageJ UI") ui_service = ij2.get_ui_service(get_context()) if ui_service is not None and not ui_service.isVisible(): if cpprefs.get_headless(): # Silence the auto-updater in the headless preferences # ij2.update_never_remind() ui_service.createUI()
def on_show_imagej(self): '''Show the ImageJ user interface This method shows the ImageJ user interface when the user presses the Show ImageJ button. ''' logger.debug("Starting ImageJ UI") ui_service = ij2.get_ui_service(get_context()) if ui_service is not None and not ui_service.isVisible(): if cpprefs.get_headless(): # Silence the auto-updater in the headless preferences # ij2.update_never_remind() ui_service.createUI() elif ui_service is not None: ui = ui_service.getDefaultUI() J.execute_runnable_in_main_thread( J.run_script( """new java.lang.Runnable() { run: function() { ui.getApplicationFrame().setVisible(true); }}""", dict(ui=ui)), True)
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)
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)
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)
def create_settings(self): '''Create the settings for the module''' logger.debug("Creating RunImageJ module settings") J.activate_awt() logger.debug("Activated AWT") self.command_or_macro = cps.Choice("Run an ImageJ command or macro?", [CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" This setting determines whether <b>RunImageJ</b> runs either a: <ul> <li><i>%(CM_COMMAND)s:</i> Select from a list of available ImageJ commands (those items contained in the ImageJ menus); or</li> <li><i>%(CM_SCRIPT)s:</i> A script written in one of ImageJ 2.0's supported scripting languages.</li> <li><i>%(CM_MACRO)s:</i> An ImageJ 1.x macro, written in the ImageJ 1.x macro language. <b>Run_ImageJ</b> runs ImageJ in 1.x compatability mode.</li> </ul>""" % globals()) # # Load the commands in visible_settings so that we don't call # ImageJ unless someone tries the module # self.command = self.make_command_choice("Command", doc=""" <i>(Used only if running a %(CM_COMMAND)s)</i><br> The command to execute when the module runs.""" % globals()) self.command_settings_dictionary = {} self.command_settings = [] self.command_settings_count = cps.HiddenCount( self.command_settings, "Command settings count") self.pre_command_settings_dictionary = {} self.pre_command_settings = [] self.pre_command_settings_count = cps.HiddenCount( self.pre_command_settings, "Prepare group command settings count") self.post_command_settings_dictionary = {} self.post_command_settings = [] self.post_command_settings_count = cps.HiddenCount( self.post_command_settings, "Post-group command settings count") self.macro = cps.Text("Macro", """import imagej.command.CommandService; cmdSvcClass = CommandService.class; cmdSvc = ImageJ.getService(cmdSvcClass); cmdSvc.run("imagej.core.commands.assign.InvertDataValues", new Object [] {"allPlanes", true}).get();""", multiline=True, doc=""" <i>(Used only if running a %(CM_MACRO)s)</i><br> This is the ImageJ macro to be executed. The syntax for ImageJ macros depends on the scripting language engine chosen. We suggest that you use the Beanshell scripting language <a href="http://www.beanshell.org/manual/contents.html"> (Beanshell documentation)</a>.""" % globals()) all_engines = ij2.get_script_service(get_context()).getLanguages() self.language_dictionary = dict([(engine.getLanguageName(), engine) for engine in all_engines]) self.macro_language = cps.Choice( "Macro language", choices=self.language_dictionary.keys(), doc=""" This setting chooses the scripting language used to execute any macros in this module""") self.wants_to_set_current_image = cps.Binary( "Input the currently active image in ImageJ?", True, doc=""" Select <i>%(YES)s</i> if you want to set the currently active ImageJ image using an image from a prior CellProfiler module. <p>Select <i>%(NO)s</i> to use the currently active image in ImageJ. You may want to do this if you have an output image from a prior <b>RunImageJ</b> that you want to perform further operations upon before retrieving the final result back to CellProfiler.</p>""" % globals()) self.current_input_image_name = cps.ImageNameSubscriber( "Select the input image", doc=""" <i>(Used only if setting the currently active image)</i><br> This is the CellProfiler image that will become ImageJ's currently active image. The ImageJ commands and macros in this module will perform their operations on this image. You may choose any image produced by a prior CellProfiler module.""") self.wants_to_get_current_image = cps.Binary( "Retrieve the currently active image from ImageJ?", True, doc=""" Select <i>%(YES)s</i> if you want to retrieve ImageJ's currently active image after running the command or macro. <p>Select <i>%(NO)s</i> if the pipeline does not need to access the current ImageJ image. For example, you might want to run further ImageJ operations with additional <b>RunImageJ</b> upon the current image prior to retrieving the final image back to CellProfiler.</p>""" % globals()) self.current_output_image_name = cps.ImageNameProvider( "Name the current output image", "ImageJImage", doc=""" <i>(Used only if retrieving the currently active image from ImageJ)</i><br> This is the CellProfiler name for ImageJ's current image after processing by the command or macro. The image will be a snapshot of the current image after the command has run, and will be available for processing by subsequent CellProfiler modules.""" ) self.pause_before_proceeding = cps.Binary( "Wait for ImageJ before continuing?", False, doc=""" Some ImageJ commands and macros are interactive; you may want to adjust the image in ImageJ before continuing. Select <i>%(YES)s</i> to stop CellProfiler while you adjust the image in ImageJ. Select <i>%(NO)s</i> to immediately use the image. <p>This command will not wait if CellProfiler is executed in batch mode. See <i>%(BATCH_PROCESSING_HELP_REF)s</i> for more details on batch processing.</p>""" % globals()) self.prepare_group_choice = cps.Choice( "Function to run before each group of images?", [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" You can run an ImageJ 2.0 script, an ImageJ 1.x macro or a command <i>before</i> each group of images. This can be useful in order to set up ImageJ before processing a stack of images. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x macro in ImageJ 1.x compatibility mode. """ % globals()) logger.debug("Finding ImageJ commands") self.prepare_group_command = self.make_command_choice("Command", doc=""" <i>(Used only if running a command before an image group)</i><br> Select the command to execute before processing a group of images.""" ) self.prepare_group_macro = cps.Text("Macro", 'run("Invert");', multiline=True, doc=""" <i>(Used only if running a macro before an image group)</i><br> This is the ImageJ macro to be executed before processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""" ) self.post_group_choice = cps.Choice( "Function to run after each group of images?", [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" You can run an ImageJ 2.0 script, an ImageJ macro or a command <i>after</i> each group of images. This can be used to do some sort of operation on a whole stack of images that have been accumulated by the group operation. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x macro in ImageJ 1.x compatibility mode. """ % globals()) self.post_group_command = self.make_command_choice("Command", doc=""" <i>(Used only if running a command after an image group)</i><br> The command to execute after processing a group of images.""") self.post_group_macro = cps.Text("Macro", 'run("Invert");', multiline=True, doc=""" <i>(Used only if running a macro after an image group)</i><br> This is the ImageJ macro to be executed after processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""" ) self.wants_post_group_image = cps.Binary( "Retrieve the image output by the group operation?", False, doc=""" You can retrieve the image that is currently active in ImageJ at the end of macro processing and use it later in CellProfiler. The image will only be available during the last cycle of the image group. <p>Select <i>%(YES)s</i> to retrieve the active image for use in CellProfiler. Select <i>%(NO)s</i> if you do not want to retrieve the active image.</p> """ % globals()) self.post_group_output_image = cps.ImageNameProvider( "Name the group output image", "ImageJGroupImage", doc=""" <i>(Used only if retrieving an image after an image group operation)</i><br> This setting names the output image produced by the ImageJ command or macro that CellProfiler runs after processing all images in the group. The image is only available at the last cycle in the group""", provided_attributes={ cps.AGGREGATE_IMAGE_ATTRIBUTE: True, cps.AVAILABLE_ON_LAST_ATTRIBUTE: True }) self.show_imagej_button = cps.DoSomething("Show ImageJ", "Show", self.on_show_imagej, doc=""" Press this button to show the ImageJ user interface. You can use the user interface to run ImageJ commands or set up ImageJ before a CellProfiler run.""") logger.debug("Finished creating settings")
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()
def setUpClass(cls): cls.context = ij2.get_context()
def create_settings(self): '''Create the settings for the module''' logger.debug("Creating RunImageJ module settings") J.activate_awt() logger.debug("Activated AWT") self.command_or_macro = cps.Choice( "Run an ImageJ command or macro?", [CM_COMMAND, CM_MACRO],doc = """ This setting determines whether <b>RunImageJ</b> runs either a: <ul> <li><i>%(CM_COMMAND)s:</i> Select from a list of available ImageJ commands (those items contained in the ImageJ menus); or</li> <li><i>%(CM_MACRO)s:</i> A series of ImageJ commands/plugins that you write yourself.</li> </ul>"""%globals()) # # Load the commands in visible_settings so that we don't call # ImageJ unless someone tries the module # self.command = self.make_command_choice( "Command",doc = """ <i>(Used only if running a %(CM_COMMAND)s)</i><br> The command to execute when the module runs."""%globals()) self.command_settings_dictionary = {} self.command_settings = [] self.command_settings_count = cps.HiddenCount( self.command_settings, "Command settings count") self.pre_command_settings_dictionary = {} self.pre_command_settings = [] self.pre_command_settings_count = cps.HiddenCount( self.pre_command_settings, "Prepare group command settings count") self.post_command_settings_dictionary = {} self.post_command_settings = [] self.post_command_settings_count = cps.HiddenCount( self.post_command_settings, "Post-group command settings count") self.macro = cps.Text( "Macro", """import imagej.command.CommandService; cmdSvcClass = CommandService.class; cmdSvc = ImageJ.getService(cmdSvcClass); cmdSvc.run("imagej.core.commands.assign.InvertDataValues", new Object [] {"allPlanes", true}).get();""", multiline = True,doc=""" <i>(Used only if running a %(CM_MACRO)s)</i><br> This is the ImageJ macro to be executed. The syntax for ImageJ macros depends on the scripting language engine chosen. We suggest that you use the Beanshell scripting language <a href="http://www.beanshell.org/manual/contents.html"> (Beanshell documentation)</a>."""%globals()) all_engines = ij2.get_script_service(get_context()).getLanguages() self.language_dictionary = dict( [(engine.getLanguageName(), engine) for engine in all_engines]) self.macro_language = cps.Choice( "Macro language", choices = self.language_dictionary.keys(),doc = """ This setting chooses the scripting language used to execute any macros in this module""") self.wants_to_set_current_image = cps.Binary( "Input the currently active image in ImageJ?", True,doc=""" Check this setting if you want to set the currently active ImageJ image using an image from a prior CellProfiler module. <p>Leave it unchecked to use the currently active image in ImageJ. You may want to do this if you have an output image from a prior <b>RunImageJ</b> that you want to perform further operations upon before retrieving the final result back to CellProfiler.</p>""") self.current_input_image_name = cps.ImageNameSubscriber( "Select the input image",doc=""" <i>(Used only if setting the currently active image)</i><br> This is the CellProfiler image that will become ImageJ's currently active image. The ImageJ commands and macros in this module will perform their operations on this image. You may choose any image produced by a prior CellProfiler module.""") self.wants_to_get_current_image = cps.Binary( "Retrieve the currently active image from ImageJ?", True,doc=""" Check this setting if you want to retrieve ImageJ's currently active image after running the command or macro. <p>Leave the setting unchecked if the pipeline does not need to access the current ImageJ image. For example, you might want to run further ImageJ operations with additional <b>RunImageJ</b> upon the current image prior to retrieving the final image back to CellProfiler.</p>""") self.current_output_image_name = cps.ImageNameProvider( "Name the current output image", "ImageJImage",doc=""" <i>(Used only if retrieving the currently active image from ImageJ)</i><br> This is the CellProfiler name for ImageJ's current image after processing by the command or macro. The image will be a snapshot of the current image after the command has run, and will be available for processing by subsequent CellProfiler modules.""") self.pause_before_proceeding = cps.Binary( "Wait for ImageJ before continuing?", False,doc = """ Some ImageJ commands and macros are interactive; you may want to adjust the image in ImageJ before continuing. Check this box to stop CellProfiler while you adjust the image in ImageJ. Leave the box unchecked to immediately use the image. <p>This command will not wait if CellProfiler is executed in batch mode. See <i>%(BATCH_PROCESSING_HELP_REF)s</i> for more details on batch processing.</p>"""%globals()) self.prepare_group_choice = cps.Choice( "Function to run before each group of images?", [CM_NOTHING, CM_COMMAND, CM_MACRO],doc=""" You can run an ImageJ macro or a command <i>before</i> each group of images. This can be useful in order to set up ImageJ before processing a stack of images. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run or <i>%(CM_MACRO)s</i> to run a macro. """ % globals()) logger.debug("Finding ImageJ commands") self.prepare_group_command = self.make_command_choice( "Command", doc = """ <i>(Used only if running a command before an image group)</i><br> Select the command to execute before processing a group of images.""") self.prepare_group_macro = cps.Text( "Macro", 'run("Invert");', multiline = True,doc=""" <i>(Used only if running a macro before an image group)</i><br> This is the ImageJ macro to be executed before processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""") self.post_group_choice = cps.Choice( "Function to run after each group of images?", [CM_NOTHING, CM_COMMAND, CM_MACRO],doc=""" You can run an ImageJ macro or a command <i>after</i> each group of images. This can be used to do some sort of operation on a whole stack of images that have been accumulated by the group operation. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run or <i>%(CM_MACRO)s</i> to run a macro. """ % globals()) self.post_group_command = self.make_command_choice( "Command", doc = """ <i>(Used only if running a command after an image group)</i><br> The command to execute after processing a group of images.""") self.post_group_macro = cps.Text( "Macro", 'run("Invert");', multiline = True,doc=""" <i>(Used only if running a macro after an image group)</i><br> This is the ImageJ macro to be executed after processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""") self.wants_post_group_image = cps.Binary( "Retrieve the image output by the group operation?", False,doc=""" You can retrieve the image that is currently active in ImageJ at the end of macro processing and use it later in CellProfiler. The image will only be available during the last cycle of the image group. Check this setting to use the active image in CellProfiler or leave it unchecked if you do not want to use the active image. """) self.post_group_output_image = cps.ImageNameProvider( "Name the group output image", "ImageJGroupImage",doc=""" <i>(Used only if retrieving an image after an image group operation)</i><br> This setting names the output image produced by the ImageJ command or macro that CellProfiler runs after processing all images in the group. The image is only available at the last cycle in the group""", provided_attributes={cps.AGGREGATE_IMAGE_ATTRIBUTE: True, cps.AVAILABLE_ON_LAST_ATTRIBUTE: True } ) self.show_imagej_button = cps.DoSomething( "Show ImageJ", "Show", self.on_show_imagej,doc=""" Press this button to show the ImageJ user interface. You can use the user interface to run ImageJ commands or set up ImageJ before a CellProfiler run.""") logger.debug("Finished creating settings")
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()