Пример #1
0
    def add_file(self, can_remove=True):
        """Add settings for another file to the list"""
        group = cps.SettingsGroup()
        if can_remove:
            group.append("divider", cps.Divider(line=False))

        def get_directory_fn():
            return self.directory.get_absolute_path()

        group.append(
            "file_name",
            cps.FilenameText(
                FILE_TEXT,
                cps.NONE,
                metadata=True,
                get_directory_fn=get_directory_fn,
                exts=[("TIF - Tagged Image File format (*.tif,*.tiff)",
                       "*.tif;*.tiff"),
                      ("PNG - Portable Network Graphics (*.png)", "*.png"),
                      ("JPG/JPEG file (*.jpg,*.jpeg)", "*.jpg,*.jpeg"),
                      ("BMP - Windows Bitmap (*.bmp)", "*.bmp"),
                      ("Compuserve GIF file (*.gif)", "*.gif"),
                      ("MATLAB image (*.mat)", "*.mat"),
                      ("All files (*.*)", "*.*")],
                doc="""
                    The filename can be constructed in one of two ways:
                    <ul>
                    <li>As a fixed filename (e.g., <i>Exp1_D03f00d0.tif</i>). </li>
                    <li>Using the metadata associated with an image set in 
                    <b>LoadImages</b> or <b>LoadData</b>. This is especially useful 
                    if you want your output given a unique label according to the
                    metadata corresponding to an image group. The name of the metadata 
                    to substitute is included in a special tag format embedded 
                    in your file specification. %(USING_METADATA_TAGS_REF)s%(USING_METADATA_HELP_REF)s.</li>
                    </ul>
                    <p>Keep in mind that in either case, the image file extension, if any, must be included."""
                % globals()))

        group.append(
            "image_objects_choice",
            cps.Choice('Load as images or objects?',
                       IO_ALL,
                       doc="""
                    This setting determines whether you load an image as image data
                    or as segmentation results (i.e., objects):
                    <ul>
                    <li><i>%(IO_IMAGES)s:</i> The input image will be given a user-specified name by
                    which it will be refered downstream. This is the most common usage for this
                    module.</li>
                    <li><i>%(IO_OBJECTS)s:</i> Use this option if the input image is a label matrix 
                    and you want to obtain the objects that it defines. A <i>label matrix</i>
                    is a grayscale or color image in which the connected regions share the
                    same label, and defines how objects are represented in CellProfiler.
                    The labels are integer values greater than or equal to 0. 
                    The elements equal to 0 are the background, whereas the elements equal to 1 
                    make up one object, the elements equal to 2 make up a second object, and so on.
                    This option allows you to use the objects without needing to insert an 
                    <b>Identify</b> module to extract them first. See <b>IdentifyPrimaryObjects</b> 
                    for more details.</li>
                    </ul>""" % globals()))

        group.append(
            "image_name",
            cps.FileImageNameProvider("Name the image that will be loaded",
                                      "OrigBlue",
                                      doc='''
                    <i>(Used only if an image is output)</i><br>
                    Enter the name of the image that will be loaded. 
                    You can use this name to select the image in downstream modules.'''
                                      ))

        group.append(
            "rescale",
            cps.Binary("Rescale intensities?",
                       True,
                       doc="""
                    <i>(Used only if an image is output)</i><br>
                    This option determines whether image metadata should be
                    used to rescale the image's intensities. Some image formats
                    save the maximum possible intensity value along with the pixel data.
                    For instance, a microscope might acquire images using a 12-bit
                    A/D converter which outputs intensity values between zero and 4095,
                    but stores the values in a field that can take values up to 65535.
                    <p>Select <i>%(YES)s</i> to rescale the image intensity so that
                    saturated values are rescaled to 1.0 by dividing all pixels
                    in the image by the maximum possible intensity value. </p>
                    <p>Select <i>%(NO)s</i> to ignore the image metadata and rescale the image
                    to 0 &ndash; 1.0 by dividing by 255 or 65535, depending on the number
                    of bits used to store the image.</p>""" % globals()))

        group.append(
            "objects_name",
            cps.ObjectNameProvider(
                'Name this loaded object',
                "Nuclei",
                doc="""<i>(Used only if objects are output)</i><br>
                    This is the name for the objects loaded from your image""")
        )

        group.append(
            "wants_outlines",
            cps.Binary("Retain outlines of loaded objects?",
                       False,
                       doc="""
                    <i>(Used only if objects are output)</i><br>
                    Select <i>%(YES)s</i> if you want to save an image of the outlines
                    of the loaded objects.""" % globals()))

        group.append(
            "outlines_name",
            cps.OutlineNameProvider('Name the outlines',
                                    'NucleiOutlines',
                                    doc="""
                    <i>(Used only if objects are output)</i><br>
                    Enter a name that will allow the outlines to be selected later in the pipeline."""
                                    ))

        if can_remove:
            group.append(
                "remove",
                cps.RemoveSettingButton("", "Remove this image",
                                        self.file_settings, group))
        self.file_settings.append(group)
Пример #2
0
 def create_settings(self):
     self.image_name = cps.ImageNameSubscriber(
         'Select the input image',
         'None',
         doc='''What did you call the images to be made into a projection?'''
     )
     self.projection_type = cps.Choice('Type of projection',
                                       P_ALL,
                                       doc='''
         What kind of projection would you like to make? The final image can be created
         by the following methods:
         <ul><li><i>%(P_AVERAGE)s:</i> Use the average pixel intensity at each pixel position.</li>
         <li><i>%(P_MAXIMUM)s:</i> Use the maximum pixel value at each pixel position.</li>
         <li><i>%(P_MINIMUM)s:</i> Use the minimum pixel value at each pixel position.</li>
         <li><i>%(P_SUM)s:</i> Add the pixel values at each pixel position.</li>
         <li><i>%(P_VARIANCE)s:</i> Compute the variance at each pixel position. <br>
         The variance  method is described in "Selinummi J, Ruusuvuori P, Podolsky I, Ozinsky A, Gold E, et al. (2009), 
         "Bright Field Microscopy as an Alternative to Whole Cell Fluorescence in Automated Analysis of
         Macrophage Images", PLoS ONE 4(10): e7497 <a href="http://dx.doi.org/10.1371/journal.pone.0007497">(link)</a>.
         The method is designed to operate on a z-stack of brightfield images taken
         at different focus planes. Background pixels will have relatively uniform
         illumination whereas cytoplasm pixels will have higher variance across the
         z-stack.</li>
         <li><i>%(P_POWER)s:</i> Compute the power at a given frequency at each pixel position.<br>
         The power method is experimental. The method computes the power at a given
         frequency through the z-stack. It might be used with a phase contrast image
         where the signal at a given pixel will vary sinusoidally with depth. The
         frequency is measured in z-stack steps and pixels that vary with the given
         frequency will have a higher score than other pixels with similar variance,
         but different frequencies.</li>
         <li><i>%(P_BRIGHTFIELD)s:</i> Perform the brightfield projection at each pixel position.<br>
         Artifacts such as dust appear as black spots which are most strongly resolved
         at their focal plane with gradually increasing signals below. The brightfield
         method scores these as zero since the dark appears in the early z-stacks.
         These pixels have a high score for the variance method but have a reduced
         score when using the brightfield method.</li>
         <li><i>%(P_MASK)s:</i> Compute a binary image of the pixels that are 
         masked in any of the input images.<br>
         The mask method operates on any masks that might have been applied to the
         images in a group. The output is a binary image where the "1" pixels are
         those that are not masked in all of the images and the "0" pixels are those
         that are masked in one or more of the images.<br>
         You can use the output of the mask method to mask or crop all of the
         images in a group similarly. Use the mask method to combine all of the
         masks in a group, save the image and then use <b>Crop</b>, <b>MaskImage</b> or 
         <b>MaskObjects</b> in another pipeline to mask all images or objects in the
         group similarly.</li>
         </ul>
         ''' % globals())
     self.projection_image_name = cps.ImageNameProvider(
         'Name the output image',
         'ProjectionBlue',
         doc='''What do you want to call the projected image?''',
         provided_attributes={
             cps.AGGREGATE_IMAGE_ATTRIBUTE: True,
             cps.AVAILABLE_ON_LAST_ATTRIBUTE: True
         })
     self.frequency = cps.Float("Frequency",
                                6.0,
                                minval=1.0,
                                doc="""
         <i>(Used only if %(P_POWER)s is selected as the projection method)</i><br>
         This setting controls the frequency at which the power
         is measured. A frequency of 2 will respond most strongly to
         pixels that alternate between dark and light in successive
         z-stack slices. A frequency of N will respond most strongly
         to pixels whose brightness cycle every N slices.""" % globals())
Пример #3
0
    def create_settings(self):
        self.input_image = cps.ImageNameSubscriber("Select an input image",
                                                   "None",
                                                   doc="""
                                                         What did you call the image to be tiled? 
                                                         Additional images within the cycle can be added 
                                                         later by choosing the <i>Across cycles</i> 
                                                         option.""")
        self.output_image = cps.ImageNameProvider("Name the output image",
                                                  "TiledImage",
                                                  doc="""
            What do you want to call the final tiled image?""")

        self.additional_images = []

        self.add_button = cps.DoSomething("", "Add another image",
                                          self.add_image)

        self.tile_method = cps.Choice("Tile within cycles or across cycles?",
                                      T_ALL,
                                      doc='''
             How would you like to tile images? Two options are available:<br>
             <ul>
             <li><i>Tile within cycles:</i> If you have loaded more than one image for each cycle
             using modules upstream in the pipeline, 
             the images can be tiled. For example, you may tile three different channels
             (OrigRed, OrigBlue, and OrigGreen), and a new tiled image will 
             be created for every image cycle. This option takes the place of the 
             obsolete <b>PlaceAdjacent</b> module.  </li>
             <li><i>Tile across cycles:</i> If you want to tile images from multiple 
             cycles together, select this option. For example, you may tile all the 
             images of the same type (e.g., OrigBlue) across all fields of view in your  
             experiment, which will result in one final tiled image 
             when processing is complete.</li>
             </ul>''')

        self.rows = cps.Integer("Number of rows in final tiled image",
                                8,
                                doc='''
            How many rows would you like to have in the tiled image?
            For example, if you want to show your images in a 96-well format, 
            enter 8. 
            <p><i>Special cases:</i> Let <i>M</i> be the total number of slots for images
            (i.e, number of rows x number of columns) and <i>N</i> be the number 
            of actual images. 
            <ul>
            <li>If <i>M</i> &gt; <i>N</i>, blanks will be used for the 
            empty slots.</li>
            <li>If the <i>M</i> &lt; <i>N</i>, an error will occur since there are
            not enough image slots. Check "Automatically calculate number of rows?"
            to avoid this error.</li>
            </ul></p>''')

        self.columns = cps.Integer(
            "Number of columns in final tiled image",
            12,
            doc='''How many columns would you like to have in the tiled image?
            For example, if you want to show your images in a 96-well format, 
            enter 12.
            <p><i>Special cases:</i> Let <i>M</i> be the total number of slots for images
            (i.e, number of rows x number of columns) and <i>N</i> be the number 
            of actual images. 
            <ul>
            <li>If <i>M</i> &gt; <i>N</i>, blanks will be used for the 
            empty slots.</li>
            <li>If the <i>M</i> &lt; <i>N</i>, an error will occur since there are
            not enough image slots. Check "Automatically calculate number of columns?"
            to avoid this error.</li>
            </ul></p>''')

        self.place_first = cps.Choice(
            "Begin tiling in which corner of the final image?",
            P_ALL,
            doc='''
            Where do you want the first image to be placed?  Begin in the upper left-hand corner
            for a typical multi-well plate format where the first image is A01.'''
        )

        self.tile_style = cps.Choice(
            "Begin tiling across a row, or down a column?",
            S_ALL,
            doc='''
            Are the images arranged in rows or columns?  If your images are named A01, A02, etc, 
            enter <i>row</i>".''')

        self.meander = cps.Binary("Tile in meander mode?",
                                  False,
                                  doc='''
            Meander mode tiles adjacent images in one direction, 
            then the next row/column is tiled in the opposite direction.  
            Some microscopes capture images
            in this fashion. The default mode is "comb", or "typewriter"
            mode; in this mode, when one row is completely tiled in one direction,
            the next row starts near where the first row started and tiles 
            again in the same direction.''')

        self.wants_automatic_rows = cps.Binary(
            "Automatically calculate number of rows?",
            False,
            doc="""<b>Tile</b> can automatically calculate the number of rows
            in the grid based on the number of image cycles that will be processed.
            Check this box to create a grid that has the number of columns
            that you entered and enough rows to display all of your images.
            If you check both automatic rows and automatic columns, <b>Tile</b>
            will create a grid that has roughly the same number of rows
            and columns.""")

        self.wants_automatic_columns = cps.Binary(
            "Automatically calculate number of columns?",
            False,
            doc="""<b>Tile</b> can automatically calculate the number of columns
            in the grid from the number of image cycles that will be processed.
            Check this box to create a grid that has the number of rows
            that you entered and enough columns to display all of your images.
            If you check both automatic rows and automatic columns, <b>Tile</b>
            will create a grid that has roughly the same number of rows
            and columns.""")
