fsleyes.colourmaps

This module manages the colour maps and lookup tables available for overlay rendering in FSLeyes.

The init() function must be called before any colour maps or lookup tables can be accessed [*].

FSLeyes colour maps and lookup tables are stored in the following locations:

  • [assetsbase]/colourmaps/

  • [assetsbase]/luts/

  • [settingsbase]/colourmaps/

  • [settingsbase]/luts/

  • [sitebase]/colourmaps/

  • [sitebase]/luts/

where:

  • [assetsbase] is the location of the FSLeyes assets directory, containing built-in colourmaps and lookup tables (see the fsleyes.assetDir attribute)

  • [settingsbase] is the base directory use by the fsl.utils.settings module for storing FSLeyes application settings and data, and user-added colourmaps and lookup tables.

  • [sitebase] is a site-specific configuration directory, specified by the $FSLEYES_SITE_CONFIG_DIR environment variable, which may contain site-specific colourmaps and lookup tables.

When init() is called, it searches in the above locations, and attempts to load all files within which have the suffix .cmap or .lut respectively. If a user-added map file has the same name as a built-in map file, the user-added one will override the built-in.

Colour maps

A .cmap file defines a colour map which may be used to display a range of intensity values - see the VolumeOpts.cmap property for an example. A .cmap file must contain a list of RGB colours, one per line, with each colour specified by three space-separated floating point values in the range 0.0 - 1.0, for example:

1.000000 0.260217 0.000000
0.000000 0.687239 1.000000
0.738949 0.000000 1.000000

This list of RGB values is used to create a ListedColormap object, which is then registered with the matplotlib.cm module (using the file name prefix as the colour map name), and thus made available for rendering purposes.

The following functions are available for managing and accessing colour maps:

scanColourMaps

Scans the colour maps directories, and returns a dictionary of {id : filepath} containing the IDs and files of all colour maps contained within.

getColourMaps

Returns a list containing the names of all available colour maps.

getColourMap

Returns the colour map instance of the specified key.

getColourMapLabel

Returns a label/display name for the specified colour map.

getColourMapFile

Returns the file associated with the specified colour map, or None if the colour map does not exist as a file.

getColourMapKey

Returns the key associated with the specified colour map file.

loadColourMapFile

Load the given file, assumed to be a colour map.

registerColourMap

Loads RGB data from the given file, and registers it as a matplotlib ListedColormap instance.

installColourMap

Attempts to install a previously registered colourmap into the [settingsbase]/colourmaps/ directory.

isColourMapRegistered

Returns True if the specified colourmap is registered, False otherwise.

isColourMapInstalled

Returns True if the specified colourmap is installed, False otherwise.

Display name and ordering

FSLeyes comes with a file at [assetsbase]/colourmaps/order.txt, which contains a list of colour map names and identifiers, defining the order in which the colour maps should be displayed to the user. Any colour maps which are present in [assetsbase]/colourmaps/, but are not listed in the order.txt, file will be appended to the end of the list, and their name will be derived from the file name.

If a file called [settingsbase]/colourmaps/order.txt or [sitebase]/colourmaps/order.txt exists in the user or site configuration directory, then it will be used in place of the built-in [assetsbase]/colourmaps/order.txt file.

User-added colour maps

An identifier and display name for all user-added colour maps are added to a persistent setting called fsleyes.colourmaps, which is a dictionary of { cmapid : displayName } mappings. The cmapid is typically the display name, converted to lower case, with spaces replaced with underscores. A user-added colour map with id cmapid will be saved as [settingsbase]/colourmaps/cmapid.cmap.

Installing a user-added colour map is a two-step process - this is implemented in the LoadColourMapAction class:

  1. First, the colour map must be registered, via the registerColourMap() function. This adds the colour map to the register, but does not persist it beyond the current execution environment.

  2. Calling the installColourMap() function will add the colour map permanently.

