求點集的最小面積外接矩形

求點集的最小面積外接矩形

void Rotate(float& x, float& y, float angle) {
  float a = x * cos(angle) - y * sin(angle);
  float b = x * sin(angle) + y * cos(angle);
  x = a;
  y = b;
}

void Rect(const vector<float>& x,
          const vector<float>& y,
          float& length,
          float& width) {
  float area = 1024;
  int size = x.size();
  // rotate 0~90 degree
  for (int i = 0; i < 91; ++i) {
    float tmpx = x[0], tmpy = y[0];
    Rotate(tmpx, tmpy, i);
    float xl = tmpx, xr = tmpx, yt = tmpy, yb = tmpy;
    // traverse all points
    for (int j = 1; j < size; ++j) {
      tmpx = x[j];
      tmpy = y[j];
      Rotate(tmpx, tmpy, i);
      if (tmpx < xl)
        xl = tmpx;
      if (tmpx > xr)
        xr = tmpx;
      if (tmpy < yb)
        yb = tmpy;
      if (tmpy > yt)
        yt = tmpy;
    }
    float xx = xr - xl, yy = yt - yb;
    if (area > xx * yy) {
      area = xx * yy;
      length = xx;
      width = yy;
    }
  }
  //
  if (length < width) {
    float tmp = length;
    length = width;
    width = tmp;
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章