Minimum Area Rectangle in CSharp

From Emgu CV: OpenCV in .NET (C#, VB, C++ and more)
Jump to navigation Jump to search

System Requirement

Component Requirement
Emgu CV Version 4.4.0
Operation System Cross Platform

Source Code

#region generate random points
System.Random r = new Random();
int sampleCount = 100;
Ellipse modelEllipse = new Ellipse(new PointF(200, 200), new SizeF(90, 60), -60);
PointF[] pts = PointCollection.GeneratePointCloud(modelEllipse, sampleCount);
#endregion

Stopwatch watch = Stopwatch.StartNew();
RotatedRect box = CvInvoke.MinAreaRect(pts);
watch.Stop();

#region draw the points and the box
Mat img = new Mat(400, 400, DepthType.Cv8U, 3);
img.SetTo(new MCvScalar(255, 255, 255));

Point[] vertices = Array.ConvertAll(box.GetVertices(), Point.Round);

CvInvoke.Polylines(img, vertices, true, new MCvScalar(0, 0, 255), 1);
foreach (PointF p in pts)
    CvInvoke.Circle(img, Point.Round(p), 2, new MCvScalar(0, 255, 0), 1);
#endregion

Emgu.CV.UI.ImageViewer.Show(img, String.Format("Time used: {0} milliseconds", watch.ElapsedMilliseconds));

Result

MinimumAreaRectangleExample.png