Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify cropping boundaries after rotation to preserve image ratio #258

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

romain-xu-darme
Copy link

After getting an exception when trying to rotate an image with unusual dimensions (470x109) by 15 degrees using RotateRange, I notice that the crop operation at the end of this operation does not seem to preserve the aspect ratio of the image, as it is computed solely from the dimensions (X,Y) of the rotated image.
After a bit of trigonometry, I propose a slight modification for the computation of the cropped region as follows

crop_rotate

Basically, for a rotation of angle $a$, the value of $M$ (red segment) is computed as $M=\frac{y}{2\times cos(a)}$. Then, knowing that $M = x' \times tan(a) + x' \times tan(c) = x' \times tan(a) + x' \times \frac{y}{x} = x'\times (tan(a)+ \frac{y}{x})$, it follows that $x' = \dfrac{M}{tan(a)+ \frac{y}{x}}$ and $y'=x'\times y/x$ (to preserve aspect ratio).

With this modified code, I seem to obtain better rotated images, see below:

Original image:
Blue_Grosbeak_0014_36708

After rotation (15 degrees) with the original code:
test_original_Blue_Grosbeak_0014_36708_original_code

With the modified code:
test_original_Blue_Grosbeak_0014_36708_modified_code

Furthermore, the code no longer throws an exception when processing images with weird aspect ratios (eg. 470x109). Note however that this formula highly depends on the ability of the rotate operation to preserve the right angles of the original image inside the rotated one.

@mdbloice
Copy link
Owner

Thanks @romain-xu-darme, looks great I will take a closer look as soon as I can, and see if we can merge.

What was causing the exceptions with 'weird' image sizes?

@romain-xu-darme
Copy link
Author

I get a ValueError: Coordinate 'lower' is less than 'upper' because with $(x,y)=(470\times109)$, you get $(X,Y)=484\times227$ after a rotation of 15 degrees. Then, using the current trigo formula, the end results is:
$E = 26$, $A = 123$, $X-E = 458$ and $Y-A=104$. In other words, $A > Y-A$, which causes the crash.

@mdbloice
Copy link
Owner

Ok understood! Thanks again for the PR, I will take a look ASAP, right now I am away from office.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants