Diagonally crop an image using python and pillow
The black box is the area that we want to crop. It is a 150x200 rectangle rotated 45 degrees. The red dot is the base, at (200, 250).
This code
import math
from PIL import Image
import diagonal_crop
im = Image.open('media/lenna.png')
angle = math.pi / 4
base = (200, 250)
height = 150
width = 200
cropped_im = diagonal_crop.crop(im, base, angle, height, width)
produces this image:
Making the crop is relatively simple; at a high level the image is rotated and then cropped.
For large images rotation can be expensive. So first, the image is cropped down to the bounding box of the target area. The bounding box is shown in white:
And here is the result:
The new crop area is calculated:
The image is rotated:
And, the crop area recalculated:
This can then be cropped, giving the final result: