Welcome to redpatch’s documentation!

Indices and tables

redpatch

A module for segmenting diseased leaf images to find healthy regions, lesion associated regions and lesion centres.

Workflow Overview

  1. Set scale sliders to find HSV values that segment whole leaves from background
  2. Segment image into leaf sub-images
  3. Set scale sliders to find HSV values that segment healthy regions within leaf sub-images
  4. Segment the healthy region
  5. Set scale sliders to find HSV values that segment lesion regions within leaf sub-images
  6. Segment the lesion regions
  7. Set scale sliders that segment lesion centres within lesion regions
  8. Segment lesion centres
  9. Quantify found objects

Basic Usage

  1. Import module

    import redpatch as rp
    
  2. Create an IPython file browser to select images

    f = rp.FileBrowser()
    f.widget()
    
  3. Load an image into HSV colour space

    hsv_image = rp.load_as_hsv( f.path )
    
  4. Create an image slider

    rp.run_threshold_preview(hsv_image, width = 2)
    
  5. Find objects using HSV values

    # find raw objects
    lesion_region_mask, lesion_region_volume = rp.griffin_lesion_regions(cleared_image, h =(0.0, 0.82),
                                                                                    s = (0.2, 1.0),
                                                                                    v = (0.4, 1.0))
    # label regions
    labelled_lesion_regions, lesion_region_count = rp.label_image(lesion_region_mask)
    
    # visual preview of regions
    rp.preview_object_labels(labelled_lesion_regions, color.hsv2rgb(cleared_image))
    
    #filter regions
    lesion_regions_properties_list = rp.get_object_properties(labelled_lesion_regions)
    lesion_regions_to_keep = rp.filter_region_property_list(lesion_regions_properties_list, rp.is_not_small
    
  6. Examine objects as scikit-image measure RegionProps objects

    first_lesion_region = lesion_regions_to_keep[0]
    first_lesion_region.area
    
redpatch.HEALTHY_BLUE = (0, 255)

Default values for griffin named functions

redpatch.HEALTHY_GREEN = (120, 175)

Default values for griffin named functions

redpatch.HEALTHY_HUE = (0.1568627450980392, 1.0)

Default values for griffin named functions

redpatch.HEALTHY_RED = (4, 155)

Default values for griffin named functions

redpatch.HEALTHY_SAT = (0.19607843137254902, 1.0)

Default values for griffin named functions

redpatch.HEALTHY_VAL = (0.0, 1.0)

Default values for griffin named functions

redpatch.LEAF_AREA_HUE = (0.0, 1.0)

Default values for griffin named functions

redpatch.LEAF_AREA_SAT = (0.19607843137254902, 1.0)

Default values for griffin named functions

redpatch.LEAF_AREA_VAL = (0.1568627450980392, 1.0)

Default values for griffin named functions

redpatch.LESION_HUE = (0.0, 0.1607843137254902)

Default values for griffin named functions

redpatch.LESION_SAT = (0.14901960784313725, 1.0)

Default values for griffin named functions

redpatch.LESION_VAL = (0.43529411764705883, 1.0)

Default values for griffin named functions

redpatch.SCALE_CARD_HUE = (0.61, 1.0)

Default values for griffin named functions

redpatch.SCALE_CARD_SAT = (0.17, 1.0)

Default values for griffin named functions

redpatch.SCALE_CARD_VAL = (0.25, 0.75)

Default values for griffin named functions

redpatch.clean_labelled_mask(label_array: numpy.ndarray, region_props: List[skimage.measure._regionprops.RegionProperties]) → numpy.ndarray

Removes unwanted object pixels from a mask.

Given a label array, sets the labels not represented in region_props to Zero removing them from the image. Intended to be used on label images

Param:label_array np.ndarray – the label array from which non-represented objects will be removed
Param:region_props List – list of skimage.measure.RegionProps, the objects to keep in the label array
Returns:np.ndarray – cleaned label array
redpatch.clear_background(img: numpy.ndarray, mask: numpy.ndarray) → numpy.ndarray

given an image and a binary mask, clears all pixels in the image (ie sets to zero) the zero/false pixels in the mask

redpatch.extract_image_segment(hsv_img: numpy.ndarray, region_prop: skimage.measure._regionprops.RegionProperties) → numpy.ndarray

Return a rectangular segment of an image covering a region object.

Given 3D hsv_img returns a slice covered by the bounding box of region_prop

Param:hsv_img np.ndarray – an hsv scaled image
Param:region_prop – a RegionProps object describing the extent of the subimage
Returns:np.ndarray
redpatch.filter_region_property_list(region_props: List[skimage.measure._regionprops.RegionProperties], func: Callable[[skimage.measure._regionprops.RegionProperties], bool]) → List[skimage.measure._regionprops.RegionProperties]

Filters region props objects from a list if they do not satisfy a condition.

Given a list of region props, and a function that returns True/False for each region prop Returns a list of region props that have passed

Param:region_props List – list of skimage.measure.RegionProps objects
Param:func Callable – a function that returns True/False to be evaluated against the RegionProps objects
Returns:List of RegionProps
redpatch.get_object_properties(label_array: numpy.ndarray, intensity_image: numpy.ndarray = None) → List[skimage.measure._regionprops.RegionProperties]

Compute object properties. EG. area.

Given a label array returns a list of computed RegionProperties objects.

Param:label_array np.ndarray – the label array to compute properties from
Param:intensity_image np.ndarray – the image on which properties are computed
Returns:list of skimage.measure.regionprops objects
redpatch.griffin_healthy_regions(hsv_img: numpy.ndarray, h: Tuple[float, float] = (0.1568627450980392, 1.0), s: Tuple[float, float] = (0.19607843137254902, 1.0), v: Tuple[float, float] = (0.0, 1.0)) → Tuple[numpy.ndarray, int]

Perform Ciaran Griffin’s Healthy Region extraction.

Given an image in hsv applies Ciaran Griffin’s detection for healthy regions. returns the mask of pixels and the pixel volume.

Param:hsv_img np.ndarray – an HSV scaled image
Param:h Tuple – minimum and maximum Hue threshold values
Param:s Tuple – minimum and maximum Saturation threshold values
Param:v Tuple – minimum and maximum Value threshold values
Returns:np.ndarray, int
redpatch.griffin_leaf_regions(hsv_img, h: Tuple[float, float] = (0.0, 1.0), s: Tuple[float, float] = (0.19607843137254902, 1.0), v: Tuple[float, float] = (0.1568627450980392, 1.0)) → Tuple[numpy.ndarray, int]

given an image in hsv applies Ciaran Griffin’s detection for leaf area regions. applies a hsv_space colour threshold and fills that mask for holes. returns a binary mask and object count.

redpatch.griffin_lesion_centres(hsv_img, lesion_region: skimage.measure._regionprops.RegionProperties, sigma: float = 2.0)

finds lesion centres in a given lesion region

redpatch.griffin_lesion_regions(hsv_img, h: Tuple[float, float] = (0.0, 0.1607843137254902), s: Tuple[float, float] = (0.14901960784313725, 1.0), v: Tuple[float, float] = (0.43529411764705883, 1.0)) → Tuple[numpy.ndarray, int]

given an image in hsv applies Ciaran Griffin’s detection for lesion regions. applies a hsv_space colour threshold, returns a labelled mask of objects and the object count.

redpatch.griffin_scale_card(hsv_img, h, s, v, side_length=5)

returns pixels per cm of scale card object

redpatch.hsv_to_rgb255(img: numpy.ndarray) → numpy.ndarray

Convert HSV image to RGB image.

Given an HSV image in (0.0,1.0) range, converts to RGB image in (0,255). Usually needed prior to viewing as most viewers interpret images as RGB.

Param:img np.ndarray – a numpy ndarray
Returns:np.ndarray – a numpy ndarray with shape == img
redpatch.is_long_and_large(obj: skimage.measure._regionprops.RegionProperties, major_to_minor: int = 2, min_area: int = 90000) → Optional[bool]

” Work out whether an object is long and large.

Given a region props object works ; returns True if the object represented has a major to minor axis ratio of > major_to_minor and takes up pixels of min_area, False otherwise and None if not calculable

Param:obj skimage.measure._regionprops._RegionProperties – a region properties object
Param:major_to_minor int – the ratio of the long to short side that defines whether the object is long
Param:min_area int – the total area that defines whether the object is large.
Returns:None or bool
redpatch.is_not_small(obj: skimage.measure._regionprops.RegionProperties, min_area: int = 2500) → Optional[bool]

” Work out whether an object is not small.

Given a region props object this function returns True if its area is greater than min_area. False if not and None if the value is not calculable

Param:obj skimage.measure._regionprops._RegionProperties – a region properties object
Param:min_area int – minimum area threshold
Returns:None or bool
redpatch.label_image(m: numpy.ndarray, structure=None, output=None) → Tuple[numpy.ndarray, int]

Creates labels for the objects in an image.

Given a binary mask array, returns a version with the distinct islands labelled by integers, and a count of objects found. Thin wrapper around ndi.label

Param:m np.ndarray – binary mask image/array
Param:structure np.ndarray – custom structuring object if needed (default None)
Returns:a labelled image mask
redpatch.load_as_hsv(fname: str) → numpy.ndarray

Load a file into HSV colour space.

Takes a file path and opens the image then converts to HSV colour space. returns numpy array dtype float 64. Strips the alpha (fourth) channel if it exists. Input must be colour image. One channel images will be rejected.

Param:fname str – path to the image
Returns:np.ndarray – numpy array containing image
redpatch.pixel_volume_to_circular_area(pixels: int, scale: float) → float

helps work out the area of a circular object with a similar pixel volume at the same scale pixels = pixels in the object , scale = pixels per cm in this image, obtainable from rp.griffin_scale_card()

returns a float giving the area a circle of that number of pixels would take up

redpatch.preview_hsv(img: numpy.ndarray, width: int = 5, height: int = 5) → None

Draw an HSV image to screen.

Given an HSV image, generates a preview image and draws to screen. Intended for use in IPython and interactive sessions as the plot renders immediately.

Param:img np.ndarray – the image to draw
Param:width int – width in inches of the plot
Param:height int – height in inches of the plot
Returns:None
redpatch.preview_mask(m: numpy.ndarray, width: int = 5, height: int = 5) → None

Draw a mask to screen.

Given a binary bool mask array draws a plot in two colours black = 1/True, white = 0/False. Intended for use in IPython and interactive sessions as the plot renders immediately

Param:m np.ndarray – the mask to draw.
Param:width int – width in inches of the plot
Param:height int – height in inches of the plot
Returns:None
redpatch.preview_object_labels(label_array: numpy.ndarray, binary_image: numpy.ndarray, width: int = 5, height: int = 5) → None

Draw a preview image of objects in a mask, colouring by labels.

Given a labelled object array from rp.label_image and a background binary image, returns a plot with the objects described in the labelled array coloured in. Intended for use in IPython and interactive sessions as the plot renders immediately.

Param:label_array np.ndarray – labelled object array/image
Returns:None
redpatch.run_threshold_preview(image: numpy.ndarray, height: int = 15, width: int = 15, slider_width: int = 500, perfect: bool = False, scale: float = 0.25) → None

Given an HSV image, generates some sliders and an overlay image. Shows the image colouring the pixels that are included in the sliders thresholds in red. Note this does not return an image or mask of those pixels, its just a tool for finding the thresholds

If perfect = False (default) the image is downsized by a factor in scale (default = 0.25) before running the thresholding.

redpatch.threshold_hsv_img(im: numpy.ndarray, h: Tuple[float, float] = (0.1568627450980392, 1.0), s: Tuple[float, float] = (0.19607843137254902, 1.0), v: Tuple[float, float] = (0.0, 1.0)) → numpy.ndarray

Selects pixels passing an HSV image threshold in all three channels.

Returns a logical binary mask array (dtype bool of dimension im ( an HSV image) in which pixels in im pass the lower and upper thresholds specified in h, s and v (hue lower,upper; sat lower,upper and val lower, upper; respectively)

Param:im np.ndarray – a numpy ndarray
Param:h Tuple – a 2-tuple of Hue thresholds (lower, upper)
Param:s Tuple – a 2-tuple of Saturation thresholds (lower, upper)
Param:v Tuple – a 2-tuple of Value thresholds (lower, upper)
Returns:np.ndarray – a logical array (dtype bool) with shape == im

filtersettings

A module for creating filter settings for redpatch experiments

Workflow Overview

  1. Create empty object
  2. Add threshold settings for selecting different parts of the image
  3. Write settings to file for re-use

Basic Usage

  1. Import module, create empty object

    import redpatch as rp
    fs = rp.FilterSettings()
    
  2. Add some settings

    fs.add_setting("leaf_area", h=(0.1, 1.0), s=(0.3, 0.6), v=(0.4, 0.6) )
    
  3. Access a setting by name

    fs.settings["leaf_area"]["h"]
    
  1. Write settings to a file

    fs.write("my_settings.yaml")
    
  2. Read in settings from a file

    fs = rp.FilterSettings()
    settings = fs.read("/some/file/settings.yaml")
    
  3. Create a default filter settings file

    fs = rp.FilterSettings()
    fs.create_default_filter_file("/some/folder/settings.yaml")
    
class filtersettings.FilterSettings

class representing groups of filter settings for different aspects of the image

add_setting(tag: str, h: Tuple[float, float] = (), s: Tuple[float, float] = (), v: Tuple[float, float] = ()) → None

add a setting to the object

Param:tag str – the name of the setting
Param:h Tuple – a 2-tuple of Hue thresholds (lower, upper)
Param:s Tuple – a 2-tuple of Saturation thresholds (lower, upper)
Param:v Tuple – a 2-tuple of Value thresholds (lower, upper)
Returns:None
create_default_filter_file(file: str = 'default_filter.yml') → None

write a file containing the default filter settings :param file str – name of the file to write: :return: None

read(infile: str) → None
Param:infile str – name of the file to read
Returns:None
write(outfile: str) → None

write the settings to a yaml file

Param:file str – name of the file to write
Returns:None

FileBrowser

A module for creating interactive file browser widgets in a Jupyter notebook

Workflow Overview

  1. Create object
  2. Browse file interactively
  3. Extract path of selected file

Basic Usage

  1. Import module and create widget

    import redpatch as rp
    f = rp.FileBrowser()
    f.widget()
    
  2. Browse

    … interactively

  3. Extract path of selected file

    f.path
    

report

A module for creating redpatch run reports; used by ‘redpatch-batch-process’

Workflow Overview

  1. Create object, specify run folder, image objects and filter settings
  2. Add calculated annotated sub images for images
  3. write to html

Basic Usage

  1. Import module and create object

    import redpatch as rp
    fs = rp.FilterSettings()
    fs.read("settings.yml")
    source_folder = "some/folder"
    image_files = ["img1.jpg", "img2.jpg]
    report = rp.RPReport(source_folder, image_files, fs)
    
  2. Add subimages and annotations

    report.add_subimages(image_file, sub_image_tag)
    report.add_annotated_subimages(image_file, sub_image_tag)
    
  3. Write report and images to results folder

    report.write("some/folder")
    
class report.RPReport(source_directory, images, filter_settings)

Class representing an HTML report page. Used by batch-process

class lesioncentre.LesionCentre(rprop: skimage.measure._regionprops.RegionProperties = None, parent_rprop: skimage.measure._regionprops.RegionProperties = None, scale: float = None, pixel_length=None, max_ratio: float = None, minimum_size: float = None, prop_across_parent: float = None)

Represents a lesion centre.

Modifies a scikit RegionProp and requires information from a parent RegionProp

Param:rprop skimage.measure._regionprops._RegionProperties – region to make a lesion centre
Param:parent_rprop skimage.measure._regionprops._RegionProperties – parent (enclosing) region of rprop
Param:scale float – measure of the scale of the image, either None (scale in image pixels) or real units from scale card
Param:pixel_length – length of side of one pixel, available when scale
Param:max_ratio float – threshold of region length / width to pass filter
Param:minimum_size float – minimum size to pass filter. calculated in units of scale
Param:prop_across_parent float – proportion of width of enclosing object the lesion centre must be to pass filter. EG 0.1 indicates that the lesion centre must be greater than 10 percent of the current width across the parent object
class subimage.SubImage(sub_i, sub_i_idx, parent_image_file, file_settings=None, dest_folder=None, min_lesion_area=None, scale=None, pixel_length=None, max_lc_ratio=None, min_lc_size=None, lc_prop_across_parent=None)

class representing sub-image (leaf containing area) of a larger image.

Variables:
  • sub_i – the subimage
  • sub_i_idx – the index of the subimage from the subimage list
  • scale – the scale of the image if computed
  • pixel_length – the length of a pixel side in real units
  • imtag – the name of the file this subimage is referred to in the output
  • annot_imtag – the name of the annotated image file this subimage is referred to in the output
  • parent_image_file – the name of the file this subimage is derived from
  • healthy_obj_props – list of HealthyAreas found in the subimage
  • leaf_area_props – list of LeafAreas found in the subimage
  • lesion_area_props – list of LesionAreas found in the subimage
  • lesion_centre_props – list of LesionCentres found in the subimage
create_results_dataframe(on_webserver=False)

generates a pandas dataframe of results from the SubImage object :return: pandas.dataframe

write_annotated_sub_image()

create output annotated subimage jpeg with results overlay :return: None

write_sub_image()

write out subimage (nonannotated) :return: None

subimage.get_sub_images(imfile, file_settings=None, dest_folder=None, min_lesion_area=None, scale=None, pixel_length=None, max_lc_ratio=None, min_lc_size=None, lc_prop_across_parent=None)

extracts different leaves from a single image file, returning them as individual SubImage objects.

Param:imfile str – path to the image
Param:file_settings str – FilterSettings object with image segmentation options
Param:dest_folder str – folder in which to place results files
Param:min_lesion_area float – minimum area for a lesion to pass filter. In either pixels or actual size if ‘scale’ passed
Param:scale float – pixels per real unit length, if known or computed earlier.
Param:max_lc_ratio float – maximum length/width ratio of lesion centre to pass filter
Param:min_lc_size float – minimum lesion centre size. Computed in real units if ‘scale’ passed. Computed as area of circle with same pixel volume as the centre.
Param:lc_prop_across_parent float – minimum proportion lesion centre must be across the width of the parent lesion (in the row the centre centroid occurs) to pass filter
class imagearea.HealthyArea(rprop, scale, pixel_length)
class imagearea.ImageArea(rprop, scale, pixel_length)

Base class for image areas that are created by rp.get_subimages() Copies user attributes from skimage.measure.regionprops and adds a few attributes

Variables:
  • size – computed size of area if scale is provided in cm2
  • passed – computed filter pass/fail. Can be NA if area does not have filter criteria
  • parent_lesion_region – ID of parent (enclosing region) where exists
  • prop_across_parent – computed distance across parent region width a lesion centre falls. Is NA for other regions
  • subimage_centre – centre pixels of image area
Scale:

scale of the image

Param:

pixel_length – length of side of one pixel, available when scale

class imagearea.LeafArea(rprop, scale, pixel_length)
class imagearea.LesionArea(rprop, scale, pixel_length, min_lesion_area=None)