”;
Cropping an image in Pillow (Python Imaging Library) involves selecting a specific region or subarea of an image and creating a new image from that region. This operation is useful for removing unwanted parts of an image and focusing on a particular subject or resizing an image to specific dimensions.
The Image module of the pillow library provides the crop() method to perform the crop operation on the images.
Cropping an Image using the crop() method
Cropping an image can be done by using the crop() method, which allows us to define a box specifying the coordinates of the left, upper, right and lower corners of the region that we want to retain and then it creates a new image with only that portion of the original image.
Here is the basic syntax for the crop() method in Pillow library −
PIL.Image.crop(box)
Where,
-
box − A tuple specifying the coordinates of the cropping box in the format (left, upper, right, lower). These coordinates represent the left, upper, right and lower edges of the rectangular region we want to retain.
Example
In this example we are cropping the image by using the crop() method by passing the left, upper, right and lower corners of the image region that we want.
from PIL import Image #Open an image image = Image.open("Images/saved_image.jpg") # Display the inaput image image.show() #Define the coordinates for the region to be cropped (left, upper, right, lower) left = 100 upper = 50 right = 300 lower = 250 #Crop the image using the coordinates cropped_image = image.crop((left, upper, right, lower)) #Display the cropped image as a new file cropped_image.show()
Output
The above code will generate the following output −
Input image:
Output image cropped image:
Example
Here this is another example of performing the crop operation of the specified portion of the input image using the crop() method.
from PIL import Image #Open an image image = Image.open("Images/yellow_car.jpg") # Display the inaput image image.show() #Define the coordinates for the region to be cropped (left, upper, right, lower) left = 100 upper = 100 right = 300 lower = 300 #Crop the image using the coordinates cropped_image = image.crop((left, upper, right, lower)) #Display the cropped image cropped_image.show()
Output
On executing the above code you will get the following output −
Input image:
Output cropped image:
”;