Пример #4
0
    def create_settings(self):
        self.orig_image_name = cps.ImageNameSubscriber(
            "Select the input images",
            cps.NONE,
            doc="""
            Select the images to display on the web page.""")

        self.wants_thumbnails = cps.Binary("Use thumbnail images?",
                                           False,
                                           doc="""
            Select <i>%(YES)s</i> to display thumbnail images (small versions of the
            images) on the web page that link to the full images. <br>
            Select <i>%(NO)s</i> to display the full image directly on the web page.
            <p>If you are going to use thumbnails, you will need to load
            them using the <b>Input</b> modules; you can also run a separate
            pipeline prior to this one to create thumbnails from your originals
            using the <b>Resize</b> and <b>SaveImages</b> modules. For some high-content
            screening systems, thumbnail files are automatically created and have
            the text "thumb" in the name.</p>""" % globals())

        self.thumbnail_image_name = cps.ImageNameSubscriber(
            "Select the thumbnail images",
            cps.NONE,
            doc="""
            <i>(Used only if using thumbnails)</i><br>
            Select the name of the images to use for thumbnails.""")

        self.web_page_file_name = cps.Text("Webpage file name",
                                           "images1",
                                           metadata=True,
                                           doc="""
            Enter the desired file name for the web page. <b>CreateWebPage</b>
            will add the .html extension if no extension is specified.
            If you have metadata associated with your images, you can name the
            file using metadata tags. %(USING_METADATA_TAGS_REF)s<br>
            For instance, if you have metadata tags named "Plate" and
            "Well", you can create separate per-plate, per-well web pages based on
            your metadata by inserting the tags "Plate_Well" to specify the
            name. %(USING_METADATA_HELP_REF)s.""" % globals())

        self.directory_choice = CWPDirectoryPath(
            "Select the folder for the .html file",
            dir_choices=[
                DIR_SAME, DIR_ABOVE, ABSOLUTE_FOLDER_NAME,
                DEFAULT_INPUT_FOLDER_NAME, DEFAULT_OUTPUT_FOLDER_NAME,
                DEFAULT_INPUT_SUBFOLDER_NAME, DEFAULT_OUTPUT_SUBFOLDER_NAME
            ],
            doc="""
            This setting determines how <b>CreateWebPage</b> selects the
            folder for the .html file(s) it creates.
            <ul>
            <li><i>%(DIR_SAME)s</i>: Place the .html file(s) in the same folder as
            the files.</li>
            <li><i>%(DIR_ABOVE)s</i>: Place the .html file(s) in the
            image files' parent folder.</li>
            <li><i>%(ABSOLUTE_FOLDER_NAME)s</i>: Places the .html file(s) in
            a folder of your choosing. <b>CreateWebPage</b> will use absolute
            references for your image URLs if you choose this option.</li>
            <li><i>%(DEFAULT_INPUT_FOLDER_NAME)s</i>: Places the .html file(s)
            in the default input folder.</li>
            <li><i>%(DEFAULT_OUTPUT_FOLDER_NAME)s</i>: Places the .html file(s)
            in the default output folder.</li>
            <li><i>%(DEFAULT_INPUT_SUBFOLDER_NAME)s</i>: Places the .html file(s)
            in a subfolder of the default input folder. You will be prompted
            for the subfolder name after making this choice</li>
            <li><i>%(DEFAULT_OUTPUT_SUBFOLDER_NAME)s</i>: Places the .html file(s)
            in a subfolder of the default input folder. You will be prompted
            for the subfolder name after making this choice</li>
            </ul>""" % globals())

        self.title = cps.Text("Webpage title",
                              "Image",
                              metadata=True,
                              doc="""
            This is the title that appears at the top of the browser
            window. If you have metadata associated with your images, you can name the
            file using metadata tags. %(USING_METADATA_TAGS_REF)sFor instance, if you
            have a metadata tag named "Plate", you can type "Plate: " and then insert
            the metadata tag "Plate" to display the plate metadata item. %(USING_METADATA_HELP_REF)s."""
                              % globals())

        self.background_color = cps.Color("Webpage background color",
                                          "White",
                                          doc="""
            This setting controls the background color for the web page.""")

        self.columns = cps.Integer("Number of columns",
                                   1,
                                   minval=1,
                                   doc="""
            This setting determines how many images are displayed
            in each row.""")

        self.table_border_width = cps.Integer("Table border width",
                                              1,
                                              minval=0,
                                              doc="""
            The table border width determines the width of the border
            around the entire grid of displayed images (i.e., the "table" of images)
            and is measured in pixels. This value can be
            set to zero, in which case you will not see the table border.""")

        self.table_border_color = cps.Color("Table border color", "White")

        self.image_spacing = cps.Integer("Image spacing",
                                         1,
                                         minval=0,
                                         doc="""
            The spacing between images ("table cells"), in pixels.""")

        self.image_border_width = cps.Integer("Image border width",
                                              1,
                                              minval=0,
                                              doc="""
            The image border width determines the width of
            the border around each image and is measured in pixels.
            This value can be set to zero, in which case you will not see the
            image border.""")

        self.create_new_window = cps.Choice(
            "Open new window when viewing full image?",
            [OPEN_ONCE, OPEN_EACH, OPEN_NO],
            doc="""
            This controls the behavior of the thumbnail links.
            <ul>
            <li><i>%(OPEN_ONCE)s:</i> Your browser will open a new window
            when you click on the first thumbnail and will display subsequent
            images in the newly opened window. </li>
            <li><i>%(OPEN_EACH)s:</i> The browser will open a new window each time
            you click on a link.</li>
            <li><i>%(OPEN_NO)s:</i> The browser will reuse the current window
            to display the image</li>
            </ul>""" % globals())

        self.wants_zip_file = cps.Binary(
            "Make a ZIP file containing the full-size images?",
            False,
            doc="""
            ZIP files are a common archive and data compression file format, making
            it convenient to download all of the images represented on the web page with a single click.
            Select <i>%(YES)s</i> to create a ZIP file that contains all your images,
            compressed to reduce file size.""" % globals())

        self.zipfile_name = cps.Text("Enter the ZIP file name",
                                     "Images.zip",
                                     metadata=True,
                                     doc="""
            <i>(Used only if creating a ZIP file)</i><br>
            Specify the name for the ZIP file.""")
Пример #5
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  cps.NONE)

        self.combine_or_split = cps.Choice("Conversion method",
                                           [COMBINE, SPLIT],
                                           doc='''
            How do you want to convert the color image? 
            <ul>
            <li><i>%(SPLIT)s:</i> Splits the three channels
            (red, green, blue) of a color image into three separate grayscale images. </li>
            <li><i>%(COMBINE)s</i> Converts a color image to a grayscale 
            image by combining the three channels (red, green, blue) together.</li>
            </ul>''' % globals())

        self.rgb_or_channels = cps.Choice("Image type",
                                          [CH_RGB, CH_HSV, CH_CHANNELS],
                                          doc="""
            Many images contain color channels other than red, green
            and blue. For instance, GIF and PNG formats can have an alpha
            channel that encodes transparency. TIF formats can have an arbitrary
            number of channels which represent pixel measurements made by
            different detectors, filters or lighting conditions. This setting
            provides three options to choose from:
            <ul>
            <li><i>%(CH_RGB)s:</i> The RGB (red,green,blue) color space is the typical model in which color images are stored. Choosing this option
            will split the image into any of the red, green and blue component images.</li>
            <li><i>%(CH_HSV)s:</i>The HSV (hue, saturation, value) color space is based on more intuitive color characteristics as 
            tint, shade and tone. Choosing
            this option will split the image into any of the hue, saturation, and value component images.</li>
            <li><i>%(CH_CHANNELS)s:</i>This is a more complex model for images which involve more than three chnnels.</li>
            </ul>""" % globals())

        # The following settings are used for the combine option
        self.grayscale_name = cps.ImageNameProvider("Name the output image",
                                                    "OrigGray")

        self.red_contribution = cps.Float("Relative weight of the red channel",
                                          1,
                                          0,
                                          doc='''
            <i>(Used only when combining channels)</i><br>
            Relative weights: If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative 
            to each other, increase or decrease the relative weights.''')

        self.green_contribution = cps.Float(
            "Relative weight of the green channel",
            1,
            0,
            doc='''
            <i>(Used only when combining channels)</i><br>
            Relative weights: If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative 
            to each other, increase or decrease the relative weights.''')

        self.blue_contribution = cps.Float(
            "Relative weight of the blue channel",
            1,
            0,
            doc='''
            <i>(Used only when combining channels)</i><br>
            Relative weights: If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative 
            to each other, increase or decrease the relative weights.''')

        # The following settings are used for the split RGB option
        self.use_red = cps.Binary('Convert red to gray?', True)
        self.red_name = cps.ImageNameProvider('Name the output image',
                                              "OrigRed")

        self.use_green = cps.Binary('Convert green to gray?', True)
        self.green_name = cps.ImageNameProvider('Name the output image',
                                                "OrigGreen")

        self.use_blue = cps.Binary('Convert blue to gray?', True)
        self.blue_name = cps.ImageNameProvider('Name the output image',
                                               "OrigBlue")

        # The following settings are used for the split HSV ption
        self.use_hue = cps.Binary('Convert hue to gray?', True)
        self.hue_name = cps.ImageNameProvider('Name the output image',
                                              "OrigHue")

        self.use_saturation = cps.Binary('Convert saturation to gray?', True)
        self.saturation_name = cps.ImageNameProvider('Name the output image',
                                                     "OrigSaturation")

        self.use_value = cps.Binary('Convert value to gray?', True)
        self.value_name = cps.ImageNameProvider('Name the output image',
                                                "OrigValue")

        # The alternative model:
        self.channels = []
        self.add_channel(False)
        self.channel_button = cps.DoSomething("", "Add another channel",
                                              self.add_channel)

        self.channel_count = cps.HiddenCount(self.channels, "Channel count")
Пример #6
0
    def create_settings(self):
        """Create your settings by subclassing this function
        
        create_settings is called at the end of initialization.
        
        You should create the setting variables for your module here:
            # Ask the user for the input image
            self.image_name = cellprofiler.settings.ImageNameSubscriber(...)
            # Ask the user for the name of the output image
            self.output_image = cellprofiler.settings.ImageNameProvider(...)
            # Ask the user for a parameter
            self.smoothing_size = cellprofiler.settings.Float(...)
        """
        self.object_name = cps.ObjectNameSubscriber(
            "Select the objects to be edited",
            cps.NONE,
            doc="""
            Choose a set of previously identified objects
            for editing, such as those produced by one of the
            <b>Identify</b> modules.""")

        self.filtered_objects = cps.ObjectNameProvider(
            "Name the edited objects",
            "EditedObjects",
            doc="""
            Enter the name for the objects that remain
            after editing. These objects will be available for use by
            subsequent modules.""")

        self.allow_overlap = cps.Binary("Allow overlapping objects?",
                                        False,
                                        doc="""
            <b>EditObjectsManually</b> can allow you to edit an
            object so that it overlaps another or it can prevent you from
            overlapping one object with another. Objects such as worms or
            the neurites of neurons may cross each other and might need to
            be edited with overlapping allowed, whereas a monolayer of cells
            might be best edited with overlapping off. Check this setting to
            allow overlaps or uncheck it to prevent them.""")

        self.wants_outlines = cps.Binary(
            "Retain outlines of the edited objects?",
            False,
            doc="""
            Check this box if you want to keep images of the outlines
            of the objects that remain after editing. This image
            can be saved by downstream modules or overlayed on other images
            using the <b>OverlayOutlines</b> module.""")

        self.outlines_name = cps.OutlineNameProvider("Name the outline image",
                                                     "EditedObjectOutlines",
                                                     doc="""
            <i>(Used only if you have selected to retain outlines of edited objects)</i><br>
            Enter a name for the outline image.""")

        self.renumber_choice = cps.Choice("Numbering of the edited objects",
                                          [R_RENUMBER, R_RETAIN],
                                          doc="""
            Choose how to number the objects that 
            remain after editing, which controls how edited objects are associated with their predecessors:
            <ul>
            <li><i>%(R_RENUMBER)s:</i> The module will number the objects that remain 
            using consecutive numbers. This
            is a good choice if you do not plan to use measurements from the
            original objects and you only want to use the edited objects in downstream modules; the
            objects that remain after editing will not have gaps in numbering
            where removed objects are missing.</li>
            <li><i>%(R_RETAIN)s:</i> This option will retain each object's original number so that the 
            edited object's number matches its original number. This allows any measurements you make from 
            the edited objects to be directly aligned with measurements you might 
            have made of the original, unedited objects (or objects directly 
            associated with them).</li>
            </ul>""" % globals())

        self.wants_image_display = cps.Binary("Display a guiding image?",
                                              True,
                                              doc="""
            Check this setting to display an image and outlines
            of the objects. Leave the setting unchecked if you do not
            want a guide image while editing""")

        self.image_name = cps.ImageNameSubscriber("Select the guiding image",
                                                  cps.NONE,
                                                  doc="""
            <i>(Used only if a guiding image is desired)</i><br>
            This is the image that will appear when editing objects.
            Choose an image supplied by a previous module.""")
Пример #7
0
    def create_settings(self):
        self.x_source = cps.Choice("Type of measurement to plot on X-axis",
                                   SOURCE_CHOICE,
                                   doc='''
            You can plot two types of measurements:
            <ul>
            <li><i>%(SOURCE_IM)s:</i> For a per-image measurement, one numerical value is 
            recorded for each image analyzed.
            Per-image measurements are produced by
            many modules. Many have <b>MeasureImage</b> in the name but others do not
            (e.g., the number of objects in each image is a per-image 
            measurement made by the <b>IdentifyObject</b> 
            modules).</li>
            <li><i>%(SOURCE_OBJ)s:</i> For a per-object measurement, each identified 
            object is measured, so there may be none or many 
            numerical values recorded for each image analyzed. These are usually produced by
            modules with <b>MeasureObject</b> in the name.</li>
            </ul>''' % globals())

        self.x_object = cps.ObjectNameSubscriber(
            'Select the object to plot on the X-axis',
            cps.NONE,
            doc='''<i>(Used only when plotting objects)</i><br>
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the X-axis.'''
        )

        self.x_axis = cps.Measurement(
            'Select the measurement to plot on the X-axis',
            self.get_x_object,
            cps.NONE,
            doc='''
            Choose the measurement (made by a previous 
            module) to plot on the X-axis.''')

        self.y_source = cps.Choice("Type of measurement to plot on Y-axis",
                                   SOURCE_CHOICE,
                                   doc='''
            You can plot two types of measurements:
            <ul>
            <li><i>%(SOURCE_IM)s:</i> For a per-image measurement, one numerical value is 
            recorded for each image analyzed.
            Per-image measurements are produced by
            many modules. Many have <b>MeasureImage</b> in the name but others do not
            (e.g., the number of objects in each image is a per-image 
            measurement made by <b>IdentifyObject</b> 
            modules).</li>
            <li><i>%(SOURCE_OBJ)s:</i> For a per-object measurement, each identified 
            object is measured, so there may be none or many 
            numerical values recorded for each image analyzed. These are usually produced by
            modules with <b>MeasureObject</b> in the name.</li>
            </ul>''' % globals())

        self.y_object = cps.ObjectNameSubscriber(
            'Select the object to plot on the Y-axis',
            cps.NONE,
            doc='''<i>(Used only when plotting objects)</i><br>
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the Y-axis.'''
        )

        self.y_axis = cps.Measurement(
            'Select the measurement to plot on the Y-axis',
            self.get_y_object,
            cps.NONE,
            doc='''
            Choose the measurement (made by a previous 
            module) to plot on the Y-axis.''')

        self.xscale = cps.Choice('How should the X-axis be scaled?',
                                 SCALE_CHOICE,
                                 None,
                                 doc='''
            The X-axis can be scaled with either a <i>linear</i> 
            scale or a <i>log</i> (base 10) scaling. 
            <p>Log scaling is useful when one of the 
            measurements being plotted covers a large range of 
            values; a log scale can bring out features in the 
            measurements that would not easily be seen if the 
            measurement is plotted linearly.</p>''')

        self.yscale = cps.Choice('How should the Y-axis be scaled?',
                                 SCALE_CHOICE,
                                 None,
                                 doc='''
            The Y-axis can be scaled with either a <i>linear</i> 
            scale or with a <i>log</i> (base 10) scaling. 
            <p>Log scaling is useful when one of the 
            measurements being plotted covers a large range of 
            values; a log scale can bring out features in the 
            measurements that would not easily be seen if the 
            measurement is plotted linearly.</p>''')

        self.title = cps.Text('Enter a title for the plot, if desired',
                              '',
                              doc='''
            Enter a title for the plot. If you leave this blank,
            the title will default 
            to <i>(cycle N)</i> where <i>N</i> is the current image 
            cycle being executed.''')
Пример #8
0
    def add_when(self, can_delete=True):
        group = cps.SettingsGroup()
        group.append(
            "choice",
            cps.Choice("When should the email be sent?",
                       S_ALL,
                       doc="""
            Select the kind of event that causes
            <b>SendEmail</b> to send an email. You have the following choices:
            <ul>
            <li><i>%(S_FIRST)s:</i> Send an email during
            processing of the first image cycle.</li>
            <li><i>%(S_LAST)s:</i> Send an email after all processing
            is complete.</li>
            <li><i>%(S_GROUP_START)s:</i> Send an email during the first
            cycle of each group of images.</li>
            <li><i>%(S_GROUP_END)s:</i> Send an email after all processing
            for a group is complete.</li>
            <li><i>%(S_EVERY_N)s</i> Send an email each time a certain
            number of image cycles have been processed. You will be prompted
            for the number of image cycles if you select this choice.</li>
            <li><i>%(S_CYCLE_N)s:</i> Send an email after the given number
            of image cycles have been processed. You will be prompted for
            the image cycle number if you select this choice. You can add
            more events if you want emails after more than one image cycle.</li>
            </ul>""" % globals()))

        group.append(
            "image_set_number",
            cps.Integer("Image cycle number",
                        1,
                        minval=1,
                        doc='''
            <i>(Used only if sending email after a particular cycle number)</i><br>
            Send an email during processing of the given image cycle.
            For instance, if you enter 4, then <b>SendEmail</b>
            will send an email during processing of the fourth image cycle.''')
        )

        group.append(
            "image_set_count",
            cps.Integer("Image cycle count",
                        1,
                        minval=1,
                        doc='''
            <i>(Used only if sending email after every N cycles)</i><br>
            Send an email each time this number of image cycles have
            been processed. For instance, if you enter 4,
            then <b>SendEmail</b> will send an email during processing of
            the fourth, eighth, twelfth, etc. image cycles.'''))

        group.append(
            "message",
            cps.Text("Message text",
                     "Notification from CellProfiler",
                     metadata=True,
                     doc="""
            The body of the message sent from CellProfiler.
            Your message can include metadata values. For instance,
            if you group by plate and want to send an email after processing each
            plate, you could use the message  
            "Finished processing plate \\g&lt;Plate&gt;". """))

        if can_delete:
            group.append(
                "remover",
                cps.RemoveSettingButton("Remove this email event",
                                        "Remove event", self.when, group))
        group.append("divider", cps.Divider())
        self.when.append(group)
