Skip to content

Commit da65625

Browse files
authored
Merge pull request #15 from dstansby/hist-2d
Support 2D and RGB images for histograms
2 parents 61050ea + b67be6c commit da65625

File tree

4 files changed

+52
-8
lines changed

4 files changed

+52
-8
lines changed

Diff for: CHANGELOG.rst

+12
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.

Diff for: src/napari_matplotlib/histogram.py

+25-4
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()

Diff for: src/napari_matplotlib/tests/conftest.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import numpy as np
2+
import pytest
3+
4+
5+
@pytest.fixture(
6+
params=[
7+
((100, 100), {"rgb": False}),
8+
((100, 100, 100), {"rgb": False}),
9+
((100, 100, 3), {"rgb": True}),
10+
]
11+
)
12+
def image_data(request):
13+
return np.ones(request.param[0]), request.param[1]

Diff for: src/napari_matplotlib/tests/test_histogram.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import numpy as np
2-
31
from napari_matplotlib import HistogramWidget
42

53

6-
def test_example_q_widget(make_napari_viewer):
4+
def test_example_q_widget(make_napari_viewer, image_data):
75
# Smoke test adding a histogram widget
86
viewer = make_napari_viewer()
9-
viewer.add_image(np.random.random((100, 100)))
7+
viewer.add_image(image_data[0], **image_data[1])
108
HistogramWidget(viewer)

0 commit comments

Comments
 (0)