求点集的最小面积外接矩形

求点集的最小面积外接矩形

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;
  }
}
发布了50 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/random_repick/article/details/103574844