title: Binary Image Orientation
body: <p>I'm trying to find the orientation of a binary image (where orientation is defined to be the axis of least moment of inertia, i.e. least second moment of area). I'm using Dr. Horn's book (MIT) on Robot Vision <a href="http://people.csail.mit.edu/bkph/courses/papers/RoVis/ch3_BI_geometric.pdf" rel="noreferrer">which can be found here</a> as reference.</p>
  
  <p>Using OpenCV, here is my function, where a, b, and c are the second moments of area as found on page 15 of the pdf above (page 60 of the text):</p>
  
  <pre><code>Point3d findCenterAndOrientation(const Mat&amp; src)
  {
      Moments m = cv::moments(src, true);
      double cen_x = m.m10/m.m00; //Centers are right
      double cen_y = m.m01/m.m00;
  
      double a = m.m20-m.m00*cen_x*cen_x;
      double b = 2*m.m11-m.m00*(cen_x*cen_x+cen_y*cen_y);
      double c = m.m02-m.m00*cen_y*cen_y;
  
      double theta = a==c?0:atan2(b, a-c)/2.0;
  
      return Point3d(cen_x, cen_y, theta);
  }
  </code></pre>
  
  <p>OpenCV calculates the second moments around the origin (0,0) so I have to use the <a href="http://en.wikipedia.org/wiki/Parallel_axis_theorem" rel="noreferrer">Parallel Axis Theorem</a> to move the axis to the center of the shape, mr^2.</p>
  
  <p>The center looks right when I call</p>
  
  <pre><code>Point3d p = findCenterAndOrientation(src);
  rectangle(src, Point(p.x-1,p.y-1), Point(p.x+1, p.y+1), Scalar(0.25), 1);
  </code></pre>
  
  <p>But when I try to draw the axis with lowest moment of inertia, using this function, it looks completely <strong>wrong</strong>:</p>
  
  <pre><code>line(src, (Point(p.x,p.y)-Point(100*cos(p.z), 100*sin(p.z))), (Point(p.x, p.y)+Point(100*cos(p.z), 100*sin(p.z))), Scalar(0.5), 1); 
  </code></pre>
  
  <p>Here are some examples of input and output:</p>
  
  <p><img src="https://i.stack.imgur.com/933uY.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/qWVQq.png" alt="enter image description here"></p>
  
  <p>(I'd expect it to be vertical)</p>
  
  <p><img src="https://i.stack.imgur.com/DwdNb.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/FENau.png" alt="enter image description here"></p>
  
  <p>(I'd expect it to be horizontal)</p>