How To Crop Image In Opencv Python

Image processing is an essential step in computer vision projects. Cropping an image is one of the basic operations that can be performed using OpenCV Python.

Cropping an image helps to remove the unwanted parts of an image and extract only the part that is required. In this tutorial, we will learn how to crop an image using OpenCV Python.

Step 1: Install the necessary libraries

Instead of installing “cv2”, you should install the “opencv-python” package which includes the “cv2” module. You can install the “opencv-python” package using pip by running the following command:

pip install opencv-python

Step 2: Import the necessary libraries

First, we need to import the necessary libraries to work with images using OpenCV Python. The following code snippet demonstrates the import of OpenCV Python.

Step 3: Load the image

We can load the image using the cv2.imread() function. This function takes the path of the image as input and returns an array of pixel values.

Step 4: Define the cropping coordinates

We need to define the coordinates of the region of interest (ROI) that we want to crop from the image. The ROI is defined as (starting x-coordinate, starting y-coordinate, width, height) of the rectangle.

Step 5: Crop the image

To crop the image, we need to pass the ROI coordinates to the array of the image.

Step 6: Display the cropped image

We can display the cropped image using the cv2.imshow() function.

Complete Code

Follow these simple steps, and you will be able to crop an image in OpenCV Python easily. To learn more, you can visit the official OpenCV Python documentation at https://docs.opencv.org/master/d6/d00/tutorial_py_root.html