# Deskew a rectangle

I'm having a "trigonometric" issue. I have as input an image that contains a skewed rectangle. The image is like a bounding box of the rectangle. like this:

0,0
|""""/\"""""|
|   /   \   |
|  /      \ |
| /        /|
|/        / |
|\       /  |
|  \    /   |
|    \ /    |
"""""""""""  w,h


When I rotate it over the center, I have a rectangle inside an image, like this:

0,0
|"""""""""""|
|  -------  |
|  |     |  |
|  |     |  |
|  |     |  |
|  |     |  |
|  |     |  |
|  -------  |
"""""""""""  w,h


The rectangle is centralized (my ascii art wasn't really precize). What I want is the coordinates (width and height) of the rectangle I've deskewed, so I could crop the borders out.

Summarizing, the information I have:

• Image width and height (the skewed rectangle's bounding box is the size of the image)
• The skew angle

What I want:

• Rectangle Width and Height

It should be easy to do, since we would just need to isolate width and height in a system of equations. However, when I test my solution, I get errors.

Could you help me?

• In the first figure, let's label the outer rectangle (ABCD, anti-clockwise starting from top-left point) and the skewed rectangle(EFGH, anti-clockwise starting from top centre point) Nov 18, 2014 at 11:41
• Can you tell us what you mean by 'centralized' ? Nov 18, 2014 at 11:50
• Centrilized - the outer (ABCD) and the inner (EFGH) rectangle have the same center point. Nov 19, 2014 at 10:48

In the first figure, let's label the outer rectangle (ABCD, anti-clockwise starting from top-left point) and the skewed rectangle(EFGH, anti-clockwise starting from top centre point)

All angles are in degrees.

Let $∠FGB = x$ and consequently, $∠AEF = 90-x$
Let $l=length of skewed rectangle = EF$ and $b=FG$

Now, $lsin(90-x) + bsinx=h$
Similarly, $lcos(90-x) + bcosx=w$

Since, you know x, h and w, you can solve for $l$ and $b$.

The new rectangle after de-skewing (in counter-clockwise direction) will have its top-left coordinate at ($\frac{w-b}{2}, \frac{h-l}{2})$