Threshold an image with slider widget


I try to threshold an image manually by using a slider widget to set the
threshold value (I don’t binarize my image, but mask it). I superimpose my
thresholded image to the original according to a colormap.

I cannot figure out why if I put the initial threshold to the max value of my
original image, my thresolded one is monochrome while with another initial
value, it follows the colormap.

Here is my code (change `f0 = gray_data.max()` to `f0 = gray_data.max() / 2`
to see the difference):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

# Generate some data...
gray_data = np.arange(10000).reshape(100, 100)

fig, ax = plt.subplots()

axcolor = 'lightgoldenrodyellow'
axthresh = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)

f0 = gray_data.max()
sthresh = Slider(axthresh, 'threshold', gray_data.min(), gray_data.max(),

mask = gray_data < f0
masked =, mask=mask)
masked_ax = ax.imshow(masked, alpha=0.5)

def update(val):
    threshold = sthresh.val
    mask = gray_data < threshold
    masked.mask = mask

Thank you for your help.