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.
1 2 |
import cv2 import numpy as np |
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.
1 |
img = cv2.imread(r'C:\dir\image.jpg') |
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.
1 2 3 4 |
x = starting x-coordinate y = starting y-coordinate w = width h = height |
Step 5: Crop the image
To crop the image, we need to pass the ROI coordinates to the array of the image.
1 |
crop_img = img[y:y+h, x:x+w] |
Step 6: Display the cropped image
We can display the cropped image using the cv2.imshow() function.
1 2 3 |
cv2.imshow('Cropped Image', crop_img) cv2.waitKey(0) cv2.destroyAllWindows() |
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import cv2 import numpy as np # Load the image img = cv2.imread(r'C:\dir\image.jpg') # Define the region of interest (ROI) to crop x = 50 y = 100 w = 200 h = 150 crop_img = img[y:y+h, x:x+w] # Display the cropped image cv2.imshow('Cropped Image', crop_img) cv2.waitKey(0) # Save the cropped image to a file cv2.imwrite(r'C:\dir\cropped_image.jpg', crop_img) # Clean up and close all windows cv2.destroyAllWindows() |
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