%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Harris corner Detector
% Please complete this function by yourself.
% You should first use low pass filter to decrease the noise,
% Then start your process to obtain the Harris corner. You'd
% better search local maximum to select the best corner.
% Put the image coordinates of found corner into the matrix D.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D = harrisCorner(I)
%高斯低通滤波滤除噪声
h = fspecial('gaussian',[3 3],2); %产生3*3的高斯窗函数
I = filter2(h,I);
%求梯度Ix、Iy
fx = [-2 -1 0 1 2]; %x方向梯度算子
Ix = filter2(fx,I); %x方向滤波
fy = [-2;-1;0;1;2]; %y方向梯度算子
Iy = filter2(fy,I); %y方向滤波
Ix_2 = Ix .* Ix;
Iy_2 = Iy .* Iy;
Ix_Iy = Ix .* Iy;
h= fspecial('gaussian',[7 7],2); %产生7*7的高斯窗函数
Ix_2 = filter2(h,Ix_2);
Iy_2 = filter2(h,Iy_2);
Ix_Iy = filter2(h,Ix_Iy);
%计算每个像素点的R值,得到D的矩阵
[height,width]=size(I);
R=zeros(height,width);
for i = 1:height
for j = 1:width
M = [Ix_2(i,j) Ix_Iy(i,j);
Ix_Iy(i,j) Iy_2(i,j)];
R(i,j) = det(M)-0.04*(trace(M))^2; %像素(i,j)处的R值,k=0.04
end
end
%逐个像素的R值与阈值比较
Rmax = max(max(R));
threshold = 0.03 * Rmax; %阈值=R最大值*0.03
for i = 1:height
for j = 1:width
if R(i,j)<threshold
R(i,j) = 0;
end
end
end
%只保留一个R值代表角(非极大值抑制)
k = 1;
for i = 2:height-1
for j = 2:width-1
%若(i,j)像素点的R值大于周围各点,则保留该点
if (R(i,j)>R(i-1,j-1))&&(R(i,j)>R(i-1,j))&&(R(i,j)>R(i-1,j+1))&&(R(i,j)>R(i,j-1))&&(R(i,j)>R(i,j+1))&&(R(i,j)>R(i+1,j-1))&&(R(i,j)>R(i+1,j))&&(R(i,j)>R(i+1,j+1))
D(2,k) = i;
D(1,k) = j;
k = k + 1;
end;
end;
end;