Alternatively, colour map files can be copied directly into [settingsbase]/colourmaps/, and their name specified in [settingsbase]/colourmaps/order.txt as outlined above. In this case, the colour maps will be loaded automatically via init().

Lookup tables

A .lut file defines a lookup table which may be used to display images wherein each voxel has a discrete integer label. Each of the possible voxel values such an image has an associated colour and name. Each line in a .lut file must specify the label value, RGB colour, and associated name. The first column (where columns are space-separated) defines the label value, the second to fourth columns specify the RGB values, and all remaining columns give the label name. For example:

1  0.00000 0.93333 0.00000 Frontal Pole
2  0.62745 0.32157 0.17647 Insular Cortex
3  1.00000 0.85490 0.72549 Superior Frontal Gyrus

This list of label, colour, and name mappings is used to create a LookupTable instance, which can be used to access the colours and names associated with each label value.

Once created, LookupTable instances may be modified - labels can be added/removed, and the name/colour of existing labels can be modified. The installLookupTable() method will install a new lookup table, or save any changes made to an existing one.

Built-in user- and site-added lookup tables are managed in the same manner as described for colour maps above. The following functions are available to access and manage LookupTable instances:

scanLookupTables

Scans the lookup table directories, and returns a dictionary of {id : filepath} containing the IDs and files of all lookup tables contained within.

getLookupTables

Returns a list containing all available lookup tables.

getLookupTable

Returns the LookupTable instance of the specified key/ID.

getLookupTableFile

Returns the file associated with the specified lookup table, or None if the lookup table does not exist as a file.

getLookupTableKey

Returns the key associated with the specified lookup table file.

loadLookupTableFile

Loads the given file, assumed to be a lookup table.

registerLookupTable

Registers the given LookupTable instance (if lut is a string, it is assumed to be the name of a .lut file, which is loaded).

installLookupTable

Attempts to install/save a previously registered lookup table into the [settingsbase]/luts directory.

isLookupTableRegistered

Returns True if the specified lookup table is registered, False otherwise.

isLookupTableInstalled

Returns True if the specified loolup table is installed, False otherwise.

Miscellaneous

Some utility functions are also kept in this module. These functions are used for querying installed colour maps and lookup tables,

fileType

Attempts to guess the type of fname.

getCmapDirs

Returns a list of directories within which all colour map files can be found.

getLutDirs

Returns a list of directories within which all lookup table files can be found.

The following functions may be used for calculating the relationship between a data display range and brightness/contrast scales, and generating/manipulating colours:

displayRangeToBricon

Converts the given brightness/contrast values to a display range, given the data range.

briconToDisplayRange

Converts the given brightness/contrast values to a display range, given the data range.

briconToScaleOffset

Used by the briconToDisplayRange() and the applyBricon() functions.

applyBricon

Applies the given brightness and contrast levels to the given rgb colour(s).

darken

Darken the given rgb colour(s) by the given amount.

brighten

Brighten the given rgb colour(s) by the given amount.

randomColour

Generates a random RGB colour.

randomBrightColour

Generates a random saturated RGB colour.

randomDarkColour

Generates a random saturated and darkened RGB colour.

complementaryColour

Generate a colour which can be used as a complement/opposite to the given colour.

fsleyes.colourmaps._getMapDirs(subDir)[source]

Used by the getCmapDirs() and getLutDirs() functions. Returns a list of all base directories within which colourmap/lookup table files might be found, in the order of precedence (i.e. files in the first directory should take precedence over subsequent directories).

fsleyes.colourmaps.getCmapDirs()[source]

Returns a list of directories within which all colour map files can be found.

fsleyes.colourmaps.getLutDirs()[source]

Returns a list of directories within which all lookup table files can be found.

fsleyes.colourmaps._walk(dirname, suffix)[source]

Recursively searches dirname, returning a list of all files with the specified suffix.

fsleyes.colourmaps._scanMaps(mapDir, mapFiles)[source]