Пример #9
0
    def create_settings(self):
        self.x_object = cps.ObjectNameSubscriber(
            'Select the object to display on the X-axis',
            cps.NONE,
            doc='''
            Choose the name of objects identified by some previous
            module (such as <b>IdentifyPrimaryObjects</b> or
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the X-axis.'''
        )

        self.x_axis = cps.Measurement(
            'Select the object measurement to plot on the X-axis',
            self.get_x_object,
            cps.NONE,
            doc='''
            Choose the object measurement made by a previous
            module to display on the X-axis.''')

        self.y_object = cps.ObjectNameSubscriber(
            'Select the object to display on the Y-axis',
            cps.NONE,
            doc='''
            Choose the name of objects identified by some previous
            module (such as <b>IdentifyPrimaryObjects</b> or
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the Y-axis.'''
        )

        self.y_axis = cps.Measurement(
            'Select the object measurement to plot on the Y-axis',
            self.get_y_object,
            cps.NONE,
            doc='''
            Choose the object measurement made by a previous
            module to display on the Y-axis.''')

        self.gridsize = cps.Integer('Select the grid size',
                                    100,
                                    1,
                                    1000,
                                    doc='''
            Enter the number of grid regions you want used on each
            axis. Increasing the number of grid regions increases the
            resolution of the plot.''')

        self.xscale = cps.Choice('How should the X-axis be scaled?',
                                 ['linear', 'log'],
                                 None,
                                 doc='''
            The X-axis can be scaled either with a <i>linear</i>
            scale or with a <i>log</i> (base 10) scaling.
            <p>Using a log scaling is useful when one of the
            measurements being plotted covers a large range of
            values; a log scale can bring out features in the
            measurements that would not easily be seen if the
            measurement is plotted linearly.</p>''')

        self.yscale = cps.Choice('How should the Y-axis be scaled?',
                                 ['linear', 'log'],
                                 None,
                                 doc='''
            The Y-axis can be scaled either with a <i>linear</i>
            scale or with a <i>log</i> (base 10) scaling.
            <p>Using a log scaling is useful when one of the
            measurements being plotted covers a large range of
            values; a log scale can bring out features in the
            measurements that would not easily be seen if the
            measurement is plotted linearly.</p>''')

        self.bins = cps.Choice('How should the colorbar be scaled?',
                               ['linear', 'log'],
                               None,
                               doc='''
            The colorbar can be scaled either with a <i>linear</i>
            scale or with a <i>log</i> (base 10) scaling.
            <p>Using a log scaling is useful when one of the
            measurements being plotted covers a large range of
            values; a log scale can bring out features in the
            measurements that would not easily be seen if the
            measurement is plotted linearly.''')

        maps = [m for m in matplotlib.cm.datad.keys() if not m.endswith('_r')]
        maps.sort()

        self.colormap = cps.Choice('Select the color map',
                                   maps,
                                   'jet',
                                   doc='''
            Select the color map for the density plot. See
            <a href="http://www.astro.princeton.edu/~msshin/science/code/matplotlib_cm/">
            this page</a> for pictures of the available colormaps.''')

        self.title = cps.Text('Enter a title for the plot, if desired',
                              '',
                              doc='''
            Enter a title for the plot. If you leave this blank,
            the title will default
            to <i>(cycle N)</i> where <i>N</i> is the current image
            cycle being executed.''')
Пример #10
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  "None",
                                                  doc="""
                            What did you call the image to be cropped?""")

        self.cropped_image_name = cps.CroppingNameProvider(
            "Name the output image",
            "CropBlue",
            doc="""
                            What do you want to call the cropped image?""")

        self.shape = cps.Choice(
            "Select the cropping shape",
            [SH_RECTANGLE, SH_ELLIPSE, SH_IMAGE, SH_OBJECTS, SH_CROPPING],
            SH_RECTANGLE,
            doc="""
                            Into which shape would you like to crop? 
                            <ul>
                            <li><i>Rectangle:</i> Self-explanatory</li>
                            <li><i>Ellipse:</i> Self-explanatory</li>
                            <li><i>Image:</i> Cropping will occur based on a binary image you specify. A choice box 
                            with available images will appear from which 
                            you can select an image. To crop into an arbitrary shape that you define, choose 
                            <i>Image</i> and use the <b>LoadSingleImage</b> module to load a black and white image 
                            that you have already prepared from a file. If you have created this image in a 
                            program such as Photoshop, this binary image should contain only the values 0 and 255,
                            with zeros (black) for the parts you want to remove and 255 (white) for
                            the parts you want to retain. Alternately, you may have previously generated a
                            binary image using this module (e.g., using the <i>Ellipse</i> option) and saved
                            it using the <b>SaveImages</b> module.<br>
                            In any case, the image must be exactly the same starting size as your image
                            and should contain a contiguous block of white pixels, because 
                            the cropping module may remove rows and columns that are
                            completely blank.</li>
                            <li><i>Objects:</i> Crop based on labeled objects identified by a previous
                            <b>Identify</b> module.</li>
                            <li><i>Previous cropping:</i> The cropping generated by a previous cropping module.
                            A choice box with available images appears if you choose <i>Cropping</i>. The
                            images in this box are ones that were generated by previous <b>Crop</b> modules.
                            This <b>Crop</b> module will use the same cropping that was used to generate whichever image
                            you choose.</li>
                            </ul>""")

        self.crop_method = cps.Choice(
            "Select the cropping method", [CM_COORDINATES, CM_MOUSE],
            CM_COORDINATES,
            doc="""                                      
                            Would you like to crop by typing in pixel coordinates or clicking with the mouse?
                            <ul>
                            <li><i>Coordinates:</i> For <i>Ellipse</i>, you will be asked to enter the geometric
                            parameters of the ellipse. For <i>Rectangle</i>, you will be asked to specify
                            the coordinates of the corners.</li> 
                            <li><i>Mouse:</i> For <i>Ellipse</i>, you will be asked to click five or more
                            points to define an ellipse around the part of the image you want to
                            analyze.  Keep in mind that the more points you click, the longer it will
                            take to calculate the ellipse shape. For <i>Rectangle</i>, you can click as many
                            points as you like that are in the interior of the region you wish to
                            retain.</li>
                            </ul>""")

        self.individual_or_once = cps.Choice(
            "Apply which cycle's cropping pattern?",
            [IO_INDIVIDUALLY, IO_FIRST],
            IO_INDIVIDUALLY,
            doc="""
                            Should the cropping pattern in the first image cycle be 
                            applied to all subsequent image cycles (<i>First</i>) or 
                            should every image cycle be cropped individually (<i>Every</i>)?"""
        )

        self.horizontal_limits = cps.IntegerOrUnboundedRange(
            "Left and right rectangle positions",
            minval=0,
            doc="""
                            <i>(Used only if Rectangle selected as cropping shape, or if using Plate Fix)</i><br>
                            Specify the left and right positions for the bounding rectangle by selecting one of the following:<br>
                            <ul>
                            <li><i>Absolute</i> to specify these values as absolute pixel
                            coordinates in the original image. For instance, you might enter
                            "25", "225", and "Absolute" to create a 200x200 pixel image that is
                            25 pixels from the top-left corner.</li>
                            <li><i>From edge</i> to specify position relative to the original image's
                            edge. For instance, you might enter "25", "25", and "Edge" to
                            crop 25 pixels from both the left and right edges of the image, irrespective
                            of the image's original size.</li>
                            </ul>""")

        self.vertical_limits = cps.IntegerOrUnboundedRange(
            "Top and bottom rectangle positions",
            minval=0,
            doc="""
                            <i>(Used only if Rectangle selected as cropping shape, or if using Plate Fix)</i><br>
                            Specify the top and bottom positions for the bounding rectangle by selecting one of the following:<br>
                            <ul>
                            <li><i>Absolute</i> to specify these values as absolute pixel coordinates.
                            For instance, you might enter "25", "225", and "Absolute" 
                            to create a 200x200 pixel image that's 25 pixels 
                            from the top-left corner.</li>
                            <li><i>From edge</i> to specify position relative to the image edge.
                            For instance, you might enter "25", "25", and "Edge" to
                            crop 25 pixels from the edges of your images irrespective
                            of their size.</li>
                            </ul>""")

        self.ellipse_center = cps.Coordinates("Coordinates of ellipse center",
                                              (500, 500),
                                              doc="""
                            <i>(Used only if Ellipse selected as cropping shape)</i><br>
                            What is the center pixel position of the ellipse?"""
                                              )

        self.ellipse_x_radius = cps.Integer("Ellipse radius, X direction",
                                            400,
                                            doc="""
                            <i>(Used only if Ellipse selected as cropping shape)</i><br>
                            What is the radius of the ellipse in the X direction?"""
                                            )

        self.ellipse_y_radius = cps.Integer("Ellipse radius, Y direction",
                                            200,
                                            doc="""
                            <i>(Used only if Ellipse selected as cropping shape)</i><br>
                            What is the radius of the ellipse in the Y direction?"""
                                            )

        self.image_mask_source = cps.ImageNameSubscriber(
            "Select the masking image",
            "None",
            doc="""
                            <i>(Used only if Image selected as cropping shape)</i><br>
                            What is the name of the image to use as a cropping mask?"""
        )

        self.cropping_mask_source = cps.CroppingNameSubscriber(
            "Select the image with a cropping mask",
            "None",
            doc="""
                            <i>(Used only if Previous Cropping selected as cropping shape)</i><br>
                            What is the name of the image with the associated cropping mask?"""
        )

        self.objects_source = cps.ObjectNameSubscriber("Select the objects",
                                                       "None",
                                                       doc="""
                            <i>(Used only if Objects selected as cropping shape)</i><br>
                            What are the objects to be used as a cropping mask?"""
                                                       )

        self.use_plate_fix = cps.Binary("Use Plate Fix?",
                                        False,
                                        doc="""
                            <i>(Used only if Image selected as cropping shape)</i><br>
                            Do you want to use Plate Fix? When attempting to crop based on a previously identified object
                            such as a rectangular plate, the plate may not have
                            precisely straight edges: there might be a tiny, almost unnoticeable
                            "appendage" sticking out. Without Plate Fix, the <b>Crop</b>
                            module would not crop the image tightly enough: it would retain the tiny appendage, leaving a lot
                            of blank space around the plate and potentially causing problems with later
                            modules (especially IlluminationCorrection). Plate Fix takes the
                            identified object and crops to exclude any minor appendages (technically,
                            any horizontal or vertical line where the object covers less than 50% of
                            the image). It also sets pixels around the edge of the object (for
                            regions greater than 50% but less than 100%) that otherwise would be 0 to the
                            background pixel value of your image, thus avoiding problems with
                            other modules. <i>Important note:</i> Plate Fix uses the coordinates
                            entered in the boxes normally used for rectangle cropping (Top, Left and
                            Bottom, Right) to tighten the edges around your identified plate. This
                            is done because in the majority of plate identifications you do not want
                            to include the sides of the plate. If you would like the entire plate to
                            be shown, you should enter "1:end" for both coordinates. If, for example, you would like
                            to crop 80 pixels from each edge of the plate, you could enter Top, Left and Bottom, Right values of 80 and select <i>From edge</i>."""
                                        )

        self.remove_rows_and_columns = cps.Choice(
            "Remove empty rows and columns?", [RM_NO, RM_EDGES, RM_ALL],
            RM_NO,
            doc="""
                            Do you want to remove rows and columns that lack objects? Options are:
                            <ul>
                            <li><i>No:</i> Leave the image the same size. The cropped areas will be turned to black (zeroes)</li>
                            <li><i>Edges:</i> Crop the image so that its top, bottom, left and right are at
                            the first nonblank pixel for that edge</li>
                            <li><i>All:</i> Remove any row or column of all-blank pixels, even from the
                            internal portion of the image</li>
                            </ul>""")
Пример #11
0
    def create_settings(self):
        self.objects_name = cps.ObjectNameSubscriber(
            "Select the input objects",
            cps.NONE,
            doc="""Select the objects whose object numbers you want to reassign.
            You can use any objects that were created in previous modules, such as 
            <b>IdentifyPrimaryObjects</b> or <b>IdentifySecondaryObjects</b>."""
        )

        self.output_objects_name = cps.ObjectNameProvider(
            "Name the new objects",
            "RelabeledNuclei",
            doc=
            """What do you want to call the objects whose numbers have been reassigned?
            You can use this name in subsequent
            modules that take objects as inputs.""")

        self.relabel_option = cps.Choice(
            "Operation to perform", [OPTION_UNIFY, OPTION_SPLIT],
            doc=
            """Choose <i>Unify</i> to assign adjacent or nearby objects the same
            object number. Choose <i>Split</i> to give a unique number to non-adjacent objects
            that currently share the same object number.""")

        self.unify_option = cps.Choice("Unification to perform",
                                       [UNIFY_DISTANCE, UNIFY_PARENT],
                                       doc="""
            <i>(Used only with the Unify option)</i><br>
            You can unify objects in one of two ways:
            <ul>
            <li><i>%(UNIFY_DISTANCE)s: </i> All objects within a certain pixel radius 
            from each other will be unified</li>
            <li><i>%(UNIFY_PARENT)s: </i>All objects which share the same parent 
            relationship to another object will be unified. This is not be confused
            with using the <b>RelateObjects</b> module, in which the related objects
            remain as individual objects. See <b>RelateObjects</b> for more details.</li>
            </ul>
            """ % globals())

        self.parent_object = cps.Choice("Select the parent object", [cps.NONE],
                                        choices_fn=self.get_parent_choices,
                                        doc="""
            Select the parent object that will be used to
            unify the child objects. Please note the following:
            <ul>
            <li>You must have established a parent-child relationship
            between the objects using a prior <b>RelateObjects</b> module.</li>
            <li>Primary objects and their associated secondary objects are
            already in a one-to-one parent-child relationship, so it makes no
            sense to unify them here.</li>
            </ul>""")

        self.distance_threshold = cps.Integer(
            "Maximum distance within which to unify objects",
            0,
            minval=0,
            doc="""
            <i>(Used only when Unifying by distance)</i><br>
            Objects that are less than or equal to the distance
            you enter here, in pixels, will be unified. If you choose zero 
            (the default), only objects that are touching will be unified. 
            Note that <i>Unify</i> will not actually connect or bridge
            the two objects by adding any new pixels; it simply assigns the same object number
            to the portions of the object. The new, unified object
            may therefore consist of two or more unconnected components.""")

        self.wants_image = cps.Binary("Unify using a grayscale image?",
                                      False,
                                      doc="""
            <i>(Used only with the unify option)</i><br>
            <i>Unify</i> can use the objects' intensity features to determine whether two
            objects should be unified. If you choose to use a grayscale image,
            <i>Unify</i> will unify two objects only if they
            are within the distance you have specified <i>and</i> certain criteria about the objects
            within the grayscale image are met.""")

        self.image_name = cps.ImageNameSubscriber(
            "Select the grayscale image to guide unification",
            cps.NONE,
            doc="""
            <i>(Used only if a grayscale image is to be used as a guide for unification)</i><br>
            Select the name of an image loaded or created by a previous module."""
        )

        self.minimum_intensity_fraction = cps.Float(
            "Minimum intensity fraction",
            .9,
            minval=0,
            maxval=1,
            doc="""
            <i>(Used only if a grayscale image is to be used as a guide for unification)</i><br>
            Select the minimum acceptable intensity fraction. This will be used 
            as described for the method you choose in the next setting.""")

        self.where_algorithm = cps.Choice("Method to find object intensity",
                                          [CA_CLOSEST_POINT, CA_CENTROIDS],
                                          doc="""
            <i>(Used only if a grayscale image is to be used as a guide for unification)</i><br>
            You can use one of two methods to determine whether two
            objects should unified, assuming they meet the distance criteria (as specified above):
            <ul>
            <li><i>Centroids:</i> When the module considers merging two objects, 
            this method identifies the centroid of each object, 
            records the intensity value of the dimmer of the two centroids, 
            multiplies this value by the <i>minimum intensity fraction</i> to generate a threshold,
            and draws a line between the centroids. The method will unify the 
            two objects only if the intensity of every point along the line is above 
            the threshold. For instance, if the intensity
            of one centroid is 0.75 and the other is 0.50 and the <i>minimum intensity fraction</i>
            has been chosen to be 0.9, all points along the line would need to have an intensity
            of min(0.75, 0.50) * 0.9 = 0.50 * 0.9 = 0.45.<br>
            This method works well for round cells whose maximum intensity
            is in the center of the cell: a single cell that was incorrectly segmented 
            into two objects will typically not have a dim line between the centroids 
            of the two halves and will be correctly unified.</li>
            
            <li><i>Closest point:</i> This method is useful for unifying irregularly shaped cells 
            which are connected. It starts by assigning background pixels in the vicinity of the objects to the nearest
            object. Objects are then unified if each object has background pixels that are:
            <ul>
            <li>Within a distance threshold from each object;</li>
            <li>Above the minimum intensity fraction of the nearest object pixel;</li>
            <li>Adjacent to background pixels assigned to a neighboring object.</li>
            </ul>
            An example of a feature that satisfies the above constraints is a line of
            pixels that connect two neighboring objects and is roughly the same intensity 
            as the boundary pixels of both (such as an axon connecting two neurons).</li>
            </ul>""")

        self.wants_outlines = cps.Binary(
            "Retain outlines of the relabeled objests?",
            False,
            doc="""<i>(Used only if objects are output)</i><br>
            Check this setting if you want to save an image of the outlines
            of the relabeled objects.""")

        self.outlines_name = cps.OutlineNameProvider(
            'Name the outlines',
            'RelabeledNucleiOutlines',
            doc="""<i>(Used only if outlined are to be retained)</i><br>
            Enter a name that will allow the outlines to be selected later in the pipeline."""
        )
