Say we have an image with the following dimensions:
width = 200
height = 100
Say that the dimensions of our crop would be 50x50
.
How can I crop an image using this new dimension from the center of the image, using Python?
Assume a crop box with the dimensions: cw, ch = 50, 50
.
The center of the image is the point (w//2, h//2)
, where w
is its width and h
is its height. The square crop box which is 50 pixels on a side would also be centered there.
This means the upper left corner of the crop box would be at (w//2 - cw//2, h//2 - ch//2)
, and its lower right corner is at (w//2 + cw//2, h//2 + ch//2)
.
There's at least two ways to crop the image I can think of. The first is to use the Image.crop()
method and pass it the coordinates of the rectangular crop region.
box = w//2 - cw//2, h//2 - ch//2, w//2 + cw//2, h//2 + ch//2
cropped_img = img.crop(box)
Which can be simplified mathematically to cut down on the number of divisions:
box = (w-cw)//2, (h-ch)//2, (w+cw)//2, (h+ch)//2 # left, upper, right, lower
cropped_img = img.crop(box)
Another way to do it is via the ImageOps.crop()
function which is passed the size of the border on each of the four sides:
from PIL import ImageOps
wdif, hdif = (w-cw)//2, (h-ch)//2
border = wdif, hdif, wdif, hdif # left, top, right, bottom
cropped_img = ImageOps.crop(img, border)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With