Kyle M. LeClairEngineering & Applied Research

Engineering Portfolio

Oscilloscope Waveform Reconstruction and Fourier Analysis

A MATLAB workflow that recovered approximate time-domain traces from archived oscilloscope images and enabled subsequent frequency-domain interpretation.

Independent Research & Computational Methods

Affiliation
Mirion (Paragon Energy Solutions)
Classification
Applied computational signal analysis
Stage
Developed computational analysis workflow

Recovering a three-day test record

At the end of a three-day hardware test, the numerical oscilloscope exports were corrupted. The screen captures survived. I developed this MATLAB workflow to recover a voltage estimate from each horizontal pixel column and examine the frequency content of the visible trace. That gave me a way to revisit the test before deciding which observations would require another acquisition.

The example below spans 400 µs. Its 738 image columns are sufficient to distinguish excursions in time and compare spectral amplitudes. They also set a firm limit on the result: several samples from the instrument can occupy the same column on screen.

Original yellow oscilloscope trace crossing a dim graticule on a black background.
The surviving input, shown at its original aspect ratio. The bright vertical strokes are particularly important because each spans several possible voltage values at one horizontal position.

Isolating the trace

The script converts the RGB image to hue, saturation, and value (HSV). It retains pixels with hue from 0.15 through 0.17 and saturation and brightness each from 0.4 through 1.0. These thresholds describe the yellow phosphor-like trace in this capture. A trace of another color requires different thresholds, and a yellow annotation within the plotting area could also pass the mask.

colorMask = (hsvImage(:,:,1) >= hueMin) & (hsvImage(:,:,1) <= hueMax) & ...
            (hsvImage(:,:,2) >= saturationMin) & (hsvImage(:,:,2) <= saturationMax) & ...
            (hsvImage(:,:,3) >= valueMin) & (hsvImage(:,:,3) <= valueMax);

Two passes repair small breaks. The first connects selected pixels separated by one to three unselected pixels along a row. The second applies the same rule down each column of the updated mask. The display multiplies the original RGB image by that mask. A newly admitted black pixel therefore stays black in the illustration and carries zero brightness weight in the numerical estimate.

Yellow trace after masking, with most background and graticule detail suppressed.
The supplied mask visualization retains the trace against black. Comparing it with the input helps identify loss of dim trace segments or inclusion of other colored features.

Estimating one voltage per column

For column jj, let SjS_j contain the selected row indices and let brjb_{rj} denote the original HSV brightness at row rr. I estimate the center of the visible stroke with a brightness-weighted mean,

r̂j=∑r∈Sjrbrj3∑r∈Sjbrj3.\hat r_j=\frac{\sum_{r\in S_j} r\,b_{rj}^{3}}{\sum_{r\in S_j} b_{rj}^{3}}.

Cubing the brightness gives a pixel at half brightness one-eighth of the weight of a fully bright pixel. This favors the trace core over dim edges. On a nearly vertical stroke the estimate falls between its extremes. If two traces or branches occupy a column, the same averaging can place the estimate between them.

weights = double(hsvImage(rows_on, col, 3)).^3;  
waveform_pixels(col) = sum(rows_on .* weights) / sum(weights);

An empty column receives a missing value. For an interior gap, linear interpolation joins the nearest available row estimates on either side. In this example column 376 (MATLAB indexing) required interpolation. The gap repair acts on pixels in two dimensions; the interpolation acts later, on the one-dimensional series of row estimates.

Calibrating the image axes

The script assigns the first and last columns to 0 and 400 µs, using ten divisions at 40 µs per division. It assigns the top and bottom rows to +5.4 and −5.4 V. With one-based indices, image height HH, and width WW, the mappings are

tj=(j−1)400W−1μst_j=(j-1)\frac{400}{W-1}\,\mu\mathrm{s}

vj=(5.4−(r̂j−1)10.8H−1)Vv_j=\left(5.4-(\hat r_j-1)\frac{10.8}{H-1}\right)\,\mathrm{V}

The row coordinate increases downward, so the voltage scale has a negative slope. The calibration is entered in the script. Applying it to a different crop requires knowing the time and voltage at the new image boundaries.

Blue reconstructed voltage across 400 microseconds, with the deepest negative excursion near 330 microseconds.
The calibrated trace retains the sequence of excursions across the capture. Its extrema describe the estimated center of the displayed stroke.

Reading the spectrum

Before taking the discrete Fourier transform, the script subtracts the arithmetic mean of the recovered voltages. This removes the DC component from the spectrum while preserving it in the time-domain figure. For N=WN=W columns, sample mean v‾\bar v, and image-derived interval Δt\Delta t,

Xk=∑j=0N−1(vj+1−v‾)e−2πijk/N,fk=kNΔt.X_k=\sum_{j=0}^{N-1}(v_{j+1}-\bar v)\,e^{-2\pi i j k/N},\qquad f_k=\frac{k}{N\Delta t}.

