Jupyter Notebook交互式降噪绘图:滑块联动逻辑异常求助
I get it—having the noise regenerate every time you adjust the smoothing slider is super frustrating, especially when you just want to see how different sigma values affect the same noisy signal. Let's fix this by adding a simple state management layer to your code, so noise only updates when the counts slider changes.
Here's a clean, memory-efficient solution using a class to track the current noise state:
import ipywidgets as widgets import matplotlib.pyplot as plt import numpy as np import skimage %matplotlib inline class NoiseFilterVisualizer: def __init__(self, base_signal): self.base_signal = base_signal self.current_counts = None self.current_noise = None def _update_noise_if_needed(self, counts): # Only regenerate noise if the counts value has changed if counts != self.current_counts: normalized_signal = self.base_signal / np.sum(self.base_signal) * counts self.current_noise = np.random.poisson(normalized_signal) self.current_counts = counts return self.current_noise def plot(self, counts, sigma): noise = self._update_noise_if_needed(counts) filtered = skimage.filters.gaussian(noise, sigma) # Clear previous plot to avoid overlapping lines plt.clf() plt.plot(noise / np.max(noise), label='Noisy Signal') plt.plot(filtered / np.max(filtered), label='Filtered Signal') plt.legend() plt.xlabel('Sample Index') plt.ylabel('Normalized Amplitude') plt.show() # Initialize our visualizer with the base signal base_sig = np.heaviside(np.linspace(-1,1,100),1)+1 visualizer = NoiseFilterVisualizer(base_sig) # Create sliders counts_slider = widgets.IntSlider(min=100, max=10000, step=10, description='Counts') sigma_slider = widgets.IntSlider(min=1, max=100, description='Smoothing') # Hook up the interaction widgets.interact(visualizer.plot, counts=counts_slider, sigma=sigma_slider)
How this works:
- The
NoiseFilterVisualizerclass keeps track of the last usedcountsvalue and the corresponding noise array incurrent_countsandcurrent_noise. - The
_update_noise_if_neededmethod checks if the incoming counts value is different from the stored one. If it is, it regenerates the noise; otherwise, it returns the existing noise array. - We use
plt.clf()to clear the previous plot before drawing new lines, which prevents messy overlapping plots as you adjust sliders.
This approach is far more memory-efficient than pre-storing multiple noise arrays—we only keep one noise array in memory at a time, and it only updates when you actually change the noise level. It should work perfectly with your conda environment versions (Python 3.7.3, ipywidgets 7.5.1, etc.).
内容的提问来源于stack exchange,提问作者Dhirschm

