Crop the image using PIL in python

Go To StackoverFlow.com

87

I want to crop image in the way by removing first 30 rows and last 30 rows from the given image. I have searched but did not get the exact solution. Does somebody have some suggestions?

2012-04-02 20:20
by Taj Koyal


143

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)
2012-04-02 20:29
by ninjagecko
Yes, I know that im.crop(box) is used for cropping the image. But I want to crop only upper and lower part of image not left and right, although box() take 4 tuple but I am not getting how to cropping the upper and lower part of image - Taj Koyal 2012-04-02 20:43
@TajKoyal: Exactly what ninjagecko is showing you is how you crop off the top and bottom. He is specifying a rectangle for the new image. You can see that he shaves off 30 pixels from the y-value on the top and bottom points. If you offset the x values in any way, THAT would affect the left and right sides - jdi 2012-04-02 21:24
Thanks guys for helping me out - Taj Koyal 2012-04-03 09:41
For someone as lazy as me Parameters: box – The crop rectangle, as a (left, upper, right, lower)-tuple.Rishav 2018-12-12 18:29


24

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()
2017-04-24 15:02
by Atul Chavan


1

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)
2019-01-17 21:23
by PouyaB
Ads