|
| 1 | +""" |
| 2 | +====================================== |
| 3 | +Thresholding an Image with RangeSlider |
| 4 | +====================================== |
| 5 | +
|
| 6 | +Using the RangeSlider widget to control the thresholding of an image. |
| 7 | +
|
| 8 | +The RangeSlider widget can be used similarly to the `.widgets.Slider` |
| 9 | +widget. The major difference is that RangeSlider's ``val`` attribute |
| 10 | +is a tuple of floats ``(lower val, upper val)`` rather than a single float. |
| 11 | +""" |
| 12 | + |
| 13 | +import numpy as np |
| 14 | +import matplotlib.pyplot as plt |
| 15 | +from matplotlib.widgets import RangeSlider |
| 16 | + |
| 17 | +# generate a fake image |
| 18 | +np.random.seed(19680801) |
| 19 | +N = 128 |
| 20 | +img = np.random.randn(N, N) |
| 21 | + |
| 22 | +fig, axs = plt.subplots(1, 2, figsize=(10, 5)) |
| 23 | +plt.subplots_adjust(bottom=0.25) |
| 24 | + |
| 25 | +im = axs[0].imshow(img) |
| 26 | +axs[1].hist(img.flatten(), bins='auto') |
| 27 | +axs[1].set_title('Histogram of pixel intensities') |
| 28 | + |
| 29 | +# Create the RangeSlider |
| 30 | +slider_ax = plt.axes([0.20, 0.1, 0.60, 0.03]) |
| 31 | +slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max()) |
| 32 | + |
| 33 | +# Create the Vertical lines on the histogram |
| 34 | +lower_limit_line = axs[1].axvline(slider.val[0], color='k') |
| 35 | +upper_limit_line = axs[1].axvline(slider.val[1], color='k') |
| 36 | + |
| 37 | + |
| 38 | +def update(val): |
| 39 | + # The val passed to a callback by the RangeSlider will |
| 40 | + # be a tuple of (min, max) |
| 41 | + |
| 42 | + # Update the image's colormap |
| 43 | + im.norm.vmin = val[0] |
| 44 | + im.norm.vmax = val[1] |
| 45 | + |
| 46 | + # Update the position of the vertical lines |
| 47 | + lower_limit_line.set_xdata([val[0], val[0]]) |
| 48 | + upper_limit_line.set_xdata([val[1], val[1]]) |
| 49 | + |
| 50 | + # Redraw the figure to ensure it updates |
| 51 | + fig.canvas.draw_idle() |
| 52 | + |
| 53 | + |
| 54 | +slider.on_changed(update) |
| 55 | +plt.show() |
| 56 | + |
| 57 | +############################################################################# |
| 58 | +# |
| 59 | +# ------------ |
| 60 | +# |
| 61 | +# References |
| 62 | +# """""""""" |
| 63 | +# |
| 64 | +# The use of the following functions, methods, classes and modules is shown |
| 65 | +# in this example: |
| 66 | + |
| 67 | +import matplotlib |
| 68 | +matplotlib.widgets.RangeSlider |
0 commit comments