if size(im2,1)==0
im2=zeros(size(im1));
end
% Horn-Schunck original method
fx = conv2(im1,0.25* [-1 1; -1 1],'same') + conv2(im2, 0.25*[-1 1; -1 1],'same');
fy = conv2(im1, 0.25*[-1 -1; 1 1], 'same') + conv2(im2, 0.25*[-1 -1; 1 1], 'same');
ft = conv2(im1, 0.25*ones(2),'same') + conv2(im2, -0.25*ones(2),'same');
function G=gaussFilter(segma,kSize)
if nargin<1
segma=1;
end
if nargin<2
kSize=2*(segma*3);
end
x=-(kSize/2):(1+1/kSize):(kSize/2);
G=(1/(sqrt(2*pi)*segma)) * exp (-(x.^2)/(2*segma^2));
function [u, v] = HS(im1, im2, alpha, ite, uInitial, vInitial, displayFlow, displayImg)
%% Default parameters
if nargin<1 || nargin<2
im1=imread('yos7.png');
im2=imread('yos8.png');
%im1 = im1(:,:,2);
%im2 = im2(:,:,2);
end
if nargin<3
alpha=1;
end
if nargin<4
ite=400;
end
if nargin<5 || nargin<6
uInitial = zeros(size(im1(:,:,1)));
vInitial = zeros(size(im2(:,:,1)));
elseif size(uInitial,1) ==0 || size(vInitial,1)==0
uInitial = zeros(size(im1(:,:,1)));
vInitial = zeros(size(im2(:,:,1)));
end
if nargin<7
displayFlow=1;
end
if nargin<8
displayImg=im1;
end
%% Convert images to grayscale
if size(size(im1),2)==3
im1=rgb2gray(im1);
end
if size(size(im2),2)==3
im2=rgb2gray(im2);
end
im1=double(im1);
im2=double(im2);
im1=smoothImg(im1,1);
im2=smoothImg(im2,1);
%tic;
%%
% Set initial value for the flow vectors
u = uInitial;
v = vInitial;
% Estimate spatiotemporal derivatives
[fx, fy, ft] = computeDerivatives(im1, im2);
% Averaging kernel
kernel_1=[1/12 1/6 1/12;1/6 0 1/6;1/12 1/6 1/12];
% Iterations
for i=1:ite
% Compute local averages of the flow vectors
uAvg=conv2(u,kernel_1,'same');
vAvg=conv2(v,kernel_1,'same');
% Compute flow vectors constrained by its local average and the optical flow constraints
u= uAvg - ( fx .* ( ( fx .* uAvg ) + ( fy .* vAvg ) + ft ) ) ./ ( alpha^2 + fx.^2 + fy.^2);
v= vAvg - ( fy .* ( ( fx .* uAvg ) + ( fy .* vAvg ) + ft ) ) ./ ( alpha^2 + fx.^2 + fy.^2);
end
u(isnan(u))=0;
v(isnan(v))=0;
%% Plotting
if displayFlow==1
plotFlow(u, v, displayImg, 5, 5);
end
function plotFlow(u, v, imgOriginal, rSize, scale)
figure();
%if nargin>2
% if sum(sum(imgOriginal))~=0
% imshow(imgOriginal,[0 255]);
% hold on;
% end
%end
if nargin<4
rSize=5;
end
if nargin<5
scale=3;
end
% Enhance the quiver plot visually by showing one vector per region
%floor(X) 向下取整,即取不大于X的最大整数
%floor(X) rounds the elements of X to the nearest integers towards minus infinity
for i=1:size(u,1)
for j=1:size(u,2)
if floor(i/rSize)~=i/rSize || floor(j/rSize)~=j/rSize
u(i,j)=0;
v(i,j)=0;
end
end
end
quiver(u, v, scale, 'color', 'r', 'linewidth', 3);
set(gca,'YDir','reverse');
function smoothedImg=smoothImg(img,segma)
if nargin<2
segma=1;
end
G=gaussFilter(segma);
smoothedImg=conv2(img,G,'same');
smoothedImg=conv2(smoothedImg,G','same');