myfirstgitrepo/heartrate/main.m

98 lines
1.9 KiB
Matlab

%set variable
fps = 15;
windowDuration = 30;
windowShift = 1;
roi = [310 126 114 54];
imgDirectory = 'images';
%global
redChannel = [];
greenChannel = [];
blueChannel = [];
%list the images
listImg = dir([imgDirectory '/*.png']);
for l_img=1:windowDuration*fps
% load the current image
image_orginal = imread([imgDirectory '/' listImg(l_img).name]);
image_face = imcrop(image_orginal,roi);
%spatial average for r, g, b channels
[r g b]=imsplit(image_face);
r_mean = mean2(r);
g_mean = mean2(g);
b_mean = mean2(b);
% store the current "average" pixel in global arrays
redChannel = [redChannel r_mean];
greenChannel = [greenChannel g_mean];
blueChannel = [blueChannel b_mean];
end
% estimate temporal average and standard deviation
greenChannel_avg = mean(greenChannel);
greenChannel_std = std(greenChannel);
%normalization
for i = 1:450
greenChannel_normal(i) = (greenChannel(i)-greenChannel_avg);
end
%Fast Fourier transform (fft) of Green Channel
greenChannel_fft = fft(greenChannel_normal);
%power spectrum P1
L = length(greenChannel_normal);
P2 = abs(greenChannel_fft/L);
P1 = P2(1:L/2+1);
P1(2:end-1)=2*P1(2:end-1);
f = 15*(0:(L/2))/L;
P1 = fftshift(P1);
plot(f,P1);
title("Power Spectrum")
xlabel("frequency (Hz)")
ylabel("Power Spectrum")
%peak - compute the freq vector
[m n]=size(P1);
x = 1:n;
y= 1:m;
[X Y]=meshgrid(x, y);
X = X - floor(n/2)-1;
Y = Y - floor(m/2)-1;
f = sqrt(X.^2 + Y.^2);
%peak - find the peak in range
indices = (f>=0.75)&(f<=4);
[peaks locations] = findpeaks(P1(indices), 'SortStr','descend');
location = locations(1);
peak_frequency = f(indices);
peak_frequency = peak_frequency(location);
heartrate = peak_frequency.*60;
disp(['Heart rate: ', num2str(heartrate), ' bpm']);
%plotting RGB
figure(2)
subplot(2,2,1);
plot(redChannel,'r');
title('Red Channel');
subplot(2,2,2);
plot(greenChannel,'g');
title('Green Channel');
subplot(2,2,3);
plot(blueChannel,'b');
title('Blue Channel');