Josselin
Josselin

Reputation: 325

Crop the center of an image

How can l use the function crop() from PIL to crop the center of an image of 224*224.

Given an input image of :

320*240, crop the center of this image of dimension 224*224

Expected output :

cropped center of the image of dimension 224*224

Upvotes: 2

Views: 1377

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207425

Starting with this image where the coloured part is 224x224 on a black background of 320x240.

enter image description here

I would just use numpy to crop like this:

#!/usr/local/bin/python3
from PIL import Image
import numpy as np

# Open the image and convert to numpy array
im=Image.open('start.png')
im=np.array(im)

# Work out where top left corner is
y=int((320-224)/2)
x=int((240-224)/2)

# Crop, convert back from numpy to PIL Image and and save
cropped=im[x:x+224,y:y+224]
Image.fromarray(cropped).save('result.png')

enter image description here

Upvotes: 1

Related Questions