C#求點集的最小包圍矩形
阿新 • • 發佈:2020-09-19
C# 求點集的最小包圍矩形,供大家參考,具體內容如下
思路:
1、求點集的中心點
2、將點集繞矩形進行一系列角度的旋轉,並求記錄旋轉點集的包圍矩形的面積和旋轉角度;
3、將面積最小的矩形繞點集中心點旋轉回去。
// 1.尋找多邊形的中心 public XYZ GetCenter(List<XYZ> pts) { double sumx = 0; double sumy = 0; foreach (var p in pts) { sumx = sumx + p.X; sumy = sumy + p.Y; } var pt = new XYZ(sumx/pts.Count(),sumy/pts.Count(),0); return pt; } // 2.旋轉多邊形,針對每個點實現繞中心點旋轉 public XYZ RotatePt(XYZ inpt,XYZ centerPt,double theta) { double ix = inpt.X; double iy = inpt.Y; double cx = centerPt.X; double cy = centerPt.Y; double Q = theta / 180 * 3.1415926; //角度 double ox,oy; ox = (ix - cx) * Math.Cos(Q) - (iy - cy) * Math.Sin(Q) + cx; //旋轉公式 oy = (ix - cx) * Math.Sin(Q) + (iy - cy) * Math.Cos(Q) + cy; var outpt = new XYZ(ox,oy,0); return outpt; } // 3.多邊形旋轉後求簡單外接矩形 public List<XYZ> GetRect(List<XYZ> inpts) { var outpts =new List<XYZ>(); int size = inpts.Count(); if (size == 0) return null; else { var tempx = new List<double>(); var tempy = new List<double>(); for (int i = 0; i < size; i++) { tempx.Add(inpts[i].X); tempy.Add(inpts[i].Y); } XYZ endpoint0 = new XYZ(tempx.Min(),tempy.Max(),0); XYZ endpoint1 = new XYZ(tempx.Max(),0); XYZ endpoint2 = new XYZ(tempx.Max(),tempy.Min(),0); XYZ endpoint3 = new XYZ(tempx.Min(),0); outpts.Add(endpoint0); outpts.Add(endpoint1); outpts.Add(endpoint2); outpts.Add(endpoint3); return outpts; } } // 4.儲存每個旋轉角度下多邊形的外接矩形,記錄外接矩形的頂點座標、面積和此時多邊形的旋轉角度 public class RectData { public List<XYZ> boundary { get;set;} public XYZ center { get; set; } public double theta { get; set; } public double area { get; set; } } public RectData GetRotateRectDatas(List<XYZ> inpts,double theta) { XYZ center = GetCenter(inpts); var tempvertices = new List<XYZ>(); for (int i=0; i<inpts.Count();i++) { XYZ temp = RotatePt(inpts[i],center,theta); tempvertices.Add(temp); } List<XYZ> vertices = GetRect(tempvertices); double deltaX,deltaY; //求每個外接矩形的面積 deltaX = vertices[0].X - vertices[2].X; deltaY = vertices[0].Y - vertices[2].Y; var polygen = new RectData { area=Math.Abs(deltaY * deltaX),center= center,theta = theta,boundary= vertices }; return polygen; } //獲取所有新的矩形 public List<RectData> GetAllNewRectDatas(List<XYZ> inpts) { var polygens =new List<RectData>(); for (int theta = 0; theta <= 90;) { polygens.Add(GetRotateRectDatas(inpts,theta)); theta = theta + 5; } return polygens; } //獲取新的矩形 public RectData GetMinAreaRect(List<RectData> polygons) { double minarea = 100000000; int N =0; for ( int i=0; i< polygons.Count(); i++) { if (minarea > polygons[i].area) { minarea = polygons[i].area; N = i; } } var polygon = new RectData(); polygon = polygons[N]; //旋轉到最小面積的方向 XYZ centerPt = GetCenter(polygon.boundary); var boundary = new List<XYZ>(); foreach(var bound in polygon.boundary) { XYZ pt = RotatePt(bound,polygon.center,-polygon.theta); boundary.Add(pt); } var outpolygon = new RectData { center= polygon.center,area = polygon.area,theta = polygon.theta,boundary = boundary }; return outpolygon; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。