Title: Crop Image with OpenCV - PyImageSearch

URL Source: https://pyimagesearch.com/2021/01/19/crop-image-with-opencv/

Published Time: 2021-01-19T07:24:00+00:00

Markdown Content:
In this tutorial, you will learn how to crop images using OpenCV.

![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20450'%3E%3C/svg%3E)

As the name suggests, **cropping is the act of _selecting_ and _extracting_ the Region of Interest** (or simply, ROI) and is the part of the image in which we are interested.

For instance, in a face detection application, we may want to crop the face from an image. And if we were developing a Python script to recognize dogs in images, we may want to crop the dog from the image once we have found it.

We already utilized cropping in our tutorial, _[Getting and setting pixels with OpenCV](https://pyimagesearch.com/2021/01/20/opencv-getting-and-setting-pixels/),_ but we’ll review it again for more completeness.

**To learn how to crop images with OpenCV, _just keep reading._**

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

In the first part of this tutorial, we’ll discuss how we represent OpenCV images as NumPy arrays. Since each image is a NumPy array, we can leverage NumPy array slicing to crop an image.

From there, we’ll configure our development environments and review our project directory structure.

I’ll then demonstrate how simple it is to crop images with OpenCV!

### **Understanding image cropping with OpenCV and NumPy array slicing**

![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20625%20310'%3E%3C/svg%3E)

**Figure 1:** We accomplish image cropping by using NumPy array slicing ([image source](http://scipy-lectures.org/intro/numpy/array_object.html)).

When we crop an image, we want to remove the outer parts of the image we are not interested in. We commonly refer to this process as selecting our _Region of Interest_, or more simply, our ROI.

We can accomplish image cropping by using NumPy array slicing.

Let’s start by initializing a NumPy list with values ranging from _\[0, 24\]:_

\>>> import numpy as np
>>> I = np.arange(0, 25)
>>> I
array(\[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
       15, 16, 17, 18, 19, 20, 21, 22, 23, 24\])
>>> 

And let’s now reshape this 1D list into a 2D matrix, pretending that it is an image:

\>>> I = I.reshape((5, 5))
>>> I
array(\[\[ 0,  1,  2,  3,  4\],
       \[ 5,  6,  7,  8,  9\],
       \[10, 11, 12, 13, 14\],
       \[15, 16, 17, 18, 19\],
       \[20, 21, 22, 23, 24\]\])
>>> 

Now, let’s suppose I want to extract the “pixels” starting at _x = 0_, _y = 0_ and ending at _x = 2_, _y = 3_. Doing so can be accomplished using the following code:

\>>> I\[0:3, 0:2\]
array(\[\[ 0,  1\],
       \[ 5,  6\],
       \[10, 11\]\])
>>> 

Notice how we have extracted three rows (_y = 3_) and two columns (_x = 2_).

Now, let’s extract the pixels starting at _x = 1_, _y = 3_ and ending at _x = 5_ and _y = 5_:

\>>> I\[3:5, 1:5\]
array(\[\[16, 17, 18, 19\],
       \[21, 22, 23, 24\]\])
>>>

This result provides the final two rows of the image, minus the first column.

Are you noticing a pattern here?

When applying NumPy array slicing to images, we extract the ROI using the following syntax:

`roi = image[startY:endY, startX:endX]`

The `startY:endY` slice provides our _rows_ (since the _y_\-axis is our number of rows) while `startX:endX` provides our _columns_ (since the _x_\-axis is the number of columns) in the image. Take a second now to convince yourself that the above statement is true.

But if you’re a bit more confused and need more convincing, don’t worry! I’ll show you some code examples later in this guide to make image cropping with OpenCV more clear and concrete for you.

### **Configuring your development environment**

To follow this guide, you need to have the OpenCV library installed on your system.

Luckily, OpenCV is pip-installable:

$ pip install opencv-contrib-python

**If you need help configuring your development environment for OpenCV, I _highly recommend_ that you read my** [**_pip install OpenCV_ guide**](https://pyimagesearch.com/2018/09/19/pip-install-opencv/) — it will have you up and running in a matter of minutes.

### **Having problems configuring your development environment?**

[![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20251'%3E%3C/svg%3E)](https://pyimagesearch.com/pyimagesearch-plus/)

**Figure 2:** Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) — you will be up and running with this tutorial in a matter of minutes.

All that said, are you:

*   Short on time?
*   Learning on your employer’s administratively locked system?
*   Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?
*   **Ready to run the code** **_right now_** **on your Windows, macOS, or Linux system?**

Then join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) today!

**Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides that are _pre-configured_ to run on Google Colab’s ecosystem right in your web browser!** No installation required.

And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!

### **Project structure**

Before we can implement image cropping with OpenCV, let’s first review our project directory structure.

Start by using the **_“Downloads”_** section of this guide to access the source code and example images:

$ tree . --dirsfirst
.
├── adrian.png
└── opencv\_crop.py

0 directories, 2 files

We only have a single Python script to review today, `opencv_crop.py`, which will load the input `adrian.png` image from disk and then crop out the face and body from the image using NumPy array slicing.

### **Implementing image cropping with OpenCV**

We are now ready to implement image cropping with OpenCV.

Open the `opencv_crop.py` file in your project directory structure and insert the following code:

\# import the necessary packages
import argparse
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add\_argument("-i", "--image", type=str, default="adrian.png",
	help="path to the input image")
args = vars(ap.parse\_args())

**Lines 2 and 3** import our required Python packages while **Lines 6-9** parse our command line arguments.

We only need one command line argument, `--image`, which is the path to the input image we wish to crop. For this example, we’ll default the `--image` switch to the `adrian.png` file in our project directory.

Next, let’s load our image from disk:

\# load the input image and display it to our screen
image = cv2.imread(args\["image"\])
cv2.imshow("Original", image)

# cropping an image with OpenCV is accomplished via simple NumPy
# array slices in startY:endY, startX:endX order -- here we are
# cropping the face from the image (these coordinates were
# determined using photo editing software such as Photoshop,
# GIMP, Paint, etc.)
face = image\[85:250, 85:220\]
cv2.imshow("Face", face)
cv2.waitKey(0)

**Lines 12 and 13** load our original `image` and then display it to our screen:

![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20585%20475'%3E%3C/svg%3E)

**Figure 3:** The original input image that we will be cropping using OpenCV.

Our goal here is to extract my _face_ and _body_ from the region using simple cropping methods.

We would normally apply [object detection techniques](https://pyimagesearch.com/category/object-detection/) to detect my face and body in the image. However, since we are still relatively early in our OpenCV education course, we will use our _a priori_ knowledge of the image and _manually_ supply the NumPy array slices where the body and face reside.

Again, we can, of course, use [object detection methods to detect and extract faces from images _automatically_](https://pyimagesearch.com/2018/02/26/face-detection-with-opencv-and-deep-learning/), but for the time being, let’s keep things simple.

We extract my face from the image on a single line of code (**Line 20**).

We are supplying NumPy array slices to extract a rectangular region of the image, starting at _(85, 85)_ and ending at _(220, 250)_.

The order in which we supply the indexes to the crop may seem counterintuitive; however, remember that OpenCV represents images as NumPy arrays with the height first (# of rows) and the width second (# of columns).

To perform our cropping, NumPy expects four indexes:

*   **Start _y_:** The starting _y_\-coordinate. In this case, we start at _y = 85_.
*   **End _y_**: The ending _y_\-coordinate. We will end our crop at _y = 250._
*   **Start _x_:** The starting _x_\-coordinate of the slice. We start the crop at _x = 85_.
*   **End _x_**: The ending _x_\-axis coordinate of the slice. Our slice ends at _x = 220_.

We can see the result of cropping my face below:

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20475'%3E%3C/svg%3E)

**Figure 4**: Cropping the face using OpenCV.

Similarly, we can crop my body from the image:

\# apply another image crop, this time extracting the body
body = image\[90:450, 0:290\]
cv2.imshow("Body", body)
cv2.waitKey(0)

Cropping my body is accomplished by starting the crop from coordinates _(0, 90)_ and ending at _(290, 450)_ of the original image.

Below you can see the output of cropping with OpenCV:

![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20381%20475'%3E%3C/svg%3E)

**Figure 5:** Cropping the body from the image using OpenCV.

While simple, cropping is an extremely important skill that we will utilize throughout this series. If you are still feeling uneasy with cropping, definitely take the time to practice now and hone your skills. From here on, cropping will be an assumed skill that you will need to understand!

### **OpenCV image cropping results**

To crop images with OpenCV, be sure you have gone to the **_“Downloads”_** section of this tutorial to access the source code and example images.

From there, open a shell and execute the following command:

$ python opencv\_crop.py

Your cropping output should match mine from the previous section.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

**Summary**
-----------

In this tutorial, you learned how to crop an image using OpenCV. Since OpenCV represents images as NumPy arrays, cropping is as simple as supplying the crop’s starting and ending ranges as a NumPy array slice.

All you need to do is remember the following syntax:

`cropped = image[startY:endY, startX:endX]`

As long as you remember the order in which to supply the starting and ending _(x, y)_\-coordinates, cropping images with OpenCV is a breeze!

**To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), _simply enter your email address in the form below!_**

![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!