Used by the scanColourMaps() and scanLookupTables() functions. Converts a sequence of colourmap or lookup table file paths into IDs. Returns a dictionary containing {mapID : mapFile} mappings

fsleyes.colourmaps._scanMapDirs(mapDirs, suffixes)[source]

Used by the scanColourMaps() and scanLookupTables() functions. Searches the given mapDir for all files with any of the given suffixes.

fsleyes.colourmaps.scanColourMaps()[source]

Scans the colour maps directories, and returns a dictionary of {id : filepath} containing the IDs and files of all colour maps contained within. This function may be called before init().

fsleyes.colourmaps.scanLookupTables()[source]

Scans the lookup table directories, and returns a dictionary of {id : filepath} containing the IDs and files of all lookup tables contained within. This function may be called before init().

fsleyes.colourmaps._cmaps = None

A dict which contains all registered colour maps as {key : _Map} mappings.

fsleyes.colourmaps._luts = None

A dict which contains all registered lookup tables as {key : _Map} mappings.

fsleyes.colourmaps.init(force=False)[source]

This function must be called before any of the other functions in this module can be used.

It initialises the colour map and lookup table registers, loading all built-in and user-added colour map and lookup table files that exist.

Parameters:

force – Forces the registers to be re-initialised, even if they have already been initialised.

fsleyes.colourmaps.registerColourMap(cmapFile, overlayList=None, displayCtx=None, key=None, name=None)[source]

Loads RGB data from the given file, and registers it as a matplotlib ListedColormap instance.

Note

If the overlayList and displayContext arguments are provided, the cmap property of all VolumeOpts instances are updated to support the new colour map.

Parameters:
  • cmapFile – Name of a file containing RGB values

  • overlayList – A OverlayList instance which contains all overlays that are being displayed (can be None).

  • displayCtx – A DisplayContext instance describing how the overlays in overlayList are being displayed. Must be provided if overlayList is provided.

  • key – Name to give the colour map. If None, defaults to the file name prefix.

  • name – Display name for the colour map. If None, defaults to the name.

Returns:

The key that the ColourMap was registered under.

fsleyes.colourmaps.registerLookupTable(lut, overlayList=None, displayCtx=None, key=None, name=None)[source]

Registers the given LookupTable instance (if lut is a string, it is assumed to be the name of a .lut file, which is loaded).

Note

If the overlayList and displayContext arguments are provided, the lut property of all LabelOpts instances are updated to support the new lookup table.

Parameters:
  • lut – A LookupTable instance, or the name of a .lut file.

  • overlayList – A OverlayList instance which contains all overlays that are being displayed (can be None).

  • displayCtx – A DisplayContext instance describing how the overlays in overlayList are being displayed. Must be provided if overlayList is provided.

  • key – Name to give the lookup table. If None, defaults to the file name prefix.

  • name – Display name for the lookup table. If None, defaults to the name.

Returns:

The LookupTable object

fsleyes.colourmaps.getLookupTables()[source]

Returns a list containing all available lookup tables.

fsleyes.colourmaps.getLookupTable(key)[source]

Returns the LookupTable instance of the specified key/ID.

fsleyes.colourmaps.getColourMaps()[source]

Returns a list containing the names of all available colour maps.

fsleyes.colourmaps.getColourMap(key)[source]

Returns the colour map instance of the specified key.

fsleyes.colourmaps.getColourMapLabel(key)[source]

Returns a label/display name for the specified colour map.

fsleyes.colourmaps.getColourMapFile(key)[source]

Returns the file associated with the specified colour map, or None if the colour map does not exist as a file.

fsleyes.colourmaps.getLookupTableFile(key)[source]

Returns the file associated with the specified lookup table, or None if the lookup table does not exist as a file.

fsleyes.colourmaps.getColourMapKey(filename)[source]

Returns the key associated with the specified colour map file. Raises a ValueError if there is no colour map associated with the file.

fsleyes.colourmaps.getLookupTableKey(filename)[source]

