Skip to content

Add colour vision deficiency simulation #20649

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions lib/matplotlib/artist.py
Original file line number Diff line number Diff line change
Expand Up @@ -924,13 +924,20 @@ def set_agg_filter(self, filter_func):

Parameters
----------
filter_func : callable
A filter function, which takes a (m, n, 3) float array and a dpi
value, and returns a (m, n, 3) array.
filter_func : callable or str or None
A filter function, or the name of a builtin one.

.. ACCEPTS: a filter function, which takes a (m, n, 3) float array
and a dpi value, and returns a (m, n, 3) array
If passed a callable, then it should have the signature:

def filter_func(np.ndarray[(M, N, 3), float]) -> \
np.ndarray[(M, N, 3), float]

If passed a string, it should be one of the names accepted by
`matplotlib.colors.get_color_filter`.
"""
if isinstance(filter_func, str):
from . import colors
filter_func = colors.get_color_filter(filter_func)
self._agg_filter = filter_func
self.stale = True

Expand Down
66 changes: 66 additions & 0 deletions lib/matplotlib/backends/backend_gtk3.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,72 @@ def __init__(self, canvas, window):
'clicked', getattr(self, callback))
tbutton.set_tooltip_text(tooltip_text)

# Add the CVD simulation button. The type of menu is progressively
# downgraded depending on GTK version.
toolitem = Gtk.SeparatorToolItem()
self.insert(toolitem, -1)

filters = ['None', 'Greyscale', 'Deuteranopia', 'Protanopia',
'Tritanopia']
image = Gtk.Image.new_from_gicon(
Gio.Icon.new_for_string(
str(cbook._get_data_path('images', 'eye-symbolic.svg'))),
Gtk.IconSize.LARGE_TOOLBAR)

if Gtk.check_version(3, 6, 0) is None:
group = Gio.SimpleActionGroup.new()
action = Gio.SimpleAction.new_stateful('cvdsim',
GLib.VariantType('s'),
GLib.Variant('s', 'none'))
group.add_action(action)

@functools.partial(action.connect, 'activate')
def set_filter(action, parameter):
filter = parameter.get_string().lower()
if filter == 'none':
filter = None

self.canvas.figure.set_agg_filter(filter)
self.canvas.draw_idle()
action.set_state(parameter)

menu = Gio.Menu()
for filt in filters:
menu.append(filt, f'local.cvdsim::{filt.lower()}')

button = Gtk.MenuButton.new()
button.add(image)
button.insert_action_group('local', group)
button.set_menu_model(menu)
button.get_style_context().add_class('flat')

item = Gtk.ToolItem()
item.add(button)
self.insert(item, -1)
else:
def set_filter(item):
filter = item.get_label().lower()
if filter == 'none':
filter = None

self.canvas.figure.set_agg_filter(filter)
self.canvas.draw_idle()

menu = Gtk.Menu()
group = []
for filt in filters:
item = Gtk.RadioMenuItem.new_with_label(group, filt)
item.set_active(filt == 'None')
item.connect('activate', set_filter)
group.append(item)
menu.append(item)
menu.show_all()

tbutton = Gtk.MenuToolButton.new(image, "Filter")
tbutton.set_menu(menu)
self.insert(tbutton, -1)

# Fill the space in between to ensure message is at end.
toolitem = Gtk.SeparatorToolItem()
self.insert(toolitem, -1)
toolitem.set_draw(False)
Expand Down
27 changes: 27 additions & 0 deletions lib/matplotlib/backends/backend_qt5.py
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,33 @@ def __init__(self, canvas, parent, coordinates=True):
if tooltip_text is not None:
a.setToolTip(tooltip_text)

menu = QtWidgets.QMenu()
group = QtWidgets.QActionGroup(menu)

@group.triggered.connect
def set_filter(action):
filter = action.text().lower()
if filter == 'none':
filter = None
self.canvas.figure.set_agg_filter(filter)
self.canvas.draw_idle()

for filt in ['None', 'Greyscale', 'Deuteranopia', 'Protanopia',
'Tritanopia']:
a = menu.addAction(filt)
a.setCheckable(True)
a.setActionGroup(group)
a.setChecked(filt == 'None')

self.addSeparator()
tb = QtWidgets.QToolButton()
tb.setIcon(self._icon('eye.png'))
tb.setText('Filter')
tb.setToolTip('Simulate color vision deficiencies')
tb.setPopupMode(QtWidgets.QToolButton.InstantPopup)
tb.setMenu(menu)
self.addWidget(tb)

# Add the (x, y) location widget at the right side of the toolbar
# The stretch factor is 1 which means any resizing of the toolbar
# will resize this label instead of the buttons.
Expand Down
64 changes: 64 additions & 0 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2394,3 +2394,67 @@ def from_levels_and_colors(levels, colors, extend='neither'):

norm = BoundaryNorm(levels, ncolors=n_data_colors)
return cmap, norm


def get_color_filter(name):
"""
Given a color filter name, create a color filter function.

Parameters
----------
name : str
The color filter name, one of the following:

- ``'greyscale'``: Convert the input to luminosity.
- ``'deuteranopia'``: Simulate the most common form of red-green
colorblindness.
- ``'protanopia'``: Simulate a rarer form of red-green colorblindness.
- ``'tritanopia'``: Simulate the rare form of blue-yellow
colorblindness.

Color conversions use `colorspacious`_.

Returns
-------
callable
A color filter function that has the form:

def filter(input: np.ndarray[M, N, D])-> np.ndarray[M, N, D]

where (M, N) are the image dimentions, and D is the color depth (3 for
RGB, 4 for RGBA). Alpha is passed through unchanged and otherwise
ignored.
"""
from colorspacious import cspace_converter

filter = _api.check_getitem({
'greyscale': 'greyscale',
'deuteranopia': 'deuteranomaly',
'protanopia': 'protanomaly',
'tritanopia': 'tritanomaly',
}, name=name)

if filter == 'greyscale':
rgb_to_jch = cspace_converter('sRGB1', 'JCh')
jch_to_rgb = cspace_converter('JCh', 'sRGB1')

def filter(im):
greyscale_JCh = rgb_to_jch(im)
greyscale_JCh[..., 1] = 0
im = jch_to_rgb(greyscale_JCh)
return im
else:
cvd_space = {'name': 'sRGB1+CVD', 'cvd_type': filter,
'severity': 100}
filter = cspace_converter(cvd_space, "sRGB1")

def filter_func(im, dpi):
alpha = None
if im.shape[-1] == 4:
im, alpha = im[..., :3], im[..., 3]
im = filter(im)
if alpha is not None:
im = np.dstack((im, alpha))
return np.clip(im, 0, 1), 0, 0

return filter_func
1 change: 1 addition & 0 deletions lib/matplotlib/mpl-data/images/eye-symbolic.svg
Binary file added lib/matplotlib/mpl-data/images/eye.pdf
Binary file not shown.
Binary file added lib/matplotlib/mpl-data/images/eye.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
70 changes: 70 additions & 0 deletions lib/matplotlib/mpl-data/images/eye.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added lib/matplotlib/mpl-data/images/eye_large.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions tools/make_icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ def make_matplotlib_icon():
('subplots', 0xf1de),
('qt4_editor_options', 0xf201),
('help', 0xf128),
('eye', 0xf06e),
]


Expand Down