一次图像处理的作业:
用最小二乘法拟合散点集所组成的椭圆:
function ellipse = fitellipse(X,Y) if nargin == 0 % Read the original picture x_ori = []; y_ori = []; f=imread('test2.png'); % Convert the picture to gray scale f = rgb2gray(f); [m,n]=size(f); for i=1:m for j=1:n if(f(i,j)>200) x_ori=[x_ori,j]; y_ori=[y_ori,i]; end end end % Plot clf plot(x_ori,y_ori,'o');set(gca,'YDir','reverse');axis([1,n,1,m]) figure(gcf) params = fitellipse(x_ori,y_ori); Returned = round(params.*[1 1 1 1 180]) % Show the ellipse t = linspace(0,pi*2); x = params(3) * cos(t); y = params(4) * sin(t); x_ori = x*cos(params(5))-y*sin(params(5)) + params(1); y_ori = x*sin(params(5))+y*cos(params(5)) + params(2); hold on plot(x_ori,y_ori,'r-') return end % Normalize the matrix mx = mean(X); my = mean(Y); sx = (max(X)-min(X))/2; sy = (max(Y)-min(Y))/2; x = (X-mx)/sx; y = (Y-my)/sy; x = x(:); y = y(:); % Create matrix D D = [ x.*x x.*y y.*y x y ones(size(x)) ]; % Create matrix S = Trans(D)*D S = D'*D; % Scatter coefficient matrix C(6,6) = 0; C(1,3) = -2; C(2,2) = 1; C(3,1) = -2; % Calculate eigenvalue [gevec, geval] = eig(S,C); % Find the eigenValue invValue = find(real(diag(geval)) < 1e-8 & ~isinf(diag(geval))); % Calculate the EigenVector A = real(gevec(:,invValue)); % Revert the normalization par = [ A(1)*sy*sy, ... A(2)*sx*sy, ... A(3)*sx*sx, ... -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ... -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ... A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ... - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ... + A(6)*sx*sx*sy*sy ... ]'; % Calculate the parameters of the ellipse thetarad = 0.5*atan2(par(2),par(1) - par(3)); a=par(1)/par(6); b=par(2)/par(6); c=par(3)/par(6); d=par(4)/par(6); e=par(5)/par(6); f=1; valueTemp = 4*a*c-b*b; xCentre = (b*e-2*c*d)/valueTemp; yCentre = (b*d-2*a*e)/valueTemp; temp1 = 2*(a*xCentre*xCentre + c*yCentre*yCentre + b*xCentre*yCentre - 1); temp2 = sqrt((a-c)*(a-c) + b*b); Ru = sqrt(temp1/(a+c-temp2)); Rv = sqrt(temp1/(a+c+temp2)); ellipse = [xCentre, yCentre, Ru, Rv, thetarad];