Returns the key associated with the specified lookup table file. Raises a ValueError if there is no lookup table associated with the file.

fsleyes.colourmaps.isColourMapRegistered(key=None, filename=None)[source]

Returns True if the specified colourmap is registered, False otherwise.

If key is provided, a colour map with the specified identifier is searched for. Otherwise if filename is provided, a colour map which was loaded from that file is searched for. Otherwise a ValueError is raised.

fsleyes.colourmaps.isLookupTableRegistered(key=None, filename=None)[source]

Returns True if the specified lookup table is registered, False otherwise.

If key is provided, a lookup table with the specified identifier is searched for. Otherwise if filename is provided, a lookup table which was loaded from that file is searched for. Otherwise a ValueError is raised.

fsleyes.colourmaps.isColourMapInstalled(key)[source]

Returns True if the specified colourmap is installed, False otherwise. A KeyError is raised if the colourmap is not registered.

fsleyes.colourmaps.isLookupTableInstalled(key)[source]

Returns True if the specified loolup table is installed, False otherwise. A KeyError is raised if the lookup tabler is not registered.

fsleyes.colourmaps.installColourMap(key)[source]

Attempts to install a previously registered colourmap into the [settingsbase]/colourmaps/ directory.

fsleyes.colourmaps.installLookupTable(key)[source]

Attempts to install/save a previously registered lookup table into the [settingsbase]/luts directory.

fsleyes.colourmaps.fileType(fname)[source]

Attempts to guess the type of fname.

fname is assumed to be a FSLeyes colour map or lookup table file, or a FSLView-style VEST lookup table file.

A ValueError is raised if the file type cannot be determined.

Parameters:

fname – Name of file to check

Returns:

One of 'vest', 'cmap', or 'lut', depending on what the contents of fname look like.

fsleyes.colourmaps.loadColourMapFile(fname, aslut=False)[source]

Load the given file, assumed to be a colour map.

Parameters:
  • fname – FSLeyes or FSLView (VEST) colour map file

  • aslut – If True, the returned array will contain a label for each colour, ranging from 1 to N, where N is the number of colours in the file.

Returns:

A numpy array of shape (N, 3) containing the RGB values for N colours. Or, if aslut is True, A numpy array of shape (N, 4) containing a label, and the RGB values for N colours.

fsleyes.colourmaps.loadLookupTableFile(fname)[source]

Loads the given file, assumed to be a lookup table.

Parameters:

fname – Name of a FSLeyes lookup table file.

Returns:

A tuple containing:

  • A numpy array of shape (N, 4) containing the label and RGB values for N colours.

  • A list containin the name for each label

Note

The provided file may also be a colour map file (see loadColourMapFile()), in which case the labels will range from 1 to N, and the names will be strings containing the label values.

fsleyes.colourmaps.briconToScaleOffset(brightness, contrast, drange)[source]

Used by the briconToDisplayRange() and the applyBricon() functions.

Calculates a scale and offset which can be used to transform a display range of the given size so that the given brightness/contrast settings are applied.

Parameters:
  • brightness – Brightness, between 0.0 and 1.0.

  • contrast – Contrast, between 0.0 and 1.0.

  • drange – Data range.

fsleyes.colourmaps.briconToDisplayRange(dataRange, brightness, contrast)[source]

Converts the given brightness/contrast values to a display range, given the data range.

Parameters:
  • dataRange – The full range of the data being displayed, a (min, max) tuple.

  • brightness – A brightness value between 0 and 1.

  • contrast – A contrast value between 0 and 1.

fsleyes.colourmaps.displayRangeToBricon(dataRange, displayRange)[source]

Converts the given brightness/contrast values to a display range, given the data range.

Parameters:
  • dataRange – The full range of the data being displayed, a (min, max) tuple.

  • displayRange – A (min, max) tuple containing the display range.

fsleyes.colourmaps.applyBricon(rgb, brightness, contrast)[source]

