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

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

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;
  }
}

你可能感兴趣的:(小功能)