Package bar :: Module base :: Class barPretracedSlideRenderer
[hide private]
[frames] | no frames]

Class barPretracedSlideRenderer


Class which converts contour slides into CAF slides.


To Do: Perhaps replacing all PIL procedures with NumPy rutines will give some speedup?

Nested Classes [hide private]
Instance Methods [hide private]
barTracedSlideRenderer
trace(self, colorMapping)
Perform tracing of the slide according to self._tracingConf.

Inherited from barPretracedSlide: __delitem__, __getitem__, __init__, __setitem__, affineTransform, getXMLelement, modifyContours, parseMarkers, values

Inherited from barSlideRenderer: renderSlide

Inherited from barVectorSlide: Show, addLabel, alignToRefMatrix, deleteLabelByCaption, deleteLabelByID, getCommentLabels, getLabelByName, getRegularLabels, getSpotLabels, renameLabelByCaption, retypeLabelByCaption, srs2svg, svg2srs, updateMetadata

Inherited from barObject: __str__, getElementById, writeXMLtoFile

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __subclasshook__

    Subprocedures - in order of execution
 
__loadImage(self)
Render provided contour slide with given resolution and put rendered image as a first element of self.__imageCache.
int
__setContourColor(self, pixelColorValue)
Apply treshold function for given pixel value.
 
__createCache(self)
Create image cache (self.__imageCache).
[barPath, ...]
__processVbrain(self)
Create outline of the whole brain.
[barRegularLabel, ...]
__getMissplacedLabels(self)
Dectect labels that cannot be traced as they are missplaced: placed over the contours or outside the brain area.
[barPath, ...]
__processLabels(self)
Create list of paths basing on the list of labels to be traced (self.__labelsLeft).
([barPath, ...], [barRegularLabel, ...])
__getUnlabeled(self)
Create list of paths and corresponding labels by tracing areas that were not labeled in pretraced files (unlabeled areas).
 
__clearAfterTracing(self)
Clear all temporary class attributes created for tracing purposes.
    Main functions - they do most of the work
[barPath, ...]
__processSingleLabel(self, seedLabel)
Extract a path defined by coordinates of the given seed label.
[barPath, ...]
__bitmapToPaths(self, sourceImage, seedLabel, invert=False)
Perform all operation releted with tracing bitmap into list of paths:
barPath
_getPath(self, pathElem, seedLabel)
Create barPath from provided SVG path element (result of tracing) and seed label.
str
_getNewPathID(self, seedLabel)
Generate proper path identifier of the path related to the seed label.
 
__substractFromBrainOutline(self, imageToSubstract, source='Struct')
Mark traced areas on __brainOutline.
(PIL.Image.Image, int) or PIL.Image.Image
__applyFill(self, sourceImage, seedLabel, retNPIX=False)
Apply flood fill to given image using coordinates passed in the seed label.
bool
__isAllowedForFilling(self, im, seedLabel)
Determine if bitmap with given seed label is suitable for tracing.
(int, int)
__getUnlabeledAreas(self)
Find white pixels in the image.
    Auxiliary functions
bool
__isOutsideBrainOutline(self, seedLabel)
Determine if label is placed outside brain outline according to values of self.__brainOutline.
bool
__isOverContour(self, im, seedLabel)
Determine if label is not placed over boundary.
 
_saveBitmap(self, im, filename)
Save provided image.
 
_saveSVG(self, svgdom, filename)
Save provided SVG.
([PIL.Image.Image, ...], [int, ...])
__getCoveredAreasList(self, seedLabel)
For images from self.__imageCache perform floodfilling with seed label.
 
__dumpWrongSeed(self, im, seedLabel)
Output warning message to stderr and dump invalid image into a file.
Class Methods [hide private]

Inherited from barPretracedSlide: fromXML

Static Methods [hide private]

Inherited from barObject (private): _getAttributesDict

Instance Variables [hide private]
PIL.Image.Image __brainOutline
whole brain outline; image is generated in moment of provedding vBrain labels; during tracing consecutive areas are substracted from brain outline; remaining white areas are considered as ublabelled areas
[PIL.Image.Image, ...] __imageCache
images representing slide; consecutive elements have thicker contours due to gap filling algorithm
{str : barStructureLabel, ...} __labelCache
temporary cache holding labels from contour slide; removed after tracing
[barStructureLabel, ...] __labelsLeft
labels undergoing tracing procedure; removed after tracing
[barStructureLabel, ...] __vBrainLabels
subset of __labelCache holding 'vBrain' labels processed in different way than other labels
{str : ?, ...} _tracingConf
tracing configuration (see module description for details)

