Combined Livescript
% Load and Crop Video
video = VideoReader('video.mp4');
numFrames = video.NumberOfFrames;
frameHeight = video.Height;
frameWidth = video.Width;
% Crop the video to focus on the laser line
cropX1 = 100;
cropX2 = 300;
cropY1 = 100;
cropY2 = 200;
% Preallocate arrays for FFT data and frequency values
fftData = zeros(1, numFrames);
frequencies = zeros(1, numFrames);
% Calculate FFT for each frame
for i = 1:numFrames
frame = readFrame(video);
croppedFrame = frame(cropY1:cropY2, cropX1:cropX2);
fftData(i) = abs(fft(croppedFrame));
frequencies(i) = i * video.FrameRate / numFrames;
end
% Find the main 10 peaks in the FFT data
[peaks, locs] = findpeaks(fftData, 'NPeaks', 10);
% Calculate the standard deviation of each frequency
stdDevs = zeros(1, 10);
for i = 1:10
stdDevs(i) = std(fftData(locs(i)-10:locs(i)+10));
end
% Calculate the relative percentage of each frequency
relPercentages = peaks ./ sum(peaks) * 100;
% Perform least squares fit on the frequency data
fitData = polyfit(frequencies(locs), locs, 1);
% Calculate the errors in the fit
errors = zeros(1, numFrames);
for i = 1:numFrames
errors(i) = abs(fitData(1) * frequencies(i) + fitData(2) - locs(i));
end
% Plot the results
figure;
% Plot the FFT data
subplot(2, 1, 1);
plot(frequencies, fftData);
title('FFT Data');
xlabel('Frequency (Hz)');
ylabel('Amplitude');
% Plot the least squares fit and errors
subplot(2, 1, 2);
errorbar(frequencies(locs), locs, errors, 'o');
hold on;
plot(frequencies, fitData(1) * frequencies + fitData(2), 'r-');
title('Least Squares Fit and Errors');
xlabel('Frequency (Hz)');
ylabel('Peak Location');
legend('Data', 'Linear Fit');
Explanation:
-
Load and Crop Video: We start by loading the video using VideoReader and defining the cropping parameters.
-
Calculate FFT for Each Frame: We loop through each frame, crop it to focus on the laser line, and calculate its FFT data.
-
Find Main 10 Peaks: We find the top 10 peaks in the FFT data.
-
Calculate Standard Deviation and Relative Percentage: We calculate the standard deviation of each peak's frequency and its relative percentage.
-
Perform Least Squares Fit: We perform a linear least squares fit on the frequency data to find the best-fit line.
-
Calculate Errors: We calculate the errors in the fit for each frequency.
-
Plot the Results: Finally, we plot the FFT data, the least squares fit, and the errors.
This combined livescript performs all the necessary steps to analyze the video, calculate the FFT data, find the main peaks, perform a linear regression, and visualize the results. It's a more streamlined and efficient way to perform the analysis.