Modify cropping boundaries after rotation to preserve image ratio #258
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
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:
After rotation (15 degrees) with the original code:
With the 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.