Inherited from barVectorSlide: slideNumber, slideTemplate

Inherited from barVectorSlide (private): _labels, _metadata

Properties [hide private]

Inherited from barPretracedSlide: svgDocument

Inherited from barSlideRenderer: bitmapSize, size

Inherited from barVectorSlide: labelIndex, labels, metadata

Inherited from object: __class__

Method Details [hide private]

trace(self, colorMapping)

 

Perform tracing of the slide according to self._tracingConf.

Parameters:
  • colorMapping ({str : str, ...}) - structure name to hexadecimal color mapping defining unique colour for each structure
Returns: barTracedSlideRenderer
traced slide created by tracing the contour slide

__loadImage(self)

 

Render provided contour slide with given resolution and put rendered image as a first element of self.__imageCache.

It is assumed that self.__imageCache == [].

__setContourColor(self, pixelColorValue)

 

Apply treshold function for given pixel value. All pixels which are non-white pixels becomes self._tracingConf['GrowDefaultBoundaryColor'] pixels. This procedure assures that output image has only two colours (white and boundary) which is very convinient in further processing.

Parameters:
  • pixelColorValue (int) - value of given pixel
Returns: int
255 if white pixel is given, self._tracingConf['GrowDefaultBoundaryColor'] otherwise

__createCache(self)

 

Create image cache (self.__imageCache). First cached image is an original image. All other images (up to cacheLevel) are images with succesive grows (applications of MinFilter).

__processVbrain(self)

 

Create outline of the whole brain. The outline serves further as a reference for detecting missplaced labels and obviously as structure representing whole brain.

Outline is created by substracting result of flooding each vBrain label and then inversing the result and tracing resulting bitmap.

Returns: [barPath, ...]
paths representing outline of the whole brain

__getMissplacedLabels(self)

 

Dectect labels that cannot be traced as they are missplaced: placed over the contours or outside the brain area.

Returns: [barRegularLabel, ...]
labels that has to be excluded from tracing

__processLabels(self)

 

Create list of paths basing on the list of labels to be traced (self.__labelsLeft).

Returns: [barPath, ...]
paths created by tracing individual labels

__getUnlabeled(self)

 

Create list of paths and corresponding labels by tracing areas that were not labeled in pretraced files (unlabeled areas). This process is rather complicated so few words of explanation:

  1. We look for patches of N or more pixels. Only such areas are considered as unlabelled areas. Smaller areas are most probably residual white pixels and should be ommited.
  2. Every group of two or more adjacent white pixels is flooded on "1".
  3. Patch of N or more white pixels is flooded with value "2" after tracing.

After fiding unlabelled areas we can find 4 values of pixels:

  1. "0": areas outside brain
  2. "1": pixels of more than one adjacent pixels but less than N
  3. "2": patches of N or more white pixels
Returns: ([barPath, ...], [barRegularLabel, ...])
pair of lists of paths and corresponding labels generated during detections of unlabelled areas.

__clearAfterTracing(self)

 

Clear all temporary class attributes created for tracing purposes. Invoked by self.trace method as the last step of tracing.

__processSingleLabel(self, seedLabel)

 

Extract a path defined by coordinates of the given seed label.

If grow level for given seed label is not provided, perform automatic grow level selection, and finally create path with all properties.

Parameters:
Returns: [barPath, ...]
list of paths resulting from tracing of the given source image and provided seed label.

Note: Function for determinating best grow level may be changed by assigning to self._tracingConf['BestFillAlgorithm'] reference for desired function.

__bitmapToPaths(self, sourceImage, seedLabel, invert=False)

 

