Ask Your Question

How to extract pixels from a rotated box2d?

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

tleyden gravatar image

updated 2020-10-23 09:49:23 -0600

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 -0600

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

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 -0600 )edit

Question Tools


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

Seen: 2,033 times

Last updated: Jul 31 '14