How to Crop an Image in Python using Numpy



Python


In this article, we show how to crop an image in Python using the numpy module.

Numpy doesn't have a specific crop function for images, but if we utilize indexing, we can crop out whatever part of any image we want. This is usually in a square or rectangle shape.

So in this article, we will read an image in using the OpenCV module, then we will use numpy to crop out a portion of the image.

So below we have an image of nature.



We will crop out the following image so that we crop as the waterfall so that it will be the most dominant feature of our cropped image. This is shown below.



So you can see that we cropped out the waterfall to focus on this part of the picture of nature.

Below is the code to crop out the waterfall of the image.



First we import cv2 and numpy. We use cv2 to read and show the image. We use numpy to crop the original image.

We then create a variable, image, and store the image of the waterfall.

We then create a variable, cropped, which stores the cropped image.

To crop an image, the format to do so is, image[start_row:end_row, start_column:end_column]

To figure out how the pixels to crop this image, you can first plot the original image with grids. This will allow you to visualize where to crop the image based on pixels. For the original image with grids, you can see it here.

You can see that the waterfall goes vertically starting at about 30px and ending at around 250px.

You can see that the waterfall goes horizontally from around 100px to around 230px.

We then show the cropped image using OpenCV.

And this is how we can crop an image with the numpy module.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...