waveform_ac = waveform_voltage - mean(waveform_voltage);  % Remove DC offset.
Y_scope = fft(waveform_ac);
N_scope = length(waveform_ac);
P2_scope = abs(Y_scope / N_scope);
P1_scope = P2_scope(1:floor(N_scope/2)+1);
P1_scope(2:end-1) = 2 * P1_scope(2:end-1);
Fs = 1 / dt;
f_scope = Fs * (0:floor(N_scope/2)) / N_scope;

For this even-length record, the one-sided amplitude is 2|Xk|/N2|X_k|/N for interior positive-frequency bins. DC and Nyquist retain |Xk|/N|X_k|/N. The output is an amplitude spectrum in volts. The script uses the full finite record with no taper or segment averaging, so energy from a component between bin centers can spread into neighboring bins. If adapting the source to an odd image width, double the last positive-frequency bin as well; the supplied indexing leaves it undoubled.

One-sided amplitude spectrum above a bar plot whose heights are ten percent of the corresponding spectral amplitudes.
Both plots share a frequency axis. The lower panel is a fixed sensitivity illustration: each bar is exactly 0.10 times the amplitude above it. Its shape follows directly from that assumption.

Numerical check on the supplied capture

An independent calculation from the original PNG, using the script’s thresholds, weights, calibration, and FFT normalization, gives the following values. The frequency of the largest bin describes this particular reconstructed record. Identifying a physical source for that component would require further measurement.

Quantity Result
Raster and recovered record 738 columns × 271 rows; 738 voltage estimates
Vertical scale 40.0 mV per image row
Horizontal spacing and effective sampling rate 0.54274 µs per column; 1.8425 MHz
Minimum, maximum, and mean voltage −5.30 V, +4.50 V, and −0.497 V
Frequency-bin spacing and image-grid Nyquist frequency 2.4966 kHz and 921.25 kHz
Largest one-sided amplitude bin 0.540 V at 97.37 kHz

What the reconstruction establishes

The image preserves the order of excursions and enough horizontal detail to compare their spectral contributions. The weighted centroid and the sample mean are descriptive statistics of that single record. Trace width, display rendering, missing columns, and the assumed axis limits all affect the estimate. The 40 mV row spacing is a conversion scale; it does not establish voltage accuracy. The 10% bars likewise come from an assigned fraction. The script estimates neither a noise distribution nor a confidence interval from repeated measurements.

A final MATLAB figure superimposes the curve on the input image. In the supplied source, that display assigns the image edges to +6 and −6 V, while the numerical extraction uses +5.4 and −5.4 V. The overlay can help check timing and trace shape. For a voltage-registration check, the image and the reconstructed curve need the same edge calibration.

Reproduce the example

Place the original capture and the MATLAB script in the same MATLAB working folder. Save any active workspace variables first: the script opens with clear all. Run WaveFormReconstruction. It opens figures for the original and masked image, the voltage record, the spectrum and its fractional bars, and the overlay. The time, voltage, frequency, and amplitude arrays remain in the workspace as time_axis, waveform_voltage, f_scope, and P1_scope.

Read the complete MATLAB source
clear all
clc

%% Image Processing and Yellow Region Extraction

% 1. Read the image and convert it to HSV.
A = imread('tek00264.png');       % Read the oscilloscope screenshot.
hsvImage = rgb2hsv(A);            % Convert from RGB to HSV.

% 2. Define HSV thresholds for the yellow color.
hueMin = 0.15;          % Minimum hue threshold for yellow.
hueMax = 0.17;          % Maximum hue threshold for yellow.
saturationMin = 0.4;    % Minimum saturation threshold.
saturationMax = 1.0;    % Maximum saturation threshold.
valueMin = 0.4;         % Minimum brightness threshold.
valueMax = 1.0;         % Maximum brightness threshold.

% 3. Create a binary mask isolating the yellow regions.
colorMask = (hsvImage(:,:,1) >= hueMin) & (hsvImage(:,:,1) <= hueMax) & ...
            (hsvImage(:,:,2) >= saturationMin) & (hsvImage(:,:,2) <= saturationMax) & ...
            (hsvImage(:,:,3) >= valueMin) & (hsvImage(:,:,3) <= valueMax);

%% Connect Gaps Along X- and Y-Axis in the Mask

filledMaskX = colorMask;   % Start with the original mask.
maxGap = 3;                % Maximum gap length (in pixels) to fill.

% ----- Horizontal (Row-wise) Gap Filling -----
for row = 1:size(filledMaskX, 1)
    currentRow = filledMaskX(row, :);
    idx = find(currentRow);  
    if isempty(idx)
        continue;
    end
    for k = 1:length(idx)-1
        gap = idx(k+1) - idx(k) - 1;
        if gap > 0 && gap <= maxGap
            filledMaskX(row, idx(k)+1:idx(k+1)-1) = 1;
        end
    end
end

% ----- Vertical (Column-wise) Gap Filling -----
filledMaskXY = filledMaskX;
for col = 1:size(filledMaskXY, 2)
    currentCol = filledMaskXY(:, col);
    idx = find(currentCol);
    if isempty(idx)
        continue;
    end
    for k = 1:length(idx)-1
        gap = idx(k+1) - idx(k) - 1;
        if gap > 0 && gap <= maxGap
            filledMaskXY(idx(k)+1:idx(k+1)-1, col) = 1;
        end
    end
