First time here? Check out the FAQ!

Ask Your Question
1

How to extract pixels from a rotated box2d?

asked Jul 31 '14

tleyden gravatar image

updated Oct 23 '0

I have a box2d that was returned from calling cvMinAreaRect2() on a contour, and it's rotated at 45 degrees.

I want to extract the pixels from that contour into it's own image, where the box2d is rotated so that it's upright.

Preview: (hide)

1 answer

Sort by » oldest newest most voted
1

answered Jul 31 '14

updated Jul 31 '14

A first step is to stop using the old outdated C-API and move on to the new C++ functionality, in your case the minAreaRect function.

What you have to define is the rotation matrix between your box and a horizontal box. More information can be found in in this great answer of Philip Wagner (and could possibly be found with a simple google search - was my first hit).

The code needed to do what you need is something like this template:

// rect is the RotatedRect (I got it from a contour...)
RotatedRect rect;
// matrices we'll use
Mat M, rotated, cropped;
// get angle and size from the bounding box
float angle = rect.angle;
Size rect_size = rect.size;
// thanks to http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
if (rect.angle < -45.) {
   angle += 90.0;
   swap(rect_size.width, rect_size.height);
}
// get the rotation matrix
M = getRotationMatrix2D(rect.center, angle, 1.0);
// perform the affine transformation
warpAffine(src, rotated, M, src.size(), INTER_CUBIC);
// crop the resulting image
getRectSubPix(rotated, rect_size, rect.center, cropped);
Preview: (hide)

Comments

1

Thanks, that worked. Here's a snippet of the python code that I used: https://gist.github.com/tleyden/d5f2fa909c5e55d0d139

tleyden gravatar imagetleyden (Aug 1 '14)edit

Question Tools

Stats

Asked: Jul 31 '14

Seen: 2,183 times

Last updated: Jul 31 '14