Applies the given brightness and contrast levels to the given rgb colour(s).

Passing in 0.5 for both the brightness and contrast will result in the colour being returned unchanged.

Parameters:
  • rgb – A sequence of three or four floating point numbers in the range [0, 1] specifying an RGB(A) value, or a numpy array of shape (n, 3) or (n, 4) specifying n colours. If alpha values are passed in, they are returned unchanged.

  • brightness – A brightness level in the range [0, 1].

  • contrast – A contrast level in the range [0, 1].

fsleyes.colourmaps.darken(rgb, amount=0.05)[source]

Darken the given rgb colour(s) by the given amount. Short-hand for applyBricon(rgb, 0.5 - amount, 0.5).

fsleyes.colourmaps.brighten(rgb, amount=0.05)[source]

Brighten the given rgb colour(s) by the given amount. Short-hand for applyBricon(rgb, 0.5 + amount, 0.5).

fsleyes.colourmaps.randomColour()[source]

Generates a random RGB colour.

fsleyes.colourmaps.randomBrightColour()[source]

Generates a random saturated RGB colour.

fsleyes.colourmaps.randomDarkColour()[source]

Generates a random saturated and darkened RGB colour.

fsleyes.colourmaps.complementaryColour(rgb)[source]

Generate a colour which can be used as a complement/opposite to the given colour.

If the given rgb sequence contains four values, the fourth value (e.g. alpha) is returned unchanged.

fsleyes.colourmaps._caseInsensitiveLookup(d, k, default=None)[source]

Performs a case-insensitive lookup on the dictionary d, with the key k.

This function is used to allow case-insensitive retrieval of colour maps and lookup tables.

class fsleyes.colourmaps._Map(key, name, mapObj, mapFile, installed)[source]

Bases: object

A little class for storing details on registered colour maps and lookup tables. This class is only used internally.

__init__(key, name, mapObj, mapFile, installed)[source]

Create a _Map.

Parameters:
  • key – The identifier name of the colour map/lookup table, which must be passed to the getColourMap() and getLookupTable() functions to look up this map object.

  • name – The display name of the colour map/lookup table.

  • mapObj – The colourmap/lut object, either a matplotlib.colors.Colormap, or a LookupTable instance.

  • mapFile – The file from which this map was loaded, or None if this cmap/lookup table only exists in memory, or is a built in matplotlib colourmap.

  • installedTrue if this is a built in matplotlib colourmap or is installed in the fsleyes/colourmaps/ or fsleyes/luts/ directory, False otherwise.

__str__()[source]

Returns a string representation of this _Map.

__repr__()[source]

Returns a string representation of this _Map.

__dict__ = mappingproxy({'__module__': 'fsleyes.colourmaps', '__doc__': 'A little class for storing details on registered colour maps and lookup\n    tables. This class is only used internally.\n    ', '__init__': <function _Map.__init__>, '__str__': <function _Map.__str__>, '__repr__': <function _Map.__repr__>, '__dict__': <attribute '__dict__' of '_Map' objects>, '__weakref__': <attribute '__weakref__' of '_Map' objects>, '__annotations__': {}})
__module__ = 'fsleyes.colourmaps'
__weakref__

list of weak references to the object

class fsleyes.colourmaps.LutLabel(*args, **kwargs)[source]

Bases: HasProperties

This class represents a mapping from a value to a colour and name. LutLabel instances are created and managed by LookupTable instances.

Listeners may be registered on the name, colour, and enabled properties to be notified when they change.

__init__(value, name=None, colour=None, enabled=None)[source]

Create a LutLabel.

Parameters:
  • value – The label value.

  • name – The label name.

  • colour – The label colour.

  • enabled – Whether the label is enabled/disabled.

name

The display name for this label. Internally (for comparison), the internalName() is used, which is simply this name, converted to lower case.

colour

The colour for this label.

enabled

Whether this label is currently enabled or disabled.

