Ask Your Question

How to extract pixels from a rotated box2d?

asked 2014-07-31 02:30:22 -0500

tleyden gravatar image

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.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2014-07-31 02:48:26 -0500

updated 2014-07-31 02:50:18 -0500

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
if (rect.angle < -45.) {
   angle += 90.0;
   swap(rect_size.width, rect_size.height);
// get the rotation matrix
M = getRotationMatrix2D(, angle, 1.0);
// perform the affine transformation
warpAffine(src, rotated, M, src.size(), INTER_CUBIC);
// crop the resulting image
getRectSubPix(rotated, rect_size,, cropped);
edit flag offensive delete link more



Thanks, that worked. Here's a snippet of the python code that I used:

tleyden gravatar imagetleyden ( 2014-08-01 04:23:56 -0500 )edit
Login/Signup to Answer

Question Tools


Asked: 2014-07-31 02:30:22 -0500

Seen: 1,070 times

Last updated: Jul 31 '14