Crop an Image using Python
In this tutorial, you will learn how to crop an Existing Image in Python. We simply use Python Imaging Library (PIL) Module to crop an Image. We mainly require Image Class from PIL module in order to Crop an Image.
Crop an Image using PIL in Python
So, the first line of the Python Script will be as follows:
from PIL import Image
Here, we have imported Image Class from Python Imaging Library (PIL). Image class is basically used to do some specific operations like Opening, Saving, Closing, and Cropping etc. We should open an Image before going to crop it. Lets have a look at Opening an Image. It would be as follows
We have used open method in Image Class to Open an Image. img is the Image Object which is able to perform Operations on Image. Whereas Path_to_Your_Image is the Path String where the Image is located in Your Computer. Lets have a Look at using Crop Method.
Syntax: img.crop(self, box=(left,upper,right,lower))
- img is the Image Object
- self is the Reference of Image Object
- box is a 4 – valued Tuple indicating the borders or boundaries of Image to crop.
- left is the Left Boundary of Cropped Image
- upper is the Upper Boundary of Cropped Image
- right is the Right Boundary of Cropped Image
- lower is the Lower Boundary of Cropped Image
Let the Box Tuple be
It simply creates a rectangular box of dimensions 500 X 700. Lets have a glance over the following Script.
It crops the given Image into given Dimensions. If given dimensions exceed the original dimensions of an Image then it will show Black Color for exceeded dimensions. Here, c_i is the Cropped Image Object based on given Dimensions of Box.
Cropped Image can Either be Shown or Saved.
To Show Cropped Image:
Show Method uses Command Prompt (cmd) to display the Image.
To Save Cropped Image:
Save Method saves the Cropped Image at Destination_Path. It can be Viewed Later by opening it.
So, Let’s have a look at the following code to show a Cropped Image.
from PIL import Image img=Image.open("Path_to_your_Image") b=(320,125,810,530) c_i=img.crop(box=b) c_i.show()
In this way, we can Crop a given Image using Python Imaging Library (PIL) in Python.
To know more about Image Processing using PIL Click Here ->Image Module in PIL