OpenCV (Open-Source Computer Vision Library) is a powerful tool for image processing and computer vision tasks. One common task is resizing images, which can be easily accomplished using OpenCV’s built-in functions. Here’s a step-by-step guide to resizing an image using OpenCV in Python.
Installation
Before you begin, ensure you have OpenCV installed. You can install it using pip:
pip install opencv-python
Loading an Image
First, load the image you want to resize. 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')
Resizing the Image
To resize the image, use the cv2.resize function. You need to specify the new width and height for the image.
# Set new dimensions new_width = 300 new_height = 200 # Resize the image resized_image = cv2.resize(image, (new_width, new_height))
Displaying the Images
You can display both the original and the resized images using cv2.imshow. This helps you verify the changes.
# Display the original image
cv2.imshow('Original Image', image)
# Display the resized image
cv2.imshow('Resized Image', resized_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Saving the Resized Image
Finally, save the resized image to a file using cv2.imwrite.
# Save the resized image
cv2.imwrite('resized_image.jpg', resized_image)
Complete Code Example
Here’s the complete code to resize an image in OpenCV:
import cv2
# Load the image
image = cv2.imread('path_to_your_image.jpg')
# Set new dimensions
new_width = 300
new_height = 200
# Resize the image
resized_image = cv2.resize(image, (new_width, new_height))
# Display the original image
cv2.imshow('Original Image', image)
# Display the resized image
cv2.imshow('Resized Image', resized_image)
# Wait for a key press and close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save the resized image
cv2.imwrite('resized_image.jpg', resized_image)