Tag Archives: height

Open CV : Determine angle of RotatedRect / minAreaRect

I was working on an OpenCV project which needed to determine Angle of a RotatedRect extracted from a contour using minAreaRect() function. Unknown of the weird and intelligent logic behind the “angle” property of the RotatedRect, my results weren’t as expected. It took me a while to understand whats going on with the determined RotatedRect properties.

Unable to finding quick info about the properties of RotatedRect in web search results. I decided to inspect it myself … and here are the results.

  1. The lowest point in a rectangle is 0th vertex, and 1st, 2nd, 3rd vertices follow clockwise.
  2. Height is distance between 0th & 1st  (or 2nd & 3rd) vertices. And width is distance between 1st  & 2nd (or 0th & 3rd) vertices.
  3. Angle is calculated from the horizontal to the first edge of rectangle, counter clockwise.
  4. Angle varies between -0 to -90 (I am unsure, what is the decisive factor of -0 or -90)

 

result_barleft result_barright result_brickrightresult_brickleftresult_barSqrHorresult_barSqrVerresult_barHorresult_barVer

For OpenCV a contour is just a pattern, it doesn’t understand how much it is rotated in real life. OpenCV will get the minAreaRect and see it only as a rectangle which rotated from the horizontal (upto 90 degrees). if your object is rotated more than (-)90 degrees, next edge of the rectangle becomes the leading edge and is used to calculate the angle from the horizontal (between -0 to -90). So you have to take care of this in your code to figure out how much the contour has rotated in real life i.e. from 0 to 359 degrees.

Tip: if your contour is of fixed shape, rotating it will make the Height & Width of the RotatedRect flip on every 90 degrees boundary.

The below code snippet can give you the rotation angle from 0 to -180.

double myContourAngle = myRotatedRect.angle;
if (myRotatedRect.size.width < myRotatedRect.size.height) {
  myContourAngle = myContourAngle - 90;
}