Minimum Area Rectangle in CSharp

From Emgu CV: OpenCV in .NET (C#, VB, C++ and more)
Revision as of 13:38, 22 October 2020 by Canming (talk | contribs) (Updated sample code to Emgu CV v4.4)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, 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