Threshold an image with slider widget

Hello,

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()
fig.subplots_adjust(bottom=0.25)
ax.matshow(gray_data, cmap=plt.cm.gray)

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(),
valinit=f0)

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

def update(val):
    threshold = sthresh.val
    mask = gray_data < threshold
    masked.mask = mask
    masked_ax.set_data(masked)
    fig.canvas.draw_idle()
sthresh.on_changed(update)

plt.show()
'''

Thank you for your help.