end

% 4. Overlay the processed mask on the original image.
targetColorImage = bsxfun(@times, A, cast(filledMaskXY, 'like', A));

%% Display the Original and Processed Images
figure;
subplot(1,2,1);
imshow(A);
title('Original Image');

subplot(1,2,2);
imshow(targetColorImage);
title('Yellow Trace with Connected Gaps');

%% Waveform Extraction from the Processed Image
% Calibration:
%   - Horizontal (time) scale: 10 divisions × 40 µs/div = 400 µs total.
%   - Vertical (voltage) scale: Top of image = +5.4 V, bottom = -5.4 V.

[H, W, ~] = size(A);  % H: image height, W: image width.

% Preallocate the vector to hold the vertical (row) position for each column.
waveform_pixels = zeros(W, 1);

% For each column, compute a weighted average of the row indices using the 
% brightness (V-channel) as the weight. Here we emphasize the brightest pixels by 
% raising the weight to an exponent.
for col = 1:W
    rows_on = find(filledMaskXY(:, col));
    if ~isempty(rows_on)
        % Raise the brightness value to an exponent (e.g. 3) to give more emphasis.
        weights = double(hsvImage(rows_on, col, 3)).^3;  
        waveform_pixels(col) = sum(rows_on .* weights) / sum(weights);
    else
        waveform_pixels(col) = NaN;
    end
end

% Fill missing data via linear interpolation.
if any(isnan(waveform_pixels))
    waveform_pixels = fillmissing(waveform_pixels, 'linear');
end

% Convert pixel positions to voltage.
% Mapping: Row 1 (top) = +5.4 V, Row H (bottom) = -5.4 V.
voltage_per_pixel = 10.8 / (H - 1);
waveform_voltage = 5.4 - (waveform_pixels - 1) * voltage_per_pixel;

% Define the time axis based on horizontal calibration.
totalTime = 10 * 40e-6;  % 400 µs.
dt = totalTime / (W - 1);
time_axis = (0:W-1)' * dt;

%% Plot the Derived Oscilloscope Waveform
figure;
plot(time_axis * 1e6, waveform_voltage, 'b-', 'LineWidth', 1.5);
title('Derived Oscilloscope Waveform');
xlabel('Time (\mus)');
ylabel('Voltage (V)');
grid on;

%% Fourier Analysis of the Derived Waveform
waveform_ac = waveform_voltage - mean(waveform_voltage);  % Remove DC offset.
Y_scope = fft(waveform_ac);
N_scope = length(waveform_ac);
P2_scope = abs(Y_scope / N_scope);
P1_scope = P2_scope(1:floor(N_scope/2)+1);
P1_scope(2:end-1) = 2 * P1_scope(2:end-1);
Fs = 1 / dt;
f_scope = Fs * (0:floor(N_scope/2)) / N_scope;

%% Plot the Frequency Spectrum with Errors in a Subplot
% For demonstration, we use a fixed fractional error (10% of the amplitude) for each bin.
err = 0.1 * P1_scope;

% Create a new figure with 2 vertically stacked subplots
figure('Position', [100, 100, 1000, 800]);

% Top subplot: Frequency spectrum
subplot(2,1,1);
plot(f_scope, P1_scope, 'r-', 'LineWidth', 1.5);
title('Single-Sided Amplitude Spectrum of Derived Waveform');
ylabel('|P1(f)|');
grid on;
% Don't show x-label in top subplot to avoid clutter
set(gca, 'XTickLabel', []); % Hide x tick labels

% Bottom subplot: Error bars
subplot(2,1,2);
bar(f_scope, err, 'FaceColor', [0.5 0.5 0.8]);
title('Error Estimates for Each Frequency Bin');
xlabel('Frequency (Hz)');
ylabel('Error Magnitude');
grid on;

% Link x-axes of both subplots so they zoom/pan together
linkaxes(findall(gcf, 'Type', 'axes'), 'x');

% Optional: Adjust x-axis limits if needed to focus on relevant frequency range
% xlim([0, max(f_scope)/4]);  % Uncomment and adjust as needed

%% Superimposed Graph: Derived Waveform Over the Original Image
figure('Position', [100, 100, 1200, 800]);
imshow(A, 'XData', [0, totalTime*1e6], 'YData', [6, -6]);  % Map physical units.
axis on;
set(gca, 'YDir', 'normal');
hold on;
plot(time_axis * 1e6, waveform_voltage, 'r-', 'LineWidth', 2);
xlim([0, totalTime*1e6]);
ylim([-6.5, 6.5]);
set(gca, 'YTick', -6:0.5:6);
xlabel('Time (\mus)');
ylabel('Voltage (V)');
title('Oscilloscope Trace with Derived Waveform Overlay');
set(gca, 'DataAspectRatio', [5 1 1]);
axis normal;
hold off;

Technical areas

MATLAB, Waveform digitization, Numerical interpolation, Fourier analysis, Measurement uncertainty.

← Independent Research & Computational Methods