Perform all operation releted with tracing bitmap into list of paths:

  1. create DOM structure from PoTrace SVG output,
  2. create single path segments instead of long bezier paths,
  3. convert path coordinates to absolute,
  4. reduce transformation rules (using svgfix module.
Parameters:
  • sourceImage (PIL.Image.Image) - image for tracing
  • seedLabel (barRegularLabel) - seed label
  • invert (bool) - determine if image has to be inverted before tracing
Returns: [barPath, ...]
paths resulting from tracing of the given source image and the provided seed label.

_getPath(self, pathElem, seedLabel)

 

Create barPath from provided SVG path element (result of tracing) and seed label. Resulting path has proper identifier and structure name, however it has black colour assigned.

Parameters:
  • pathElem (SVG path element) - xml.dom.minidom.Node
  • seedLabel (seed label) - barRegularLabel
Returns: barPath
path representation created from provided SVG path element

_getNewPathID(self, seedLabel)

 

Generate proper path identifier of the path related to the seed label.

Parameters:
Returns: str
identifier of new path generated using self._tracingConf['NewPathIdTemplate']

__substractFromBrainOutline(self, imageToSubstract, source='Struct')

 

Mark traced areas on __brainOutline. Depending on source marking is performed in different way. Region denoted by vBrain regions are changed to black (0) while areas from tracing normal labels are changed to 100.

Parameters:
  • imageToSubstract (PIL.Image.Image) - PIL image
  • source (str) - determines source of imageToSubstract (may be either 'Struct' or 'Brain').

__applyFill(self, sourceImage, seedLabel, retNPIX=False)

 

Apply flood fill to given image using coordinates passed in the seed label.

Description:

  1. Extract coordinates and structure name from seedLabel.
  2. Rescale SVG coordinates to rendered image coordinates
  3. Fill given image with black color
  4. Extend filled region by applying MinFilter filter. Do it l+1 times
  5. Return flooded image or return number of black pixels depending on retNPIX value.
Parameters:
  • sourceImage (PIL.Image.Image) - image to be floodfilled
  • seedLabel (barRegularLabel) - seed label
  • retNPIX (bool) - if True, floodfilled image is returned along with number of replaced pixels; otherwise only flooded image is returned
Returns: (PIL.Image.Image, int) or PIL.Image.Image
flooded image (and number of flooded pixels if requested)

__isAllowedForFilling(self, im, seedLabel)

 

Determine if bitmap with given seed label is suitable for tracing. There are briefly two conditions which need to be satisfied in order to allow the tracing:

  1. Seed has to be placed within brain contour. The brain contour is defined at the begining of tracing procedure.
  2. Seed has to be placed at white pixel. If seed points into non-white pixel is it a) border between two structures; b) area outside brain contour.

In both cases debug information is printed.

Parameters:
  • im (PIL.Image.Image) - image to be floodfilled
  • seedLabel (seed label) - barRegularLabel
Returns: bool
True if image is suitable for tracing (according to testing conditions), False otherwise

__getUnlabeledAreas(self)

 

Find white pixels in the image. If found pixel has white neighbourhood, its coordinates are returned, otherwise iteration continues until all white pixels are spotted.

Current algorithm is rather ineffective. Main reason is that function has to exit if patch of white pixels is spotted. Then function is invoked again and iteration starts from beginning which is extremely ineffective. What should be done in such case? Perhaps implementation should include iterator. The problem is that we need to change array while we iterate over this array.

Returns: (int, int)
(x, y) image coordinates of first spotted pixel that belongs to patch (two or more adjecent pixeles) of white pixels; if there is no such pixel, None

__isOutsideBrainOutline(self, seedLabel)

 

Determine if label is placed outside brain outline according to values of self.__brainOutline.

Parameters:
Returns: bool
True if label is placed outside brain, False otherwise

__isOverContour(self, im, seedLabel)

 

Determine if label is not placed over boundary.

Parameters:
  • im (PIL.Image.Image) - image to verify seed label location
  • seedLabel (seed label) - barRegularLabel
Returns: bool
True if label is not placed over contour, False otherwise

_saveBitmap(self, im, filename)

 

Save provided image.

Parameters:
  • im (PIL.Image.Image) - bitmap image to be saved
  • filename (str) - name of the output file (only filename - without path; provide .png extension)

To Do: integrate _saveBitmap and _saveSVG into one function

_saveSVG(self, svgdom, filename)

 

Save provided SVG.

Parameters:
  • svgdom (xml.dom.minidom.Document) - SVG image to be saved
  • filename (str) - name of the output file (only filename - without path; provide .png extension)

To Do: integrate _saveBitmap and _saveSVG into one function

__getCoveredAreasList(self, seedLabel)

 

For images from self.__imageCache perform floodfilling with seed label.

Parameters:
Returns: ([PIL.Image.Image, ...], [int, ...])
pair of lists of floodfilled images and area of floodfill in pixels (both lists have the same length and are corresponding to some prefix of self.__imageCache)

__dumpWrongSeed(self, im, seedLabel)

 

Output warning message to stderr and dump invalid image into a file.

Parameters:
  • im (PIL.Image.Image) - image to be dumped
  • seedLabel (seed label) - barRegularLabel