Ellipse Fitting - An Efficient Implementation
Jump to navigation
Jump to search
The following is a very efficient way to fit an Ellipse on an array of PointF.
This function is part of the Emgu.CV.PointCollection class.
/// <summary>
/// Fit an ellipse to the points collection
/// </summary>
/// <param name="points">The points to be fitted</param>
/// <returns>An ellipse</returns>
public static Ellipse EllipseLeastSquareFitting(PointF[] points)
{
IntPtr seq = Marshal.AllocHGlobal(StructSize.MCvSeq);
IntPtr block = Marshal.AllocHGlobal(StructSize.MCvSeqBlock);
GCHandle handle = GCHandle.Alloc(points, GCHandleType.Pinned);
CvInvoke.cvMakeSeqHeaderForArray(
CvInvoke.CV_MAKETYPE((int)CvEnum.MAT_DEPTH.CV_32F, 2),
StructSize.MCvSeq,
StructSize.PointF,
handle.AddrOfPinnedObject(),
points.Length,
seq,
block);
Ellipse e = new Ellipse(CvInvoke.cvFitEllipse2(seq));
handle.Free();
Marshal.FreeHGlobal(seq);
Marshal.FreeHGlobal(block);
return e;
}