property value

Returns the value of this LutLabel.

property internalName

Returns the internal name of this LutLabel, which is just its name, converted to lower-case. This is used by __eq__() and __hash__(), and by the LookupTable class.

__eq__(other)[source]

Equality operator - returns True if this LutLabel has the same value as the given one.

__lt__(other)[source]

Less-than operator - compares two LutLabel instances based on their value.

__hash__()[source]

The hash of a LutLabel is a combination of its value, name, and colour, but not its enabled state.

__str__()[source]

Returns a string representation of this LutLabel.

__repr__()[source]

Returns a string representation of this LutLabel.

__annotations__ = {}
__module__ = 'fsleyes.colourmaps'
class fsleyes.colourmaps.LookupTable(*args, **kwargs)[source]

Bases: Notifier

A LookupTable encapsulates a list of label values and associated colours and names, defining a lookup table to be used for colouring label images.

A label value typically corresponds to an anatomical region (as in e.g. atlas images), or a classification (as in e.g. white/grey matter/csf segmentations).

The label values, and their associated names/colours, in a LookupTable are stored in LutLabel instances, ordered by their value in ascending order. These are accessible by label value via the get() method, by index, by directly indexing the LookupTable instance, or by name, via the getByName() method. New label values can be added via the insert() and new() methods. Label values can be removed via the meth:delete method.

Notifications

The LookupTable class implements the Notifier interface. If you need to be notified when a LookupTable changes, you may register to be notified on the following topics:

Topic

Meaning

label

The properties of a LutLabel have changed.

saved

The saved state of this LookupTable has changed.

added

A new LutLabel has been added.

removed

A LutLabel has been removed.

__init__(key, name, lutFile=None)[source]

Create a LookupTable.

Parameters:
  • key – The identifier for this LookupTable. Must be a valid key (see isValidMapKey()).

  • name – The display name for this LookupTable.

  • lutFile – A file to load lookup table label values, names, and colours from. If None, this LookupTable will be empty - labels can be added with the new() or insert() methods.

lazyparse()[source]

Decorator which is used to lazy-parse the LUT file only when it is first needed.

__str__()[source]

Returns the name of this LookupTable.

__repr__()[source]

Returns the name of this LookupTable.

__len__()[source]

Returns the number of labels in this LookupTable.

__getitem__(i)[source]

Access the LutLabel at index i. Use the get() method to determine the index of a LutLabel from its value.

max()[source]

Returns the maximum current label value in this LookupTable.

__annotations__ = {}
__module__ = 'fsleyes.colourmaps'
property saved

Returns True if this LookupTable is registered and saved, False if it is not registered, or has been modified.

index(value)[source]

Returns the index in this LookupTable of the LutLabel with the specified value. Raises a ValueError if no LutLabel with this value is present.

Note

The value which is passed in can be either an integer specifying the label value, or a LutLabel instance.

labels()[source]

Returns an iterator over all LutLabel instances in this LookupTable.

get(value)[source]

Returns the LutLabel instance associated with the given value, or None if there is no label.

getByName(name)[source]

Returns the LutLabel instance associated with the given name, or None if there is no LutLabel. The name comparison is case-insensitive.

new(name=None, colour=None, enabled=None)[source]

Add a new LutLabel with value max() + 1, and add it to this LookupTable.

insert(value, name=None, colour=None, enabled=None)[source]

Create a new LutLabel associated with the given value and insert it into this LookupTable. Internally, the labels are stored in ascending (by value) order.

Returns:

The newly created LutLabel instance.

delete(value)[source]

Removes the label with the given value from the lookup table.

Raises a ValueError if no label with the given value is present.

save(lutFile)[source]

Saves this LookupTable instance to the specified lutFile.

__parse(lut, names)

Parses lut, a numpy array containing a LUT.

__labelChanged(value, valid, label, propName)

Called when the properties of any LutLabel change. Triggers notification on the label topic.