Cropping an image is a straightforward task in image processing, and OpenCV makes it easy to accomplish. This guide will show you how to crop an image using OpenCV.
Installation
First, ensure you have OpenCV installed. You can install it using pip:
pip install opencv-python
Loading an Image
To crop an image, you first need to load it. Use the cv2.imread function to read the image from a file.
import cv2
# Load the image
image = cv2.imread('path_to_your_image.jpg')
Cropping the Image
Cropping an image involves selecting a region of interest (ROI) and extracting it from the image. You do this by specifying the coordinates of the top-left and bottom-right corners of the desired region.
Define the Coordinates:
- Set the coordinates for the region you want to crop. For example:
x_start, y_start = 50, 50 # Top-left corner x_end, y_end = 200, 200 # Bottom-right corner
Crop the Image:
- Use array slicing to crop the image.
cropped_image = image[y_start:y_end, x_start:x_end]
Displaying the Images
You can display both the original and cropped images using cv2.imshow. This helps you see the result.
# Display the original image
cv2.imshow('Original Image', image)
# Display the cropped image
cv2.imshow('Cropped Image', cropped_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Complete Code Example
Here’s the complete code to crop an image using OpenCV:
import cv2
# Load the image
image = cv2.imread('path_to_your_image.jpg')
# Define the coordinates for cropping
x_start, y_start = 50, 50 # Top-left corner
x_end, y_end = 200, 200 # Bottom-right corner
# Crop the image
cropped_image = image[y_start:y_end, x_start:x_end]
# Display the original image
cv2.imshow('Original Image', image)
# Display the cropped image
cv2.imshow('Cropped Image', cropped_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()