Пример #12
0
 def create_settings(self):
     #
     # The ImageNameSubscriber "subscribes" to all ImageNameProviders in
     # prior modules. Modules before yours will put images into CellProfiler.
     # The ImageSubscriber gives your user a list of these images
     # which can then be used as inputs in your module.
     #
     self.input_image_name = cps.ImageNameSubscriber(
         # The text to the left of the edit box
         "Input image name:",
         # HTML help that gets displayed when the user presses the
         # help button to the right of the edit box
         doc="""This is the image that the module operates on. You can
         choose any image that is made available by a prior module.
         <br>
         <b>ImageTemplate</b> will do something to this image.
         """)
     #
     # The ImageNameProvider makes the image available to subsequent
     # modules.
     #
     self.output_image_name = cps.ImageNameProvider(
         "Output image name:",
         # The second parameter holds a suggested name for the image.
         "OutputImage",
         doc="""This is the image resulting from the operation.""")
     #
     # Here's a choice box - the user gets a drop-down list of what
     # can be done.
     #
     self.gradient_choice = cps.Choice(
         "Gradient choice:",
         # The choice takes a list of possibilities. The first one
         # is the default - the one the user will typically choose.
         [GRADIENT_MAGNITUDE, GRADIENT_DIRECTION_X, GRADIENT_DIRECTION_Y],
         #
         # Here, in the documentation, we do a little trick so that
         # we use the actual text that's displayed in the documentation.
         #
         # %(GRADIENT_MAGNITUDE)s will get changed into "Gradient magnitude"
         # etc. Python will look in globals() for the "GRADIENT_" names
         # and paste them in where it sees %(GRADIENT_...)s
         #
         # The <ul> and <li> tags make a neat bullet-point list in the docs
         #
         doc="""Choose what to calculate:
         <ul>
         <li><i>%(GRADIENT_MAGNITUDE)s</i> to calculate the
         magnitude of the gradient at each pixel.</li>
         <li><i>%(GRADIENT_DIRECTION_X)s</i> to get the relative contribution
         of the gradient in the X direction (.5 = no contribution,
         0 to .5 = decreasing with increasing X, .5 to 1 = increasing
         with increasing X).</li>
         <li><i>%(GRADIENT_DIRECTION_Y)s</i> to get the relative
         contribution of the gradient in the Y direction.</li></ul>
         """ % globals())
     #
     # A binary setting displays a checkbox.
     #
     self.automatic_smoothing = cps.Binary(
         "Automatically choose the smoothing scale?",
         # The default value is to choose automatically
         True,
         doc="""The module will automatically choose a 
         smoothing scale for you if you leave this checked.""")
     #
     # We do a little smoothing which supplies a scale to the gradient.
     #
     # We use a float setting so that the user can give us a number
     # for the scale. The control will turn red if the user types in
     # an invalid scale.
     #
     self.scale = cps.Float(
         "Scale:",
         # The default value is 1 - a short-range scale
         1,
         # We don't let the user type in really small values
         minval=.1,
         # or large values
         maxval=100,
         doc="""This is a scaling factor that supplies the sigma for
         a gaussian that's used to smooth the image. The gradient is
         calculated on the smoothed image, so large scales will give
         you long-range gradients and small scales will give you
         short-range gradients""")
Пример #13
0
    def create_settings(self):
        threshold_methods = [
            method for method in TM_METHODS if method != TM_BINARY_IMAGE
        ]

        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  doc='''
            Choose the image to be thresholded.''')

        self.thresholded_image_name = cps.ImageNameProvider(
            "Name the output image",
            "ThreshBlue",
            doc='''
            Enter a name for the thresholded image.''')

        self.binary = cps.Choice("Select the output image type",
                                 [GRAYSCALE, BINARY],
                                 doc='''
            Two types of output images can be produced:<br>
            <ul>
            <li><i>%(GRAYSCALE)s:</i> The pixels that are retained after some pixels 
            are set to zero or shifted (based on your selections for thresholding 
            options) will have their original 
            intensity values.</li>
            <li><i>%(BINARY)s:</i> The pixels that are retained after some pixels are 
            set to zero (based on your selections for thresholding options) will be 
            white and all other pixels will be black (zeroes).</li>
            </ul>''' % globals())

        # if not binary:
        self.low_or_high = cps.Choice(
            "Set pixels below or above the threshold to zero?",
            [TH_BELOW_THRESHOLD, TH_ABOVE_THRESHOLD],
            doc="""
            <i>(Used only when "%(GRAYSCALE)s" thresholding is selected)</i><br>
            This option adjusts how pixels above or below the threshold are handled:
            <ul>
            <li><i>%(TH_BELOW_THRESHOLD)s:</i> Set the dim pixels below 
            the threshold to zero.</li>
            <li><i>%(TH_ABOVE_THRESHOLD)s:</i> Set the bright pixels above the 
            threshold to zero.</li>
            </ul>
            """ % globals())

        # if not binary and below threshold

        self.shift = cps.Binary(
            "Subtract the threshold value from the remaining pixel intensities?",
            False,
            doc='''
            <i>(Used only if the output image is %(GRAYSCALE)s and pixels below a given intensity are to be set to zero)</i><br>
            Select <i>%(YES)s</i> to shift the value of the dim pixels by the threshold value.'''
            % globals())

        # if not binary and above threshold

        self.dilation = cps.Float(
            "Number of pixels by which to expand the thresholding around those excluded bright pixels",
            0.0,
            doc='''
            <i>(Used only if the output image is grayscale and pixels above a given intensity are to be set to zero)</i><br>
            This setting is useful when attempting to exclude bright artifactual objects: 
            first, set the threshold to exclude these bright objects; it may also be desirable to expand the
            thresholded region around those bright objects by a certain distance so as to avoid a "halo" effect.'''
        )

        self.create_threshold_settings(threshold_methods)
        self.threshold_smoothing_choice.value = TSM_NONE
Пример #14
0
    def create_settings(self):
        # Input settings
        self.input_color_choice = cps.Choice("Input image type",
                                             CC_ALL,
                                             doc="""
            Specify whether you are combining several grayscale images or 
            loading a single color image.""")

        self.wants_red_input = cps.Binary("Use a red image?",
                                          True,
                                          doc="""
            Check this box to specify an image to use for the red channel.""")

        self.red_input_image = cps.ImageNameSubscriber("Select the red image",
                                                       cps.NONE)

        self.wants_green_input = cps.Binary("Use a green image?",
                                            True,
                                            doc="""
            Check this box to specify an image to use for the green channel."""
                                            )

        self.green_input_image = cps.ImageNameSubscriber(
            "Select the green image", cps.NONE)

        self.wants_blue_input = cps.Binary("Use a blue image?",
                                           True,
                                           doc="""
            Check this box to specify an image to use for the blue channel.""")

        self.blue_input_image = cps.ImageNameSubscriber(
            "Select the blue image", cps.NONE)

        self.color_input_image = cps.ImageNameSubscriber(
            "Select the color image",
            cps.NONE,
            doc='''
            Select the color image to use.''')

        # Output settings
        self.output_color_choice = cps.Choice("Output image type",
                                              CC_ALL,
                                              doc="""
            Specify whether you want to produce several grayscale images or one color image."""
                                              )

        self.wants_red_output = cps.Binary("Produce a red image?", True)

        self.red_output_image = cps.ImageNameProvider("Name the red image",
                                                      "InvertedRed")

        self.wants_green_output = cps.Binary("Produce a green image?", True)

        self.green_output_image = cps.ImageNameProvider(
            "Name the green image", "InvertedGreen")

        self.wants_blue_output = cps.Binary("Produce a blue image?", True)

        self.blue_output_image = cps.ImageNameProvider("Name the blue image",
                                                       "InvertedBlue")

        self.color_output_image = cps.ImageNameProvider(
            "Name the inverted color image",
            "InvertedColor",
            doc='''
            <i>(Used only when producing a color output image)</i><br>
            Enter a name for the inverted color image.''')
Пример #15
0
    def create_settings(self):
        """Create your settings by subclassing this function
        
        create_settings is called at the end of initialization.
        
        You should create the setting variables for your module here:
            # Ask the user for the input image
            self.image_name = cellprofiler.settings.ImageNameSubscriber(...)
            # Ask the user for the name of the output image
            self.output_image = cellprofiler.settings.ImageNameProvider(...)
            # Ask the user for a parameter
            self.smoothing_size = cellprofiler.settings.Float(...)
        """
        self.objects_or_image = cps.Choice(
            "Display object or image measurements?", [OI_OBJECTS, OI_IMAGE],
            doc="""
            <ul>
            <li><i>%(OI_OBJECTS)s</i> displays measurements made on
            objects.</li>
            <li><i>%(OI_IMAGE)s</i> displays a single measurement made
            on an image.</li> 
            </ul>""" % globals())

        self.objects_name = cps.ObjectNameSubscriber(
            "Select the input objects",
            cps.NONE,
            doc="""
            <i>(Used only when displaying object measurements)</i><br>
            Choose the name of objects identified by some previous
            module (such as <b>IdentifyPrimaryObjects</b> or
            <b>IdentifySecondaryObjects</b>).""")

        def object_fn():
            if self.objects_or_image == OI_OBJECTS:
                return self.objects_name.value
            else:
                return cpmeas.IMAGE

        self.measurement = cps.Measurement("Measurement to display",
                                           object_fn,
                                           doc="""
            Choose the measurement to display. This will be a measurement
            made by some previous module on either the whole image (if
            displaying a single image measurement) or on the objects you
            selected.""")

        self.wants_image = cps.Binary(
            "Display background image?",
            True,
            doc="""Choose whether or not to display the measurements on
            a background image. Usually, you will want to see the image
            context for the measurements, but it may be useful to save
            just the overlay of the text measurements and composite the
            overlay image and the original image later. Choose "Yes" to
            display the measurements on top of a background image or "No"
            to display the measurements on a black background.""")
        self.image_name = cps.ImageNameSubscriber(
            "Select the image on which to display the measurements",
            cps.NONE,
            doc="""
            Choose the image to be displayed behind the measurements.
            This can be any image created or loaded by a previous module.
            If you have chosen not to display the background image, the image
            will only be used to determine the dimensions of the displayed image"""
        )

        self.color_or_text = cps.Choice(
            "Display mode", [CT_TEXT, CT_COLOR],
            doc="""<i>(Used only when displaying object measurements)</i><br>
            Choose how to display the measurement information. If you choose
            %(CT_TEXT)s, <b>DisplayDataOnImage</b> will display the numeric
            value on top of each object. If you choose %(CT_COLOR)s,
            <b>DisplayDataOnImage</b> will convert the image to grayscale, if
            necessary, and display the portion of the image within each object
            using a hue that indicates the measurement value relative to
            the other objects in the set using the default color map.
            """ % globals())

        self.colormap = cps.Colormap(
            "Color map",
            doc="""<i>(Used only when displaying object measurements)</i><br>
            This is the color map used as the color gradient for coloring the
            objects by their measurement values.
            """)
        self.text_color = cps.Color("Text color",
                                    "red",
                                    doc="""
            This is the color that will be used when displaying the text.
            """)

        self.display_image = cps.ImageNameProvider(
            "Name the output image that has the measurements displayed",
            "DisplayImage",
            doc="""
            The name that will be given to the image with
            the measurements superimposed. You can use this name to refer to the image in
            subsequent modules (such as <b>SaveImages</b>).""")

        self.font_size = cps.Integer("Font size (points)", 10, minval=1)

        self.decimals = cps.Integer("Number of decimals", 2, minval=0)

        self.saved_image_contents = cps.Choice("Image elements to save",
                                               [E_IMAGE, E_FIGURE, E_AXES],
                                               doc="""
            This setting controls the level of annotation on the image:
            <ul>
            <li><i>%(E_IMAGE)s:</i> Saves the image with the overlaid measurement annotations.</li>
            <li><i>%(E_AXES)s:</i> Adds axes with tick marks and image coordinates.</li>
            <li><i>%(E_FIGURE)s:</i> Adds a title and other decorations.</li></ul>"""
                                               % globals())

        self.offset = cps.Integer("Annotation offset (in pixels)",
                                  0,
                                  doc="""
            Add a pixel offset to the measurement. Normally, the text is
            placed at the object (or image) center, which can obscure relevant features of
            the object. This setting adds a specified offset to the text, in a random
            direction.""")

        self.color_map_scale_choice = cps.Choice(
            "Color map scale", [CMS_USE_MEASUREMENT_RANGE, CMS_MANUAL],
            doc="""<i>(Used only when displaying object measurements as a 
            colormap)</i><br>
            <b>DisplayDataOnImage</b> assigns a color to each object's
            measurement value from a colormap when in colormap-mode, mapping
            the value to a color along the colormap's continuum. This mapping
            has implicit upper and lower bounds to its range which are the
            extremes of the colormap. This setting determines whether the
            extremes are the minimum and maximum values of the measurement
            from among the objects in the current image or manually-entered
            extremes. 
            <ul>
            <li><i>%(CMS_USE_MEASUREMENT_RANGE)s:</i> Use
            the full range of colors to get the maximum contrast within the
            image. </li>
            <li><i>%(CMS_MANUAL)s:</i> Manually set the upper and
            lower bounds so that images with different maxima and minima
            can be compared by a uniform color mapping.</li>
            </ul>
            """ % globals())
        self.color_map_scale = cps.FloatRange(
            "Color map range",
            value=(0.0, 1.0),
            doc="""<i>(Used only when setting a manual colormap range)</i><br>
            This setting determines the lower and upper bounds of the values
            for the color map.
            """)
