In this tutorial, you will learn how to crop images using OpenCV.
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, but we’ll review it again for more completeness.
To learn how to crop images with OpenCV, just keep reading.
Looking for the source code to this post?
Jump Right To The Downloads SectionCrop Image with OpenCV
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
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 — it will have you up and running in a matter of minutes.
Having problems configuring your development environment?
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 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:
Our goal here is to extract my face and body from the region using simple cropping methods.
We would normally apply object detection techniques 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, 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:
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:
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.
86 total classes • 115+ hours of on-demand code walkthrough videos • Last updated: October 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:
- ✓ 86 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ 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 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
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!
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!
Comment section
Hey, Adrian Rosebrock here, author and creator of PyImageSearch. While I love hearing from readers, a couple years ago I made the tough decision to no longer offer 1:1 help over blog post comments.
At the time I was receiving 200+ emails per day and another 100+ blog post comments. I simply did not have the time to moderate and respond to them all, and the sheer volume of requests was taking a toll on me.
Instead, my goal is to do the most good for the computer vision, deep learning, and OpenCV community at large by focusing my time on authoring high-quality blog posts, tutorials, and books/courses.
If you need help learning computer vision and deep learning, I suggest you refer to my full catalog of books and courses — they have helped tens of thousands of developers, students, and researchers just like yourself learn Computer Vision, Deep Learning, and OpenCV.
Click here to browse my full catalog.