%% Initialize Video Reader and Writer
videoFile = 'speed4_v5.mp4'; % Change this to your video file
videoReader = VideoReader(videoFile);
videoWriter = VideoWriter('filtered_video.avi', 'Uncompressed AVI');
open(videoWriter);
%% Define HSV Thresholds for the Green Laser
hueRange = [0.25, 0.40]; % Adjust these values
satRange = [0.10, 1.00]; % Adjust these values
valRange = [0.20, 1.00]; % Adjust these values
%% Initialize FFT Analysis Variables
fftResults = []; % Store FFT results for each frame
frameCount = 0; % Count the number of frames processed
%% Process Video Frames
while hasFrame(videoReader)
frame = readFrame(videoReader);
frameCount = frameCount + 1;
code
% Crop the frame to the 53%-93% length of the image horizontally
[height, width, ~] = size(frame);
cropStartWidth = floor(width * 0.60) + 1;
cropEndWidth = floor(width * 0.90);
% Crop the frame to the upper 30% vertically
cropStartHeight = 1;
cropEndHeight = floor(height * 0.30);
% Apply both horizontal and vertical cropping
croppedFrame = frame(cropStartHeight:cropEndHeight, cropStartWidth:cropEndWidth, :);
% Convert the cropped image from RGB to HSV
hsvImage = rgb2hsv(croppedFrame);
% Create a binary mask for the green laser
hueMask = (hsvImage(:,:,1) >= hueRange(1)) & (hsvImage(:,:,1) <= hueRange(2));
satMask = (hsvImage(:,:,2) >= satRange(1)) & (hsvImage(:,:,2) <= satRange(2));
valMask = (hsvImage(:,:,3) >= valRange(1)) & (hsvImage(:,:,3) <= valRange(2));
laserMask = uint8(hueMask & satMask & valMask);
% Convert the masked frame to black and white
bwFrame = imbinarize(laserMask);
% Convert logical array to uint8
bwFrameUint8 = uint8(bwFrame) * 255;
% Write frame to video
writeVideo(videoWriter, bwFrameUint8);
% Display the result
imshow(bwFrameUint8);
drawnow;
%% FFT Analysis
% Extract the line and compute the FFT
lineProfile = max(bwFrame, [], 1);
Y = fft(double(lineProfile));
fftResults(:, frameCount) = abs(Y(1:floor(end/2)));
end
%% Post-Processing of FFT Results
averageFFT = mean(fftResults, 2);
Fs = videoReader.FrameRate;
N = size(fftResults, 1);
fRes = Fs / N;
f = (0:N/2-1)*fRes;
%% Calculate Standard Deviations for Each Frequency
frequencyStdDevs = std(fftResults, 0, 2); % Standard deviation across columns (frames)
%% Find and Display Top Peaks
[pks, locs] = findpeaks(averageFFT(1:floor(N/2)), 'SortStr', 'descend', 'NPeaks', 4);
peakFreqs = (locs - 1) * fRes;
topPeakFreqsRounded = round(peakFreqs, 3);
%% Initialize the Results Table with Measured Frequencies and Their Standard Deviations
resultsTable = table(topPeakFreqsRounded, zeros(4,1), zeros(4,1), frequencyStdDevs(locs), 'VariableNames', {'Measured', 'Theoretical', 'Difference', 'StandardDeviation'});
%% Clean Up
close(videoWriter);
% Known parameters
Lx = 0.563; % Length of the tank in meters
Ly = 0.358; % Width of the tank in meters
g = 9.84; % Acceleration due to gravity in m/s^2
d = 0.07; % Depth of water in meters
% Calculate theoretical frequencies for a range of modes
maxMode = 10; % Define the maximum mode number you want to consider
theoreticalFreqs = zeros(maxMode, maxMode);
for m = 1:maxMode
for n = 1:maxMode
% The dispersion relation for surface waves in a rectangular tank
theoreticalFreqs(m, n) = (1/(2pi)) * sqrt((gd) * ((mpi/Lx)^2 + (npi/Ly)^2) * tanh((mpid)/Lx) * tanh((npid)/Ly));
end
end
% Flatten the matrix of theoretical frequencies and sort them
theoreticalFreqs = sort(theoreticalFreqs(:));
% Find the closest theoretical frequency for each FFT-derived frequency
for i = 1:length(resultsTable.Measured)
currentFreq = resultsTable.Measured(i);
[minDiff, idx] = min(abs(theoreticalFreqs - currentFreq));
closestTheoreticalFreq = theoreticalFreqs(idx);
code
% Update the results table with the theoretical frequency and the difference
resultsTable.Theoretical(i) = closestTheoreticalFreq;
resultsTable.Difference(i) = abs(currentFreq - closestTheoreticalFreq);
end
%% Calculate the sum of the squares of the FFT results for the top peaks
powerSpectrum = averageFFT(locs).^2;
totalPeakPower = sum(powerSpectrum);
% Calculate the percentage contribution of each peak to the total peak power
FreqPercentage = (powerSpectrum / totalPeakPower) * 100;
%% Update the Results Table with Percentage Contributions
resultsTable.Percentage = FreqPercentage;
%% Function to Calculate Wavelength Using an Iterative Approach
function lambda = calculateWavelength(g, d, T)
lambdaGuess = sqrt(gT^2/(2pi));
equationToSolve = @(lambda) lambda - (g/(2pi))T^2tanh((2pi*d)/lambda);
lambda = fzero(equationToSolve, lambdaGuess);
end
%% Function to Calculate Wave Speed
function c = calculateWaveSpeed(g, lambda, d)
c = sqrt((glambda)/(2pi)tanh((2pi*d)/lambda));
end
%% Calculate Wavelength and Speed for Each Frequency
wavelengths = zeros(length(topPeakFreqsRounded), 1);
speeds = zeros(length(topPeakFreqsRounded), 1);
for i = 1:length(topPeakFreqsRounded)
T = 1 / topPeakFreqsRounded(i); % Period of the wave
% Initial guess for lambda (could be any reasonable value)
lambdaGuess = sqrt(gT^2/(2pi));
% Define the equation to solve
equationToSolve = @(lambda) lambda - (g/(2pi))T^2tanh((2pid)/lambda);
% Solve for lambda using the initial guess
lambda = fzero(equationToSolve, lambdaGuess);
% Ensure the wavelength is positive
lambda = abs(lambda);
Wavelength(i) = lambda;
% Calculate the speed using the wavelength
Speed(i) = sqrt((glambda)/(2pi)tanh((2pid)/lambda));
end
%% Initialize the Results Table with Measured Frequencies and Their Standard Deviations
% Round the numerical data to two decimal places
resultsTable.Measured = round(resultsTable.Measured, 2);
resultsTable.StandardDeviation = round(resultsTable.StandardDeviation, 2);
resultsTable.Theoretical = round(resultsTable.Theoretical, 2);
resultsTable.Difference = round(resultsTable.Difference, 2);
resultsTable.Wavelength = round(Wavelength, 2);
resultsTable.Speed = round(Speed, 2);
resultsTable.FreqPercentage = round(FreqPercentage, 0);
% Create the results table with columns in the desired order
resultsTable = table(Measured, StandardDeviation, Theoretical, Difference, Wavelength, Speed, FreqPercentage, ...
'VariableNames', {'Measured', 'StdDev', 'Theoretical', 'Difference', 'Wavelength', 'Speed', 'Freq%'});
%% Display the Updated Results Table
disp(resultsTable);
% Calculate the frequency resolution
duration = 47.3; % Duration of the video in seconds
frameRate = 30; % Frame rate of the video in frames per second
frequencyResolution = 1 / duration;
nyquistFrequency = frameRate / 2;
% Display FFT Error and Nyquist Frequency below the table
fprintf('\nFFT Error (Frequency Resolution): %.2f Hz\n', frequencyResolution);
fprintf('Nyquist Frequency: %.1f Hz\n', nyquistFrequency);
% Plot the measured and theoretical frequencies with error bars
figure;
hold on;
errorbar(1:length(resultsTable.Measured), resultsTable.Measured, resultsTable.('Std Dev'), 'o', 'DisplayName', 'Measured Frequencies');
plot(1:length(resultsTable.Theoretical), resultsTable.Theoretical, 'x', 'DisplayName', 'Theoretical Frequencies');
% Move the legend to the upper left corner
legend('Location', 'northwest');
% Define the text for the note
samplingRateText = 'Sampling rate: 30.0 Hz';
nyquistText = 'Nyquist Frequency: 15.0 Hz'; % Nyquist frequency is half the sampling rate
durationText = 'Duration: 47.3 s';
fftResText = 'FFT Resolution: 0.02 Hz'; % Rounded to two decimal places
% Add the note to the lower right of the plot
text('Units', 'normalized', 'Position', [0.95 0.05], 'String', {samplingRateText, nyquistText, durationText, fftResText}, ...
'HorizontalAlignment', 'right', 'VerticalAlignment', 'bottom', 'FontSize', 8, 'EdgeColor', 'none');
xlabel('Harmonic Order');
ylabel('Frequency (Hz)');
title('Measured vs Theoretical Frequencies with Error Bars');
% Adjust the x-axis to improve visibility of the first frequency
xlim([0.5, length(resultsTable.Measured) + 0.5]);
xticks(1:length(resultsTable.Measured)); % Set x-axis ticks to integer values
hold off;
Assistant
Here are a few ways to improve the analysis and visualization:
Calculate theoretical frequencies for more modes (higher m and n values) to enable matching of more measured peaks.
Plot the FFT power spectrum to visualize all the peaks. Add vertical lines to indicate the theoretical frequencies.
Include units (Hz) on the frequency axes.
Use different markers for measured vs theoretical points. For example:
Add error bars to the measured frequencies using the standard deviation values.
Annotate key parameters on the plot itself to provide context:
Sampling rate
Nyquist frequency
Duration of data
FFT frequency resolution
Calculate and display the wavelength and wave velocity for each measured frequency using the dispersion relation.
Quantify goodness of fit between measured and theoretical freqs using metrics like RMSE.
For better visibility of lower frequencies, adjust the x-axis limits to exclude unnecessary space on right side of plot.
Let me know if any part needs more clarification! Adding these improvements will really polish the analysis and help convey key insights into the accuracy of the measurements.