Пример #16
0
    def create_settings(self):
        '''Create the settings for the ExportToCellH5 module'''
        self.directory = cps.DirectoryPath(
            "Output file location",
            doc = """
            This setting lets you choose the folder for the output files.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s
            """ % globals())
        
        def get_directory_fn():
            '''Get the directory for the CellH5 file'''
            return self.directory.get_absolute_path()
        
        def set_directory_fn(path):
            dir_choice, custom_path = self.directory.get_parts_from_path(path)
            self.directory.join_parts(dir_choice, custom_path)
        
        self.file_name = cps.FilenameText(
            "Output file name", "DefaultOut.ch5",
            get_directory_fn = get_directory_fn,
            set_directory_fn = set_directory_fn,
            metadata = True,
            browse_msg = "Choose CellH5 file",
            mode = cps.FilenameText.MODE_APPEND,
            exts = [("CellH5 file (*.cellh5)", "*.ch5"),
                    ("HDF5 file (*.h5)", "*.h5"),
                    ("All files (*.*", "*.*")],
            doc = """
            This setting lets you name your CellH5 file. If you choose an
            existing file, CellProfiler will add new data to the file
            or overwrite existing locations.
            <p>%(IO_WITH_METADATA_HELP_TEXT)s %(USING_METADATA_TAGS_REF)s. 
            For instance, if you have a metadata tag named 
            "Plate", you can create a per-plate folder by selecting one the subfolder options
            and then specifying the subfolder name as "\g&lt;Plate&gt;". The module will 
            substitute the metadata values for the current image set for any metadata tags in the 
            folder name.%(USING_METADATA_HELP_REF)s.</p>

            """ % globals())
        self.overwrite_ok = cps.Binary(
            "Overwrite existing data without warning?", False,
            doc="""
            Select <i>%(YES)s</i> to automatically overwrite any existing data
            for a site. Select <i>%(NO)s</i> to be prompted first.
            
            If you are running the pipeline on a computing cluster,
            select <i>%(YES)s</i> unless you want execution to stop because you
            will not be prompted to intervene. Also note that two instances
            of CellProfiler cannot write to the same file at the same time,
            so you must ensure that separate names are used on a cluster.
            """ % globals())
        self.repack = cps.Binary(
            "Repack after analysis", True,
            doc="""
            This setting determines whether CellProfiler in multiprocessing mode
            repacks the data at the end of analysis. If you select <i>%(YES)s</i>,
            CellProfiler will combine all of the satellite files into a single
            file upon completion. This option requires some extra temporary disk
            space and takes some time at the end of analysis, but results in
            a single file which may occupy less disk space. If you select
            <i>%(NO)s</i>, CellProfiler will create a master file using the
            name that you give and this file will have links to individual
            data files that contain the actual data. Using the data generated by
            this option requires that you keep the master file and the linked
            files together when copying them to a new folder.
            """ % globals())
        self.plate_metadata = cps.Choice(
            "Plate metadata", [], value="Plate", 
            choices_fn=self.get_metadata_choices,
            doc="""
            This is the metadata tag that identifies the plate name of
            the images for the current cycle. Choose <i>None</i> if
            your assay does not have metadata for plate name. If your
            assay is slide-based, you can use a metadata item that identifies
            the slide as the choice for this setting and set the well
            and site metadata items to <i>None</i>.""")
        self.well_metadata = cps.Choice(
            "Well metadata", [], value="Well", 
            choices_fn=self.get_metadata_choices,
            doc = """This is the metadata tag that identifies the well name
            for the images in the current cycle. Choose <i>None</i> if
            your assay does not have metadata for the well.""")
        self.site_metadata = cps.Choice(
            "Site metadata", [], value="Site",
            choices_fn = self.get_metadata_choices,
            doc = 
            """This is the metadata tag that identifies the site name
            for the images in the current cycle. Choose <i>None</i> if
            your assay doesn't divide wells up into sites or if this
            tag is not required for other reasons.""")
        self.divider = cps.Divider()
        self.wants_to_choose_measurements = cps.Binary(
            "Choose measurements?", False,
            doc="""
            This setting lets you choose between exporting all measurements or
            just the ones that you choose. Select <i>%(YES)s</i> to pick the
            measurements to be exported. Select <i>%(NO)s</i> to automatically
            export all measurements available at this stage of the pipeline.
            """ % globals()) 
        self.measurements = cps.MeasurementMultiChoice(
            "Measurements to export",
            doc = """
            <i>(Used only if choosing measurements.)</i>
            <br>
            This setting lets you choose individual measurements to be exported.
            Check the measurements you want to export.
            """)
        self.objects_to_export = []
        self.add_objects_button = cps.DoSomething(
            "Add objects to export", "Add objects",
            self.add_objects)
        self.images_to_export = []
        self.add_image_button = cps.DoSomething(
            "Add an image to export", "Add image",
            self.add_image)
        self.objects_count = cps.HiddenCount(self.objects_to_export)
        self.images_count = cps.HiddenCount(self.images_to_export)
Пример #17
0
    def create_settings(self):
        #XXX needs to use cps.SettingsGroup
        class Operand(object):
            '''Represents the collection of settings needed by each operand'''
            def __init__(self, index, operation):
                self.__index = index
                self.__operation = operation
                self.__operand_choice = cps.Choice(self.operand_choice_text(),
                                                   MC_ALL,
                                                   doc="""
                                            Is the operand an image or object measurement?"""
                                                   )

                self.__operand_objects = cps.ObjectNameSubscriber(
                    self.operand_objects_text(),
                    "None",
                    doc="""
                                            Which objects do you want to measure for this operation?"""
                )

                self.__operand_measurement = cps.Measurement(
                    self.operand_measurement_text(),
                    self.object_fn,
                    doc="""
                                            Enter the category that was used to create the measurement. You
                                            will be prompted to add additional information depending on 
                                            the type of measurement that is requested."""
                )

                self.__multiplicand = cps.Float(
                    "Multiply the above operand by",
                    1,
                    doc="""
                                            By what number would you like to multiply the above operand?"""
                )

                self.__exponent = cps.Float(
                    "Raise the power of above operand by",
                    1,
                    doc="""
                                            To what power would you like to raise the above operand?"""
                )

            @property
            def operand_choice(self):
                '''Either MC_IMAGE for image measurements or MC_OBJECT for object'''
                return self.__operand_choice

            @property
            def operand_objects(self):
                '''Get measurements from these objects'''
                return self.__operand_objects

            @property
            def operand_measurement(self):
                '''The measurement providing the value of the operand'''
                return self.__operand_measurement

            @property
            def multiplicand(self):
                '''Premultiply the measurement by this value'''
                return self.__multiplicand

            @property
            def exponent(self):
                '''Raise the measurement to this power'''
                return self.__exponent

            @property
            def object(self):
                '''The name of the object for measurement or "Image"'''
                if self.operand_choice == MC_IMAGE:
                    return cpmeas.IMAGE
                else:
                    return self.operand_objects.value

            def object_fn(self):
                if self.__operand_choice == MC_IMAGE:
                    return cpmeas.IMAGE
                elif self.__operand_choice == MC_OBJECT:
                    return self.__operand_objects.value
                else:
                    raise NotImplementedError(
                        "Measurement type %s is not supported" %
                        self.__operand_choice.value)

            def operand_name(self):
                '''A fancy name based on what operation is being performed'''
                if self.__index == 0:
                    return ("first operand" if self.__operation
                            in (O_ADD, O_MULTIPLY) else "minuend"
                            if self.__operation == O_SUBTRACT else "numerator")
                elif self.__index == 1:
                    return ("second operand" if self.__operation
                            in (O_ADD, O_MULTIPLY) else "subtrahend" if
                            self.__operation == O_SUBTRACT else "denominator")

            def operand_choice_text(self):
                return self.operand_text("Select the %s measurement type")

            def operand_objects_text(self):
                return self.operand_text("Select the %s objects")

            def operand_text(self, format):
                return format % self.operand_name()

            def operand_measurement_text(self):
                return self.operand_text("Select the %s measurement")

            def settings(self):
                '''The operand settings to be saved in the output file'''
                return [
                    self.operand_choice, self.operand_objects,
                    self.operand_measurement, self.multiplicand, self.exponent
                ]

            def visible_settings(self):
                '''The operand settings to be displayed'''
                self.operand_choice.text = self.operand_choice_text()
                self.operand_objects.text = self.operand_objects_text()
                self.operand_measurement.text = self.operand_measurement_text()
                result = [self.operand_choice]
                result += ([self.operand_objects] if self.operand_choice == MC_OBJECT \
                          else [])
                result += [
                    self.operand_measurement, self.multiplicand, self.exponent
                ]
                return (result)

        self.output_feature_name = cps.Text("Name the output measurement",
                                            "Measurement",
                                            doc="""
                                            What do you want to call the measurement calculated by this module?"""
                                            )

        self.operation = cps.Choice("Operation",
                                    O_ALL,
                                    doc="""
                                    What arithmetic operation would you like to perform? <i>None</i> is useful if 
                                    you simply want to select some of the later options in the module, such as multiplying
                                    or exponentiating your image by a constant."""
                                    )

        self.operands = (Operand(0,
                                 self.operation), Operand(1, self.operation))

        self.spacer_1 = cps.Divider(line=True)

        self.spacer_2 = cps.Divider(line=True)

        self.spacer_3 = cps.Divider(line=True)

        self.wants_log = cps.Binary("Take log10 of result?",
                                    False,
                                    doc="""
                                    Do you want the log (base 10) of the result?"""
                                    )

        self.final_multiplicand = cps.Float("Multiply the result by",
                                            1,
                                            doc="""
                                    <i>(Used only for operations other than None)</i><br>
                                    By what number would you like to multiply the result?"""
                                            )

        self.final_exponent = cps.Float("Raise the power of result by",
                                        1,
                                        doc="""
                                    <i>(Used only for operations other than None)</i><br>
                                    To what power would you like to raise the result?"""
                                        )

        self.final_addend = cps.Float("Add to the result",
                                      0,
                                      doc="""
                                    What number would you like to add to the result?"""
                                      )

        self.constrain_lower_bound = cps.Binary(
            "Constrain the result to a lower bound?",
            False,
            doc="""
                                    Check this setting if you want the result to be 
                                    constrained to a lower bound.""")

        self.lower_bound = cps.Float("Enter the lower bound",
                                     0,
                                     doc="""
                                    Enter the lower bound here.""")

        self.constrain_upper_bound = cps.Binary(
            "Constrain the result to an upper bound?",
            False,
            doc="""
                                    Check this setting if you want the result to be 
                                    constrained to an upper bound.""")

        self.upper_bound = cps.Float("Enter the upper bound",
                                     1,
                                     doc="""
                                    Enter the upper bound here.""")
Пример #18
0
 def create_settings(self):
     '''Create the UI settings for this module'''
     
     self.recipients = []
     self.recipient_count = cps.HiddenCount(self.recipients)
     self.add_recipient(False)
     self.add_recipient_button = cps.DoSomething(
         "Add a recipient address.",
         "Add address",
         self.add_recipient)
     
     if sys.platform.startswith("win"):
         user = os.environ.get("USERNAME","yourname@yourdomain")
     else:
         user = os.environ.get("USER","yourname@yourdomain")
         
     self.from_address = cps.Text(
         "Sender address", user,
         doc="""Enter the address for the email's "From" field.""")
     
     self.subject = cps.Text(
         "Subject line","CellProfiler notification",
         metadata=True,
         doc="""Enter the text for the email's subject line. If you have metadata 
         associated with your images, you can use metadata tags here. %(USING_METADATA_TAGS_REF)s<br>
         For instance, if you have plate metadata,
         you might use the line, "CellProfiler: processing plate " and insert the metadata tag
         for the plate at the end. %(USING_METADATA_HELP_REF)s."""%globals())
     
     self.smtp_server = cps.Text(
         "Server name", "mail",
         doc="""Enter the address of your SMTP server. You can ask your
         network administrator for your outgoing mail server which is often
         made up of part of your email address, e.g., 
         "*****@*****.**". You might be able to find this information
         by checking your settings or preferences in whatever email program
         you use.""")
     
     self.port = cps.Integer(
         "Port", smtplib.SMTP_PORT, 0, 65535,
         doc="""Enter your server's SMTP port. The default (25) is the
         port used by most SMTP servers. Your network administrator may
         have set up SMTP to use a different port; also, the connection
         security settings may require a different port.""")
     
     self.connection_security = cps.Choice(
         "Select connection security", C_ALL,
         doc="""Select the connection security. Your network administrator 
         can tell you which setting is appropriate, or you can check the
         settings on your favorite email program.""")
     
     self.use_authentication = cps.Binary(
         "Username and password required to login?", False,
         doc="""Check this box if you need to enter a username and password 
         to authenticate.""")
     
     self.username = cps.Text(
         "Username", user,
         doc="""Enter your server's SMTP username.""")
     
     self.password = cps.Text(
         "Password", "",
         doc="""Enter your server's SMTP password.""")
     
     self.when = []
     self.when_count = cps.HiddenCount(self.when)
     self.add_when(False)
     
     self.add_when_button = cps.DoSomething(
         "Add another email event","Add event", self.add_when,
         doc="""Press this button to add another event or condition.
         <b>SendEmail</b> will send an email when this event happens""")
Пример #19
0
    def create_settings(self):
        self.delimiter = cps.CustomChoice(
            'Select or enter the column delimiter',
            DELIMITERS,
            doc="""
                            What delimiter do you want to use? This is the character that separates columns in a file. The
                            two default choices are tab and comma, but you can type in any single character delimiter you would prefer. Be sure that the delimiter you choose is not a character that is present within your data (for example, in file names)."""
        )

        self.prepend_output_filename = cps.Binary(
            "Prepend the output file name to the data file names?",
            True,
            doc="""
                            This can be useful if you want to run a pipeline multiple 
                            times without overwriting the old results.""")

        self.directory = cps.DirectoryPath(
            "Output file location",
            dir_choices=[
                DEFAULT_OUTPUT_FOLDER_NAME, DEFAULT_INPUT_FOLDER_NAME,
                ABSOLUTE_FOLDER_NAME, DEFAULT_INPUT_SUBFOLDER_NAME,
                DEFAULT_OUTPUT_SUBFOLDER_NAME
            ],
            doc="""This setting lets you choose the folder for the output
            files. %(IO_FOLDER_CHOICE_HELP_TEXT)s
            
            <p>%(IO_WITH_METADATA_HELP_TEXT)s %(USING_METADATA_TAGS_REF)s<br>
            For instance, if you have a metadata tag named 
            "Plate", you can create a per-plate folder by selecting one of the subfolder options
            and then specifying the subfolder name as "\g&lt;Plate&gt;". The module will 
            substitute the metadata values for the current image set for any metadata tags in the 
            folder name. %(USING_METADATA_HELP_REF)s.</p>""" % globals())

        self.add_metadata = cps.Binary(
            "Add image metadata columns to your object data file?",
            False,
            doc=
            """"Image_Metadata_" columns are normally exported in the Image data file, but if you check this box they will also be exported with the Object data file(s)."""
        )

        self.excel_limits = cps.Binary(
            "Limit output to a size that is allowed in Excel?",
            False,
            doc="""
                            If your output has more than 256 columns, a window will open
                            which allows you to select the columns you'd like to export. If your output exceeds
                            65,000 rows, you can still open the .csv in Excel, but not all rows will be visible."""
        )

        self.pick_columns = cps.Binary(
            "Select the columns of measurements to export?",
            False,
            doc="""
                            Checking this setting will open up a window that allows you to select the columns to export."""
        )

        self.columns = cps.MeasurementMultiChoice(
            "Press button to select measurements to export",
            doc=
            """<i>(Used only when selecting the columns of measurements to export)</i><br>This setting controls the columns to be exported. Press
            the button and check the measurements or categories to export""")

        self.wants_aggregate_means = cps.Binary(
            "Calculate the per-image mean values for object measurements?",
            False,
            doc="""
                            <b>ExportToSpreadsheet</b> can calculate population statistics over all the 
                            objects in each image and save that value as an aggregate 
                            measurement in the Image file.  For instance, if you are measuring 
                            the area of the Nuclei objects and you check the box for this option, <b>ExportToSpreadsheet</b> will 
                            create a column in the Image file called "Mean_Nuclei_AreaShape_Area". 
                            <p>You may not want to use <b>ExportToSpreadsheet</b> to calculate these 
                            measurements if your pipeline generates a large number of per-object 
                            measurements; doing so might exceed Excel's limits on the number of columns (256). """
        )

        self.wants_aggregate_medians = cps.Binary(
            "Calculate the per-image median values for object measurements?",
            False)

        self.wants_aggregate_std = cps.Binary(
            "Calculate the per-image standard deviation values for object measurements?",
            False)

        self.wants_genepattern_file = cps.Binary(
            "Create a GenePattern GCT file?",
            False,
            doc="""
            Create a GCT file compatible with <a href="http://www.broadinstitute.org/cancer/software/genepattern/">GenePattern</a>.
            The GCT file format is a tab-delimited text file format that describes a gene expression dataset; the specifics of the
            format are described <a href="http://www.broadinstitute.org/cancer/software/genepattern/tutorial/gp_fileformats.html#gct">here</a>.
            By converting your measurements into a GCT file, you can make use of GenePattern's data visualization and clustering methods.
            
            <p>Each row in the GCT file represents (ordinarily) a gene and each column represents a sample (in this case, a per-image set
            of measurements). In addition to any other spreadsheets desired, checking this box will produce a GCT file with the 
            extension .gct, prepended with the text selection above. If per-image aggregate measurements are requested above, those 
            measurements are included in the GCT file as well.</p>""")

        self.how_to_specify_gene_name = cps.Choice(
            "Select source of sample row name",
            GP_NAME_OPTIONS,
            GP_NAME_METADATA,
            doc="""
            <i>(Used only if a GenePattern file is requested)</i><br>
            The first column of the GCT file is the unique identifier for each sample, which is ordinarily the gene name. 
            This information may be specified in one of two ways:
            <ul>
            <li><i>Metadata:</i> If you used <b>LoadData</b> or <b>LoadImages</b> to input your images, you may use a per-image data measurement 
            (such as metadata) that corresponds to the identifier for this column. %(USING_METADATA_HELP_REF)s.</li>
            <li><i>Image filename:</i> If the gene name is not available, the image filename can be used as a surrogate identifier.</li>
            </ul>""" % globals())

        self.gene_name_column = cps.Measurement(
            "Select the metadata to use as the identifier",
            lambda: cpmeas.IMAGE,
            doc="""
            <i>(Used only if a GenePattern file is requested and metadata is used to name each row)</i><br>
            Choose the measurement that corresponds to the identifier, such as metadata from <b>LoadData</b>'s input file. 
            %(USING_METADATA_HELP_REF)s.""" % globals())

        self.use_which_image_for_gene_name = cps.ImageNameSubscriber(
            "Select the image to use as the identifier",
            "None",
            doc="""
            <i>(Used only if a GenePattern file is requested and image filename is used to name each row)</i><br>
            Select which image whose filename will be used to identify each sample row."""
        )

        self.wants_everything = cps.Binary(
            "Export all measurements, using default file names?",
            True,
            doc="""Check this setting to export every measurement.
            <b>ExportToSpreadsheet</b> will create one file per object type,
            as well as per-image, per-experiment and object relationships, 
            if relevant. 
            It will use the object name as the file name, 
            optionally prepending the output file name if
            specified above. Leave this box unchecked to specify which
            objects should be exported or to override the automatic names.""")

        self.object_groups = []
        self.add_object_group()
        self.add_button = cps.DoSomething("", "Add another data set",
                                          self.add_object_group)
