In this video, we will see an important and basic function of OpenCV and precisely How crop images with OpenCV and Python. It might seem a foregone and trivial thing for those who know Opencv but cropping images with Python can be of help to many beginners who follow my lessons.

In this lesson we will see:

1. How to crop the image vertically or horizontally
2. Crop a portion of the image

1. How to crop the image vertically or horizontally

First we need to load the image into our project. Obviously for the crop images with Opencv and Python we have to make sure that the OpenCV library is installed correctly.

If you haven’t installed Opencv yet, don’t worry, I offer you a tutorial for installing on three different devices:

How to install Python 3 and Opencv 4 on Windows
Install Opencv 4.1 on Nvidia Jetson Nano
Raspberry Pi 3 and Opencv 3 Installation Tutorial

Well, now that we have all the necessary basic elements we proceed with importing Opencv and Numpy, then we also put the path of our image to include it in our python project.

import cv2
import numpy as np

img = cv2.imread("colors.jpg")

Let’s now take rows and cols of the image:

rows, cols, _ = img.shape
print("Rows", rows)
print("Cols", cols)

Rows represents the vertical part and cols the horizontal part. As seen in the print of the image below, I have circled the result, the dimensions show exactly one rectangle.

Let’s now proceed with a first horizontal cut test.

# Cut image
cut_image = img[426: 853, 0: 1280]

In the code, we have set a horizontal cut and in the image, you can see a first test result. Try to vary the numbers of the array, within the maximum limits of the image, to better understand the procedure.

2. Crop a portion of the image

After all the previous steps, to understand How crop images with OpenCV and Python, we now need to retrieve the region of interest (ROI). If you want to learn more about the topic, I recommend the official OpenCV guide on ROI.

To do this we need to find the coordinates of:
-top left point (x, y)
-right bottom (x2, y2)
# ROI (Region of interest)
cv2.rectangle(img, (385, 155), (851, 613), (0, 255, 0), 3)

roi = img[155: 613, 385: 851]

I first checked the coordinates of the points so I could enter them manually. As you can see from the image here is the final result.

You can notice that there is a small green frame, it is not essential to have it and you can remove it by commenting this function cv2.rectangle.