Skip to content

Commit 3fd5359

Browse files
committed
Support 2D and RGB images for histograms
1 parent 61050ea commit 3fd5359

File tree

3 files changed

+44
-6
lines changed

3 files changed

+44
-6
lines changed

CHANGELOG.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
0.0.2
2+
=====
3+
4+
New features
5+
------------
6+
- `HistogramWidget` now shows individual histograms for RGB channels when
7+
present.
8+
9+
10+
Bug fixes
11+
---------
12+
- `HistogramWidget` now works properly with 2D images.

src/napari_matplotlib/histogram.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
__all__ = ["HistogramWidget"]
77

88

9+
_COLORS = {"r": "tab:red", "g": "tab:green", "b": "tab:blue"}
10+
11+
912
class HistogramWidget(NapariMPLWidget):
1013
"""
1114
Widget to display a histogram of the currently selected layer.
@@ -40,9 +43,27 @@ def hist_current_layer(self) -> None:
4043
"""
4144
self.axes.clear()
4245
layer = self.layer
43-
z = self.viewer.dims.current_step[0]
4446
bins = np.linspace(np.min(layer.data), np.max(layer.data), 100)
45-
data = layer.data[z]
46-
self.axes.hist(data.ravel(), bins=bins)
47-
self.axes.set_title(f"{layer.name}, z={z}")
47+
48+
if layer.data.ndim - layer.rgb == 3:
49+
# 3D data, can be single channel or RGB
50+
data = layer.data[self.current_z]
51+
self.axes.set_title(f"z={self.current_z}")
52+
else:
53+
data = layer.data
54+
55+
if layer.rgb:
56+
# Histogram RGB channels independently
57+
for i, c in enumerate("rgb"):
58+
self.axes.hist(
59+
data[..., i].ravel(),
60+
bins=bins,
61+
label=c,
62+
histtype="step",
63+
color=_COLORS[c],
64+
)
65+
else:
66+
self.axes.hist(data.ravel(), bins=bins, label=layer.name)
67+
68+
self.axes.legend()
4869
self.canvas.draw()
Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
import numpy as np
2+
import pytest
23

34
from napari_matplotlib import HistogramWidget
45

56

6-
def test_example_q_widget(make_napari_viewer):
7+
# Test with 2D and 3D data
8+
@pytest.mark.parametrize(
9+
"data", [np.random.random((100, 100)), np.random.random((100, 100, 100))]
10+
)
11+
def test_example_q_widget(make_napari_viewer, data):
712
# Smoke test adding a histogram widget
813
viewer = make_napari_viewer()
9-
viewer.add_image(np.random.random((100, 100)))
14+
viewer.add_image(data)
1015
HistogramWidget(viewer)

0 commit comments

Comments
 (0)