Пример #20
0
    def create_settings(self):
        self.scheme_choice = cps.Choice(
            "Select a color scheme",
            [SCHEME_RGB, SCHEME_CMYK, SCHEME_STACK],doc="""
            This module can use one of two color schemes to combine images:<br/>
            <ul><li><i>%(SCHEME_RGB)s</i>: Each input image determines the intensity of
            one of the color channels: red, green, and blue.</li>
            <li><i>%(SCHEME_CMYK)s</i>: Three of the input images are combined to determine
            the colors (cyan, magenta, and yellow) and a fourth is used only for brightness. The cyan
            image adds equally to the green and blue intensities. The magenta
            image adds equally to the red and blue intensities. The yellow
            image adds equally to the red and green intensities.</li>
            <li><i>%(SCHEME_STACK)s</i>: The channels are stacked in order. An arbitrary number of 
            channels is allowed.</li>
            </ul>"""%globals())
        
        # # # # # # # # # # # # # # # #
        # 
        # RGB settings
        #
        # # # # # # # # # # # # # # # #
        self.red_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored red",
            can_be_blank = True, blank_text = LEAVE_THIS_BLACK)
        
        self.green_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored green",
            can_be_blank = True, blank_text = LEAVE_THIS_BLACK)
        
        self.blue_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored blue",
            can_be_blank = True,blank_text = LEAVE_THIS_BLACK)
        
        self.rgb_image_name = cps.ImageNameProvider(
            "Name the output image","ColorImage")
        
        self.red_adjustment_factor = cps.Float(
            "Relative weight for the red image",
            value=1,minval=0,doc='''
            <i>(Used only if %(SCHEME_RGB)s is selected as the color scheme)</i><br>
            Enter the relative weight for the red image. If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        
        self.green_adjustment_factor = cps.Float(
            "Relative weight for the green image",
            value=1,minval=0,doc='''
            <i>(Used only if %(SCHEME_RGB)s is selected as the color scheme)</i><br>
            Enter the relative weight for the green image. If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        
        self.blue_adjustment_factor = cps.Float(
            "Relative weight for the blue image",
            value=1, minval=0,doc='''
            <i>(Used only if %(SCHEME_RGB)s is selected as the color scheme)</i><br>
            Enter the relative weight for the blue image. If all relative weights are equal, all three 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        # # # # # # # # # # # # # #
        #
        # CYMK settings
        #
        # # # # # # # # # # # # # #
        self.cyan_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored cyan", can_be_blank = True,
            blank_text = LEAVE_THIS_BLACK)
        
        self.magenta_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored magenta", can_be_blank = True,
            blank_text = LEAVE_THIS_BLACK)
        
        self.yellow_image_name = cps.ImageNameSubscriber(
            "Select the image to be colored yellow", can_be_blank = True,
            blank_text = LEAVE_THIS_BLACK)
        
        self.gray_image_name = cps.ImageNameSubscriber(
            "Select the image that determines brightness", can_be_blank = True,
            blank_text = LEAVE_THIS_BLACK)
        
        self.cyan_adjustment_factor = cps.Float(
            "Relative weight for the cyan image", 
            value=1, minval=0,doc='''
            <i>(Used only if %(SCHEME_CMYK)s is selected as the color scheme)</i><br>
            Enter the relative weight for the cyan image. If all relative weights are equal, all 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        
        self.magenta_adjustment_factor = cps.Float(
            "Relative weight for the magenta image", 
            value=1, minval=0,doc='''
            <i>(Used only if %(SCHEME_CMYK)s is selected as the color scheme)</i><br>
            Enter the relative weight for the magenta image. If all relative weights are equal, all 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        
        self.yellow_adjustment_factor = cps.Float(
            "Relative weight for the yellow image", 
            value=1,minval=0,doc='''
            <i>(Used only if %(SCHEME_CMYK)s is selected as the color scheme)</i><br>
            Enter the relative weight for the yellow image. If all relative weights are equal, all 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
        
        self.gray_adjustment_factor = cps.Float(
            "Relative weight for the brightness image", 
            value=1,minval=0,doc='''
            <i>(Used only if %(SCHEME_CMYK)s is selected as the color scheme)</i><br>
            Enter the relative weight for the brightness image. If all relative weights are equal, all 
            colors contribute equally in the final image. To weight colors relative to each other, 
            increase or decrease the relative weights.'''%globals())
    
        # # # # # # # # # # # # # #
        #
        # Stack settings
        #
        # # # # # # # # # # # # # #

        self.stack_channels = []
        self.add_stack_channel_cb(can_remove = False)
        self.add_stack_channel = cps.DoSomething("","Add another channel", self.add_stack_channel_cb)
Пример #21
0
    def create_settings(self):
        self.obj_or_img = cps.Choice(
            "Compare segmented objects, or foreground/background?", O_ALL)

        self.ground_truth = cps.ImageNameSubscriber(
            "Select the image to be used as the ground truth basis for calculating the amount of overlap",
            cps.NONE,
            doc="""
            <i>(Used only when comparing foreground/background)</i> <br>
            This binary (black and white) image is known as the "ground truth" image.  It can be the product of segmentation performed by hand, or
            the result of another segmentation algorithm whose results you would like to compare."""
        )

        self.test_img = cps.ImageNameSubscriber(
            "Select the image to be used to test for overlap",
            cps.NONE,
            doc="""
            <i>(Used only when comparing foreground/background)</i> <br>
            This binary (black and white) image is what you will compare with the ground truth image. It is known as the "test image"."""
        )

        self.object_name_GT = cps.ObjectNameSubscriber(
            "Select the objects to be used as the ground truth basis for calculating the amount of overlap",
            cps.NONE,
            doc="""
            <i>(Used only when comparing segmented objects)</i> <br>
            Choose which set of objects will used as the "ground truth" objects. It can be the product of segmentation performed by hand, or
            the result of another segmentation algorithm whose results you would like to compare. See the <b>Load</b> modules for more details
            on loading objects.""")

        self.object_name_ID = cps.ObjectNameSubscriber(
            "Select the objects to be tested for overlap against the ground truth",
            cps.NONE,
            doc="""
            <i>(Used only when comparing segmented objects)</i> <br>
            This set of objects is what you will compare with the ground truth objects. It is known as the "test object." """
        )
        self.wants_emd = cps.Binary(
            "Calculate earth mover's distance?",
            False,
            doc="""The earth mover's distance computes the shortest distance 
            that would have to be travelled to move each foreground pixel in the
            test image to some foreground pixel in the reference image.
            "Earth mover's" refers to an analogy: the pixels are "earth" that
            has to be moved by some machine at the smallest possible cost.
            <br>
            It would take too much memory and processing time to compute the
            exact earth mover's distance, so <b>CalculateImageOverlap</b>
            chooses representative foreground pixels in each image and
            assigns each foreground pixel to its closest representative. The
            earth mover's distance is then computed for moving the foreground
            pixels associated with each representative in the test image to
            those in the reference image.
            """)
        self.max_points = cps.Integer("Maximum # of points",
                                      value=250,
                                      minval=100,
                                      doc="""
            <i>(Used only when computing the earth mover's distance)</i> <br>
            This is the number of representative points that will be taken
            from the foreground of the test image and from the foreground of 
            the reference image using the point selection method (see below).
            """)
        self.decimation_method = cps.Choice("Point selection method",
                                            choices=[DM_KMEANS, DM_SKEL],
                                            doc="""
            <i>(Used only when computing the earth mover's distance)</i> <br>
            The point selection setting determines how the
            representative points are chosen. 
            <ul>
            <li><i>%(DM_KMEANS)s:</i> Select to pick representative points using a 
            K-Means clustering technique. The foregrounds of both images are combined 
            and representatives are picked that minimize the distance to the nearest 
            representative. The same representatives are then used for the test and 
            reference images.</li>
            <li><i>%(DM_SKEL)s:</i> Select to skeletonize the image and pick
            points eqidistant along the skeleton. </li>
            </ul>
            <dl>
            <dd><img src="memory:%(PROTIP_RECOMEND_ICON)s">&nbsp;
            <i>%(DM_KMEANS)s</i> is a
            choice that's generally applicable to all images. <i>%(DM_SKEL)s</i>
            is best suited to long, skinny objects such as worms or neurites.</dd>
            </dl>
            """ % globals())
        self.max_distance = cps.Integer("Maximum distance",
                                        value=250,
                                        minval=1,
                                        doc="""
            <i>(Used only when computing the earth mover's distance)</i> <br>
            This setting sets an upper bound to the distance penalty
            assessed during the movement calculation. As an example, the score
            for moving 10 pixels from one location to a location that is
            100 pixels away is 10*100, but if the maximum distance were set
            to 50, the score would be 10*50 instead.
            <br>
            The maximum distance should be set to the largest reasonable
            distance that pixels could be expected to move from one image
            to the next.
            """)
        self.penalize_missing = cps.Binary("Penalize missing pixels",
                                           value=False,
                                           doc="""
            <i>(Used only when computing the earth mover's distance)</i> <br>
            If one image has more foreground pixels than the other, the
            earth mover's distance is not well-defined because there is
            no destination for the extra source pixels or vice-versa.
            It's reasonable to assess a penalty for the discrepancy when
            comparing the accuracy of a segmentation because the discrepancy
            represents an error. It's also reasonable to assess no penalty
            if the goal is to compute the cost of movement, for example between
            two frames in a time-lapse movie, because the discrepancy is
            likely caused by noise or artifacts in segmentation.
            
            Set this setting to "Yes" to assess a penalty equal to the
            maximum distance times the absolute difference in number of
            foreground pixels in the two images. Set this setting to "No"
            to assess no penalty.
            """)
Пример #22
0
 def get_command_settings(self, command, d):
     '''Get the settings associated with the current command
     
     d - the dictionary that persists the setting. None = regular
     '''
     key = command.get_unicode_value()
     if not d.has_key(key):
         try:
             module_info = command.get_selected_leaf()[2]
         except cps.ValidationError:
             logger.info("Could not find command %s" % key)
             return []
         result = []
         inputs = module_info.getInputs()
         for module_item in inputs:
             field_type = module_item.getType()
             label = module_item.getLabel()
             if label is None:
                 label = module_item.getName()
             if module_item.isOutput():
                 # if both, qualify which is for input and which for output
                 label = "%s (Input)" % label
             minimum = module_item.getMinimumValue()
             maximum = module_item.getMaximumValue()
             default = module_item.loadValue()
             description = module_item.getDescription()
             if field_type == ij2.FT_BOOL:
                 value = (J.is_instance_of(default, 'java/lang/Boolean')
                          and J.call(default, "booleanValue", "()Z"))
                 setting = cps.Binary(label, value=value, doc=description)
             elif field_type == ij2.FT_INTEGER:
                 if J.is_instance_of(default, 'java/lang/Number'):
                     value = J.call(default, "intValue", "()I")
                 elif minimum is not None:
                     value = minimum
                 elif maximum is not None:
                     value = maximum
                 else:
                     value = 0
                 setting = cps.Integer(label, value=value, doc=description)
             elif field_type == ij2.FT_FLOAT:
                 if J.is_instance_of(default, 'java/lang/Number'):
                     value = J.call(default, "doubleValue", "()D")
                 elif minimum is not None:
                     value = minimum
                 elif maximum is not None:
                     value = maximum
                 else:
                     value = 0
                 setting = cps.Float(label, value=value, doc=description)
             elif field_type == ij2.FT_STRING:
                 choices = module_item.getChoices()
                 value = J.to_string(default)
                 if choices is not None:
                     choices = J.get_collection_wrapper(choices)
                     setting = cps.Choice(label,
                                          choices,
                                          value,
                                          doc=description)
                 else:
                     setting = cps.Text(label, value, doc=description)
             elif field_type == ij2.FT_COLOR:
                 value = "#ffffff"
                 setting = cps.Color(label, value, doc=description)
             elif field_type == ij2.FT_IMAGE:
                 setting = cps.ImageNameSubscriber(label,
                                                   "InputImage",
                                                   doc=description)
             elif field_type == ij2.FT_TABLE:
                 setting = IJTableSubscriber(label,
                                             "InputTable",
                                             doc=description)
             elif field_type == ij2.FT_FILE:
                 setting = cps.FilenameText(label, None, doc=description)
             else:
                 continue
             result.append((setting, module_item))
         for output in module_info.getOutputs():
             field_type = output.getType()
             label = output.getLabel()
             if label is None:
                 label = output.getName()
             if output.isInput():
                 # if both, qualify which is for input and which for output
                 label = "%s (Output)" % label
             if field_type == ij2.FT_IMAGE:
                 result.append(
                     (cps.ImageNameProvider(label,
                                            "ImageJImage",
                                            doc=description), output))
             elif field_type == ij2.FT_TABLE:
                 result.append((IJTableProvider(label,
                                                "ImageJTable",
                                                doc=description), output))
         d[key] = result
     else:
         result = d[key]
     return [setting for setting, module_info in result]
Пример #23
0
    def create_settings(self):
        self.sub_object_name = cps.ObjectNameSubscriber(
            'Select the input child objects',
            cps.NONE,
            doc="""
            Child objects are defined as those objects contained within the
            parent object. For example, when relating speckles to the
            nuclei that contains them, the speckles are the children.""")

        self.parent_name = cps.ObjectNameSubscriber(
            'Select the input parent objects',
            cps.NONE,
            doc="""
            Parent objects are defined as those objects which encompass the 
            child object. For example, when relating speckles to the
            nuclei that contains them, the nuclei are the parents.""")

        self.find_parent_child_distances = cps.Choice(
            "Calculate child-parent distances?",
            D_ALL,
            doc="""
            Choose the method to calculate distances of each child to its parent.
            <ul>
            <li><i>%(D_NONE)s:</i> Do not calculate any distances.</li>
            <li><i>%(D_MINIMUM)s:</i> The distance from the 
            centroid of the child object to the closest perimeter point on
            the parent object.</li>
            <li><i>%(D_CENTROID)s:</i> The distance from the
            centroid of the child object to the centroid of the parent. </li>
            <li><i>%(D_BOTH)s:</i> Calculate both the <i>%(D_MINIMUM)s</i> and 
            <i>%(D_CENTROID)s</i> distances.</li>
            </ul>""" % globals())

        self.wants_step_parent_distances = cps.Binary(
            "Calculate distances to other parents?",
            False,
            doc="""
            <i>(Used only if calculating distances)</i><br>
            Select <i>%(YES)s</i> to calculate the distances of the child objects to 
            some other objects. These objects must be either parents or
            children of your parent object in order for this module to
            determine the distances. For instance, you might find "Nuclei" using
            <b>IdentifyPrimaryObjects</b>, find "Cells" using
            <b>IdentifySecondaryObjects</b> and find "Cytoplasm" using
            <b>IdentifyTertiaryObjects</b>. You can use <b>Relate</b> to relate
            speckles to cells and then measure distances to nuclei and
            cytoplasm. You could not use <b>RelateObjects</b> to relate speckles to
            cytoplasm and then measure distances to nuclei, because nuclei is
            neither a direct parent or child of cytoplasm.""" % globals())
        self.step_parent_names = []

        self.add_step_parent(can_delete=False)

        self.add_step_parent_button = cps.DoSomething("", "Add another parent",
                                                      self.add_step_parent)

        self.wants_per_parent_means = cps.Binary(
            'Calculate per-parent means for all child measurements?',
            False,
            doc="""
            Select <i>%(YES)s</i> to calculate the per-parent mean values of every upstream 
            measurement made with the children objects and stores them as a
            measurement for the parent; the nomenclature of this new measurements is 
            "Mean_&lt;child&gt;_&lt;category&gt;_&lt;feature&gt;". 
            For this reason, this module should be placed <i>after</i> all <b>Measure</b>
            modules that make measurements of the children objects.""" %
            globals())
Пример #24
0
    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")
Пример #25
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber(
            "Select the input image",
            cps.NONE,
            doc='''Select the image to be rescaled.''')

        self.rescaled_image_name = cps.ImageNameProvider(
            "Name the output image",
            "RescaledBlue",
            doc='''Enter the name of output rescaled image.''')

        self.rescale_method = cps.Choice('Rescaling method',
                                         choices=M_ALL,
                                         doc='''
            There are a number of options for rescaling the input image: 
            <ul>
            <li><i>%(M_STRETCH)s:</i> Find the minimum and maximum values within the unmasked part of the image 
            (or the whole image if there is no mask) and rescale every pixel so that 
            the minimum has an intensity of zero and the maximum has an intensity of one.</li>
            <li><i>%(M_MANUAL_INPUT_RANGE)s:</i> Pixels are
            scaled from their user-specified original range to the range 0 to 1.
            Options are available to handle values outside of the original range.<br>
            To convert 12-bit images saved in 16-bit format to the correct range,
            use the range 0 to 0.0625. The value 0.0625 is equivalent 
            to 2<sup>12</sup> divided by 2<sup>16</sup>, so it will convert a 16 bit image containing 
            only 12 bits of data to the proper range.</li>
            <li><i>%(M_MANUAL_IO_RANGE)s:</i> Pixels are scaled from their original range to
            the new target range. Options are available to handle values outside
            of the original range.</li>
            <li><i>%(M_DIVIDE_BY_IMAGE_MINIMUM)s:</i> Divide the intensity value of each pixel 
            by the image's minimum intensity value so that all pixel intensities are equal to or 
            greater than 1. The rescaled image can serve as an illumination correction function in 
            <b>CorrectIlluminationApply</b>.</li>
            <li><i>%(M_DIVIDE_BY_IMAGE_MAXIMUM)s:</i> Divide the intensity value of each pixel by the 
            image's maximum intensity value so that all pixel intensities are less than or equal to 1.</li>
            <li><i>%(M_DIVIDE_BY_VALUE)s:</i> Divide the intensity value of each pixel by the value entered.</li>
            <li><i>%(M_DIVIDE_BY_MEASUREMENT)s:</i> The intensity value of each pixel is divided by some 
            previously calculated measurement. This measurement can be the output of some other module
            or can be a value loaded by the <b>Metadata</b> module.</li>
            <li><i>%(M_SCALE_BY_IMAGE_MAXIMUM)s:</i> Scale an image so that its maximum value is the 
            same as the maximum value within the reference image.</li>
            <li><i>%(M_CONVERT_TO_8_BIT)s:</i> Images in CellProfiler are normally stored as a floating 
            point number in the range of 0 to 1. This option converts these images to class uint8, 
            meaning an 8 bit integer in the range of 0 to 255, 
            reducing the amount of memory required to store the image. <i>Warning:</i> Most
            CellProfiler modules require the incoming image to be in the standard 0
            to 1 range, so this conversion may cause downstream modules to behave 
            in unexpected ways.</li>
            </ul>''' % globals())

        self.wants_automatic_low = cps.Choice(
            'Method to calculate the minimum intensity',
            LOW_ALL,
            doc="""
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" is selected)</i><br>
            This setting controls how the minimum intensity is determined.
            <ul>
            <li><i>%(CUSTOM_VALUE)s:</i> Enter the minimum intensity manually below.</li>
            <li><i>%(LOW_EACH_IMAGE)s</i>: use the lowest intensity in this image
            as the minimum intensity for rescaling</li>
            <li><i>%(LOW_ALL_IMAGES)s</i>: use the lowest intensity from all images
            in the image group or the experiment if grouping is not being used.
            <b>Note:</b> Choosing this option may have undesirable results for
            a large ungrouped experiment split into a number of batches. Each batch
            will open all images from the chosen channel at the start of the run.
            This sort of synchronized action may have a severe impact on your
            network file system.</li>
            </ul>
            """ % globals())

        self.wants_automatic_high = cps.Choice(
            'Method to calculate the maximum intensity',
            HIGH_ALL,
            doc="""
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" is selected)</i><br>
            This setting controls how the maximum intensity is determined.
            <ul>
            <li><i>%(CUSTOM_VALUE)s</i>: Enter the maximum intensity manually below.</li>
            <li><i>%(HIGH_EACH_IMAGE)s</i>: Use the highest intensity in this image
            as the maximum intensity for rescaling</li>
            <li><i>%(HIGH_ALL_IMAGES)s</i>: Use the highest intensity from all images
            in the image group or the experiment if grouping is not being used.
            <b>Note:</b> Choosing this option may have undesirable results for
            a large ungrouped experiment split into a number of batches. Each batch
            will open all images from the chosen channel at the start of the run.
            This sort of synchronized action may have a severe impact on your
            network file system.</li>
            </ul>
            """ % globals())

        self.source_low = cps.Float(
            'Lower intensity limit for the input image', 0)

        self.source_high = cps.Float(
            'Upper intensity limit for the input image', 1)

        self.source_scale = cps.FloatRange(
            'Intensity range for the input image', (0, 1))

        self.dest_scale = cps.FloatRange(
            'Intensity range for the output image', (0, 1))

        self.low_truncation_choice = cps.Choice(
            'Method to rescale pixels below the lower limit',
            [R_MASK, R_SET_TO_ZERO, R_SET_TO_CUSTOM, R_SCALE],
            doc='''
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" is selected)</i><br>
            There are several ways to handle values less than the lower limit of the intensity range:
            <ul>
            <li><i>%(R_MASK)s:</i> Creates a mask for the output image. All pixels below
            the lower limit will be masked out.</li>
            <li><i>%(R_SET_TO_ZERO)s:</i> Sets all pixels below the lower limit to zero.</li>
            <li><i>%(R_SET_TO_CUSTOM)s:</i> Sets all pixels below the lower limit to a custom
            value.</li>
            <li><i>%(R_SCALE)s:</i> Scales pixels with values below the lower limit
            using the same offset and divisor as other pixels. The results
            will be less than zero.</li>
            </ul>''' % globals())

        self.custom_low_truncation = cps.Float(
            "Custom value for pixels below lower limit",
            0,
            doc="""
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" and "%(R_SET_TO_CUSTOM)s are selected)</i><br>
            enter the custom value to be assigned to pixels with values below the lower limit."""
            % globals())

        self.high_truncation_choice = cps.Choice(
            'Method to rescale pixels above the upper limit',
            [R_MASK, R_SET_TO_ONE, R_SET_TO_CUSTOM, R_SCALE],
            doc="""
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" is selected)</i><br>
            There are several ways to handle values greater than the upper limit of the intensity range; 
            Options are described in the Help for the equivalent lower limit question."""
        )

        self.custom_high_truncation = cps.Float(
            "Custom value for pixels below upper limit",
            0,
            doc="""
            <i>(Used only if "%(M_MANUAL_IO_RANGE)s" and "%(R_SET_TO_CUSTOM)s are selected)</i><br>
            Enter the custom value to be assigned to pixels with values above the upper limit."""
        )

        self.matching_image_name = cps.ImageNameSubscriber(
            "Select image to match in maximum intensity",
            cps.NONE,
            doc="""
            <i>(Used only if "%(M_SCALE_BY_IMAGE_MAXIMUM)s" is selected)</i><br>
            Select the image whose maximum you want the rescaled image to match."""
            % globals())

        self.divisor_value = cps.Float("Divisor value",
                                       1,
                                       minval=np.finfo(float).eps,
                                       doc="""
            <i>(Used only if "%(M_DIVIDE_BY_VALUE)s" is selected)</i><br>
            Enter the value to use as the divisor for the final image.""" %
                                       globals())

        self.divisor_measurement = cps.Measurement("Divisor measurement",
                                                   lambda: cpmeas.IMAGE,
                                                   doc="""
            <i>(Used only if "%(M_DIVIDE_BY_MEASUREMENT)s" is selected)</i><br>
            Select the measurement value to use as the divisor for the final image."""
                                                   % globals())
Пример #26
0
    def add_single_measurement(self, can_delete=True):
        '''Add a single measurement to the group of single measurements
        
        can_delete - True to include a "remove" button, False if you're not
                     allowed to remove it.
        '''
        group = cps.SettingsGroup()
        if can_delete:
            group.append("divider", cps.Divider(line=True))

        group.append(
            "object_name",
            cps.ObjectNameSubscriber(
                "Select the object to be classified",
                "None",
                doc="""The name of the objects to be classified. You can
            choose from objects created by any previous module. See
            <b>IdentifyPrimaryObjects</b>, <b>IdentifySecondaryObjects</b>, or
            <b>IdentifyTertiaryObjects</b>."""))

        def object_fn():
            return group.object_name.value

        group.append(
            "measurement",
            cps.Measurement(
                "Select the measurement to classify by",
                object_fn,
                doc=
                """Select a measurement made by a previous module. The objects
            will be classified according to their values for this 
            measurement."""))
        group.append(
            "bin_choice",
            cps.Choice(
                "Select bin spacing", [BC_EVEN, BC_CUSTOM],
                doc="""You can either specify bins of equal size, bounded by
            upper and lower limits, or you can specify custom values that
            define the edges of each bin with a threshold. 
            
            <i>Note:</i> If you would like two bins, choose <i>Custom-defined bins</i> and then provide a single threshold when asked. 
            <i>Evenly spaced bins</i> creates the indicated number of bins
            at evenly spaced intervals between the low and high threshold.
            You also have the option to create bins for objects that fall below
            or above the low and high threhsold"""))

        group.append(
            "bin_count",
            cps.Integer(
                "Number of bins",
                3,
                minval=1,
                doc="""This is the number of bins that will be created between
            the low and high threshold"""))

        group.append(
            "low_threshold",
            cps.Float(
                "Lower threshold",
                0,
                doc=
                """<i>(Used only if Evenly spaced bins selected)</i><br>This is the threshold that separates the lowest bin from the
            others. The lower threshold, upper threshold, and number of bins
            define the thresholds of bins between the lowest and highest."""))

        group.append(
            "wants_low_bin",
            cps.Binary(
                "Use a bin for objects below the threshold?",
                False,
                doc="""Check this box if you want to create a bin for objects
            whose values fall below the low threshold. Leave the box unchecked
            if you do not want a bin for these objects."""))

        def min_upper_threshold():
            return group.low_threshold.value + np.finfo(float).eps

        group.append(
            "high_threshold",
            cps.Float(
                "Upper threshold",
                1,
                minval=cps.NumberConnector(min_upper_threshold),
                doc=
                """<i>(Used only if Evenly spaced bins selected)</i><br> This is the threshold that separates the last bin from
            the others.
            <i>Note:</i> If you would like two bins, choose <i>Custom-defined bins</i>."""
            ))

        group.append(
            "wants_high_bin",
            cps.Binary(
                "Use a bin for objects above the threshold?",
                False,
                doc="""Check this box if you want to create a bin for objects
            whose values are above the high threshold. Leave the box unchecked
            if you do not want a bin for these objects."""))

        group.append(
            "custom_thresholds",
            cps.Text(
                "Enter the custom thresholds separating the values between bins",
                "0,1",
                doc="""
            <i>(Used only if Custom thresholds selected)</i><br>
            This setting establishes the threshold values for the
            bins. You should enter one threshold between each bin, separating
            thresholds with commas (for example, <i>0.3, 1.5, 2.1</i> for four bins).
            The module will create one more bin than there are thresholds."""))

        group.append(
            "wants_custom_names",
            cps.Binary(
                "Give each bin a name?",
                False,
                doc="""This option lets you assign custom names to bins you have 
            specified. If you leave this unchecked, the module will
            assign names based on the measurements and the bin number."""))

        group.append(
            "bin_names",
            cps.Text("Enter the bin names separated by commas",
                     "None",
                     doc="""
            <i>(Used only if Give each bin a name? is checked)</i><br>
            Enter names for each of the bins, separated by commas.
            An example including three bins might be <i>First,Second,Third</i>."""
                     ))

        group.append(
            "wants_images",
            cps.Binary(
                "Retain an image of the objects classified by their measurements, for use later in the pipeline (for example, in SaveImages)?",
                False))

        group.append(
            "image_name",
            cps.ImageNameProvider("Name the output image", "ClassifiedNuclei"))

        group.can_delete = can_delete

        def number_of_bins():
            '''Return the # of bins in this classification'''
            if group.bin_choice == BC_EVEN:
                value = group.bin_count.value
            else:
                value = len(group.custom_thresholds.value.split(",")) - 1
            if group.wants_low_bin:
                value += 1
            if group.wants_high_bin:
                value += 1
            return value

        group.number_of_bins = number_of_bins

        def measurement_name():
            '''Get the measurement name to use inside the bin name
            
            Account for conflicts with previous measurements
            '''
            measurement_name = group.measurement.value
            other_same = 0
            for other in self.single_measurements:
                if id(other) == id(group):
                    break
                if other.measurement.value == measurement_name:
                    other_same += 1
            if other_same > 0:
                measurement_name += str(other_same)
            return measurement_name

        def bin_feature_names():
            '''Return the feature names for each bin'''
            if group.wants_custom_names:
                return [
                    name.strip() for name in group.bin_names.value.split(",")
                ]
            return [
                '_'.join((measurement_name(), 'Bin_%d' % (i + 1)))
                for i in range(number_of_bins())
            ]

        group.bin_feature_names = bin_feature_names

        def validate_group():
            bin_name_count = len(bin_feature_names())
            bin_count = number_of_bins()
            if bin_count < 1:
                bad_setting = (group.bin_count if group.bin_choice == BC_EVEN
                               else group.custom_thresholds)
                raise cps.ValidationError(
                    "You must have at least one bin in order to take measurements. "
                    "Either add more bins or ask for bins for objects above or below threshold",
                    bad_setting)
            if bin_name_count != number_of_bins():
                raise cps.ValidationError(
                    "The number of bin names (%d) does not match the number of bins (%d)."
                    % (bin_name_count, bin_count), group.bin_names)
            if group.bin_choice == BC_CUSTOM:
                try:
                    [
                        float(x.strip())
                        for x in group.custom_thresholds.value.split(",")
                    ]
                except ValueError:
                    raise cps.ValidationError(
                        'Custom thresholds must be a comma-separated list '
                        'of numbers (example: "1.0, 2.3, 4.5")',
                        group.custom_thresholds)

        group.validate_group = validate_group

        if can_delete:
            group.remove_settings_button = cps.RemoveSettingButton(
                "", "Remove the above classification",
                self.single_measurements, group)
        self.single_measurements.append(group)
Пример #27
0
    def add_flag(self, can_delete=True):
        group = cps.SettingsGroup()
        group.append("divider1", cps.Divider(line=False))
        group.append("measurement_settings", [])
        group.append("measurement_count",
                     cps.HiddenCount(group.measurement_settings))
        group.append(
            "category",
            cps.Text("Name the flag's category",
                     "Metadata",
                     doc='''
                                Name a measurement category in which the flag should reside. Metadata allows you to 
                                later group images in the <b>LoadImages</b> module based on the flag, if you load the 
                                flag data in a future pipeline via the <b>LoadData</b> module.  Otherwise, you might 
                                choose to have the flag stored in the "Image" category or using some other word you prefer.  
                                The flag is stored as a per-image measurement whose name is a combination of the
                                flag's category and feature name, underscore delimited. 
                                For instance, if the measurement category is
                                "Metadata" and the feature name is "QCFlag", then the default
                                measurement name would be "Metadata_QCFlag". %s'''
                     % USING_METADATA_HELP_REF))

        group.append(
            "feature_name",
            cps.Text("Name the flag",
                     "QCFlag",
                     doc='''
                                The flag is stored as a per-image measurement whose name is a combination of the
                                flag's category and feature name, underscore delimited. 
                                For instance, if the measurement category is
                                "Metadata" and the feature name is "QCFlag", then the default
                                measurement name would be "Metadata_QCFlag".'''
                     ))

        group.append(
            "combination_choice",
            cps.Choice(
                "Flag if any, or all, measurement(s) fails to meet the criteria?",
                [C_ANY, C_ALL],
                doc='''
                                <ul>
                                <li><i>Any:</i> An image will be flagged if any of its measurements fail. This can be useful
                                for flagging images possessing multiple QC flaws; for example, you can flag all bright images and all out of focus images with one flag.</li>
                                <li><i>All:</i> A flag will only be assigned if all measurements fail.  This can be useful for flagging  images that possess only a combination
                                of QC flaws; for example, you can flag only images that are both bright and out of focus.</li>
                                </ul>'''))

        group.append(
            "wants_skip",
            cps.Binary(
                "Skip image set if flagged?",
                False,
                doc="""You can skip the remainder of the pipeline for image sets
            that are flagged by checking this setting. If you check this
            setting, CellProfiler will not run subsequent modules in the
            pipeline on the images in any image set that is flagged. 
            CellProfiler will continue to process the pipeline if you leave
            the setting unchecked.<p>
            You may want to check this setting in order to filter out
            unwanted images during processing. For instance, you may want
            to exclude out of focus images when running 
            <b>CorrectIllumination_Calculate</b>. You can do this with a
            pipeline that measures image quality and flags inappropriate
            images before it runs <b>CorrectIllumination_Calculate</b>"""))

        group.append(
            "add_measurement_button",
            cps.DoSomething("", "Add another measurement",
                            self.add_measurement, group))
        self.add_measurement(group, False if not can_delete else True)
        if can_delete:
            group.append(
                "remover",
                cps.RemoveSettingButton("", "Remove this flag", self.flags,
                                        group))
        group.append("divider2", cps.Divider(line=True))
        self.flags.append(group)
Пример #28
0
    def create_settings(self):
        """Create the settings for the module
        
        Create the settings for the module during initialization.
        """
        self.contrast_choice = cps.Choice(
            "Should each classification decision be based on a single measurement or on the combination of a pair of measurements?",
            [BY_SINGLE_MEASUREMENT, BY_TWO_MEASUREMENTS],
            doc="""This setting controls how classifications are recorded:<br>
            <ul><li><i>Single measurements</i>: Classifies each object based on a single measurement.</li>
            <li><i>Pair of measurements</i>: Classifies each object based on a pair of measurements taken together (that is, an object must meet two criteria to belong to a class).</li></ul>"""
        )

        ############### Single measurement settings ##################
        #
        # A list holding groupings for each of the single measurements
        # to be done
        #
        self.single_measurements = []
        #
        # A count of # of measurements
        #
        self.single_measurement_count = cps.HiddenCount(
            self.single_measurements)
        #
        # Add one single measurement to start off
        #
        self.add_single_measurement(False)
        #
        # A button to press to get another measurement
        #
        self.add_measurement_button = cps.DoSomething(
            "", "Add another classification", self.add_single_measurement)
        #
        ############### Two-measurement settings #####################
        #
        # The object for the contrasting method
        #
        self.object_name = cps.ObjectNameSubscriber(
            "Enter the object name",
            "None",
            doc="""Select the object that you want to measure from the list.
            This should be an object created by a previous module such as
            <b>IdentifyPrimaryObjects</b>, <b>IdentifySecondaryObjects</b>, or
            <b>IdentifyTertiaryObjects</b>.""")

        #
        # The two measurements for the contrasting method
        #
        def object_fn():
            return self.object_name.value

        self.first_measurement = cps.Measurement(
            "Select the first measurement",
            object_fn,
            doc="""Select a measurement made on the above object. This is
            the first of two measurements that will be contrasted together.
            The measurement should be one made on the object in a prior
            module.""")

        self.first_threshold_method = cps.Choice(
            "Method to select the cutoff", [TM_MEAN, TM_MEDIAN, TM_CUSTOM],
            doc="""Objects are classified as being above or below a cutoff
            value for a measurement. You can set this cutoff threshold in one
            of three ways:<br>
            <ul><li><i>Mean</i>: At the mean
            of the measurement's value for all objects in the image cycle.</li>
            <li><i>Median</i>: At the median of the
            measurement's value for all objects in the image set.</li>
            <li><i>Custom</i>: You specify a custom threshold value.</li></ul>"""
        )

        self.first_threshold = cps.Float(
            "Enter the cutoff value",
            .5,
            doc="""This is the cutoff value separating objects in the two 
            classes.""")

        self.second_measurement = cps.Measurement(
            "Select the second measurement",
            object_fn,
            doc="""Select a measurement made on the above object. This is
            the second of two measurements that will be contrasted together.
            The measurement should be one made on the object in a prior
            module.""")

        self.second_threshold_method = cps.Choice(
            "Method to select the cutoff", [TM_MEAN, TM_MEDIAN, TM_CUSTOM],
            doc="""Objects are classified as being above or below a cutoff
            value for a measurement. You can set this cutoff threshold in one
            of three ways:<br>
            <ul><li><i>Mean</i>: At the mean
            of the measurement's value for all objects in the image cycle.</li>
            <li><i>Median</i>: At the median of the
            measurement's value for all objects in the image set.</li>
            <li><i>Custom</i>: You specify a custom threshold value.</li></ul>"""
        )

        self.second_threshold = cps.Float(
            "Enter the cutoff value",
            .5,
            doc="""This is the cutoff value separating objects in the two 
            classes.""")

        self.wants_custom_names = cps.Binary(
            "Use custom names for the bins?",
            False,
            doc="""Check this if you want to specify the names of each bin 
            measurement. If you leave the box unchecked, the module will
            create names based on the measurements. (For instance, for
            "Intensity_MeanIntensity_Green" and "Intensity_TotalIntensity_Blue",
            the module generates measurements such as
            "Classify_Intensity_MeanIntensity_Green_High_Intensity_TotalIntensity_Low")."""
        )

        self.low_low_custom_name = cps.Text("Enter the low-low bin name",
                                            "low_low",
                                            doc="""
            <i>(Used only if using a pair of measurements)</i><br>
            Name of the measurement for objects that
            fall below the threshold for both measurements.""")

        self.low_high_custom_name = cps.Text("Enter the low-high bin name",
                                             "low_high",
                                             doc="""
            <i>(Used only if using a pair of measurements)</i><br>
            Name of the measurement for objects whose
            first measurement is below threshold and whose second measurement
            is above threshold.""")

        self.high_low_custom_name = cps.Text("Enter the high-low bin name",
                                             "high_low",
                                             doc="""
            <i>(Used only if using a pair of measurements)</i><br>
            Name of the measurement for objects whose
            first measurement is above threshold and whose second measurement
            is below threshold.""")

        self.high_high_custom_name = cps.Text("Enter the high-high bin name",
                                              "high_high",
                                              doc="""
            <i>(Used only if using a pair of measurements)</i><br>
            Name of the measurement for objects that
            are above the threshold for both measurements.""")

        self.wants_image = cps.Binary(
            "Retain an image of the objects classified by their measurements, for use later in the pipeline (for example, in SaveImages)?",
            False)

        self.image_name = cps.ImageNameProvider(
            "Enter the image name",
            "None",
            doc="""Name that will be associated with the graph
            image. You can specify this name in a <b>SaveImages</b> module
            if you want to save the image.""")
Пример #29
0
    def create_settings(self):
        '''Create the initial settings and name the module'''
        self.target_name = cps.ObjectNameProvider('Name the output objects',
                                                  'FilteredBlue',
                                                  doc="""
                                What do you want to call the filtered objects? This will be the name for 
                                the collection of objects that are retained after applying the filter(s)."""
                                                  )

        self.object_name = cps.ObjectNameSubscriber(
            'Select the object to filter',
            'None',
            doc="""
                                What object would you like to filter? This setting 
                                also controls which measurement choices appear for filtering:
                                you can only filter based on measurements made on the object you select.
                                If you intend to use a measurement 
                                calculated by the <b>CalculateMath</b> module to to filter objects, select
                                the first operand's object here, because <b>CalculateMath</b> measurements
                                are stored with the first operand's object.""")

        self.spacer_1 = cps.Divider(line=False)

        self.mode = cps.Choice(
            'Select the filtering mode',
            [MODE_MEASUREMENTS, MODE_RULES, MODE_BORDER],
            doc="""You can choose from the following options:
            <ul>
            <li><i>%(MODE_MEASUREMENTS)s</i>: Specify a per-object measurement made by an upstream 
            module in the pipeline.</li>
            <li><i>%(MODE_RULES)s</i>: Use a file containing rules generated by CellProfiler Analyst.
            You will need to ensure that the measurements specified by the rules file are 
            produced by upstream modules in the pipeline.</li>
            <li><i>%(MODE_BORDER)s</i>: Remove objects touching the border of the image and/or the 
            edges of an image mask.</li>
            </ul>""" % globals())
        self.spacer_2 = cps.Divider(line=False)

        self.measurements = []
        self.measurement_count = cps.HiddenCount(self.measurements,
                                                 "Measurement count")
        self.add_measurement(False)
        self.add_measurement_button = cps.DoSomething(
            "Add another measurement", "Add", self.add_measurement)
        self.filter_choice = cps.Choice("Select the filtering method",
                                        FI_ALL,
                                        FI_LIMITS,
                                        doc="""
                                <i>(Used only if filtering using measurements)</i><br>
                                There are five different ways to filter objects:
                                <ul>
                                <li><i>Limits:</i> Keep an object if its measurement value falls within a range you specify.</li> 
                                <li><i>Maximal:</i> Keep the object with the maximum value for the measurement
                                of interest. If multiple objects share a maximal value, retain one object 
                                selected arbitrarily per image.</li>
                                <li><i>Minimal:</i> Keep the object with the minimum value for the measurement
                                of interest. If multiple objects share a minimal value, retain one object 
                                selected arbitrarily per image.</li>
                                <li><i>Maximal per object:</i> This option requires you to choose a parent object.
                                The parent object might contain several child objects of
                                choice (for instance, mitotic spindles within a cell or FISH
                                probe spots within a nucleus). Only the child object whose measurements equal the maximum child-measurement
                                value among that set of child objects will be kept 
                                (for example, the longest spindle
                                in each cell).  You do not have to explicitly relate objects before using this module.</li>
                                <li><i>Minimal per object:</i> Same as <i>Maximal per object</i>, except filtering is based on the minimum value.</li>
                                </ul>""")

        self.enclosing_object_name = cps.ObjectNameSubscriber(
            'Select the objects that contain the filtered objects',
            'None',
            doc="""
                                <i>(Used only if a per-object filtering method is selected)</i><br>
                                This setting selects the container (i.e., parent) objects for the <i>Maximal per object</i> 
                                and <i>Minimal per object</i> filtering choices."""
        )

        self.rules_directory = cps.DirectoryPath(
            "Rules file location",
            doc="""<i>(Used only when filtering by rules)</i>
            <br>
            Select the location of the rules file that will be used for filtering.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals())

        def get_rules_class_choices(pipeline):
            try:
                rules = self.get_rules()
                nclasses = len(rules.rules[0].weights[0])
                return [str(i) for i in range(1, nclasses + 1)]
            except:
                return [str(i) for i in range(1, 3)]

        self.rules_class = cps.Choice(
            "Class number",
            choices=["1", "2"],
            choices_fn=get_rules_class_choices,
            doc="""<i>(Used only when filtering by rules)</i>
            <br>
            Select which of the classes to keep when filtering. The
            CellProfiler Analyst classifier user interface lists the names of 
            the classes in order. By default, these are the positive (class 1)
            and negative (class 2) classes. <b>FilterObjects</b> uses the
            first class from CellProfiler Analyst if you choose "1", etc.""")

        def get_directory_fn():
            '''Get the directory for the rules file name'''
            return self.rules_directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = self.rules_directory.get_parts_from_path(
                path)
            self.rules_directory.join_parts(dir_choice, custom_path)

        self.rules_file_name = cps.FilenameText(
            "Rules file name",
            "rules.txt",
            get_directory_fn=get_directory_fn,
            set_directory_fn=set_directory_fn,
            doc="""<i>(Used only when filtering using rules)</i>
            <br>The name of the file holding the rules. Each line of
            this file should be a rule naming a measurement to be made
            on the object you selected, for instance:<pre>IF (Nuclei_AreaShape_Area &lt; 351.3, [0.79, -0.79], [-0.94, 0.94])</pre><br><br>
            The above rule will score +0.79 for the positive category and -0.94
            for the negative category for nuclei whose area is less than 351.3 
            pixels and will score the opposite for nuclei whose area is larger.
            The filter adds positive and negative and keeps only objects whose
            positive score is higher than the negative score.
            <p>Note that if the rules are obtained from CellProfiler Analyst, the objects
            that are removed are those represented by the second number between the brackets.</p>"""
        )

        self.wants_outlines = cps.Binary(
            'Retain outlines of the identified objects?', False)

        self.outlines_name = cps.OutlineNameProvider('Name the outline image',
                                                     'FilteredObjects',
                                                     doc='''
                                 <i>(Used only if the outline image is to be retained for later use in the  
                                 pipeline)</i> <br> Choose a name by which the outline image can be 
                                 selected later in the pipeline.
                                 <p><i>Special note on saving images:</i> You can use the settings in this module
                                 to pass object outlines along to the module <b>OverlayOutlines</b>, and then save
                                 them with the <b>SaveImages</b> module. Also, the identified objects themselves
                                 can be passed along to the object processing module <b>ConvertToImage</b>
                                 and then saved with the <b>SaveImages</b> module.'''
                                                     )
        self.additional_objects = []
        self.additional_object_count = cps.HiddenCount(
            self.additional_objects, "Additional object count")
        self.spacer_3 = cps.Divider(line=False)

        self.additional_object_button = cps.DoSomething(
            'Relabel additional objects to match the filtered object?',
            'Add an additional object',
            self.add_additional_object,
            doc="""
                                Click this button to add an object to receive the same post-filtering labels as
                                the filtered object. This is useful in making sure that labeling is maintained 
                                between related objects (e.g., primary and secondary objects) after filtering."""
        )
Пример #30
0
 def create_settings(self):
     self.filter_choice = cps.Choice("Filter choice", [S_GAUSSIAN, S_SOBEL])
     self.input_image_name = cps.ImageNameSubscriber("Input image")
     self.output_image_name = cps.ImageNameProvider("Output image",
                                                    "Filtered")