kalfasyan

Untitled

Feb 29th, 2016
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.03 KB | None | 0 0
  1. function A = EllipseDirectFit(XY,pic);
  2. %
  3. %  Direct ellipse fit, proposed in article
  4. %    A. W. Fitzgibbon, M. Pilu, R. B. Fisher
  5. %     "Direct Least Squares Fitting of Ellipses"
  6. %     IEEE Trans. PAMI, Vol. 21, pages 476-480 (1999)
  7. %
  8. %  Our code is based on a numerically stable version
  9. %  of this fit published by R. Halir and J. Flusser
  10. %
  11. %     Input:  XY(n,2) is the array of coordinates of n points x(i)=XY(i,1), y(i)=XY(i,2)
  12. %
  13. %     Output: A = [a b c d e f]' is the vector of algebraic
  14. %             parameters of the fitting ellipse:
  15. %             ax^2 + bxy + cy^2 +dx + ey + f = 0
  16. %             the vector A is normed, so that ||A||=1
  17. %
  18. %  This is a fast non-iterative ellipse fit.
  19. %
  20. %  It returns ellipses only, even if points are
  21. %  better approximated by a hyperbola.
  22. %  It is somewhat biased toward smaller ellipses.
  23. %
  24. centroid = mean(XY);   % the centroid of the data set
  25.  
  26. D1 = [(XY(:,1)-centroid(1)).^2, (XY(:,1)-centroid(1)).*(XY(:,2)-centroid(2)),...
  27.       (XY(:,2)-centroid(2)).^2];
  28. D2 = [XY(:,1)-centroid(1), XY(:,2)-centroid(2), ones(size(XY,1),1)];
  29. S1 = D1'*D1;
  30. S2 = D1'*D2;
  31. S3 = D2'*D2;
  32. T = -inv(S3)*S2';
  33. M = S1 + S2*T;
  34. M = [M(3,:)./2; -M(2,:); M(1,:)./2];
  35. [evec,eval] = eig(M);
  36. cond = 4*evec(1,:).*evec(3,:)-evec(2,:).^2;
  37. A1 = evec(:,find(cond>0));
  38. A = [A1; T*A1];
  39. A4 = A(4)-2*A(1)*centroid(1)-A(2)*centroid(2);
  40. A5 = A(5)-2*A(3)*centroid(2)-A(2)*centroid(1);
  41. A6 = A(6)+A(1)*centroid(1)^2+A(3)*centroid(2)^2+...
  42.      A(2)*centroid(1)*centroid(2)-A(4)*centroid(1)-A(5)*centroid(2);
  43. A(4) = A4;  A(5) = A5;  A(6) = A6;
  44. %abs(A(1))*2;
  45. A = A/norm(A);
  46. 2*abs(A(1)) % kalfasyan
  47.  
  48. hold on
  49.  
  50. %Convert the A to str
  51. a = num2str(A(1));
  52. b = num2str(A(2));
  53. c = num2str(A(3));
  54. d = num2str(A(4));
  55. e = num2str(A(5));
  56. f = num2str(A(6));
  57.  
  58. %Equation
  59. eqt= ['(',a, ')*x^2 + (',b,')*x*y + (',c,')*y^2 + (',d,')*x+ (',e,')*y + (',f,')'];
  60. xmin=0.7*min(XY(:,1));
  61. xmax=1.3*max(XY(:,2));
  62. imshow(pic)
  63. hold on
  64. ezplot(eqt,[xmin,xmax])
  65. %scatter(XY(:,1),XY(:,2), 'g') % kalfasyan
  66. hold off
  67. end  %  EllipseDirectFit
Add Comment
Please, Sign In to add comment