To open and resize an image using OpenCV in Python, you can use the cv2
module. Here’s a basic example:
import cv2
# Open an image file
image_path = 'path/to/your/image.jpg'
original_image = cv2.imread(image_path)
# Check if the image is loaded successfully
if original_image is not None:
# Display the original image
cv2.imshow('Original Image', original_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Resize the image
width, height = 500, 300 # Set the new dimensions
resized_image = cv2.resize(original_image, (width, height))
# Display the resized image
cv2.imshow('Resized Image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save the resized image
cv2.imwrite('path/to/save/resized_image.jpg', resized_image)
else:
print('Error: Unable to open the image.')
- Replace
'path/to/your/image.jpg'
with the actual path to your image file. - Adjust the
width
andheight
variables to set the desired dimensions for the resized image. - The
cv2.imshow
function is used to display the original and resized images. Thecv2.waitKey(0)
waits for a key press before closing the image window. - Finally, the
cv2.imwrite
function is used to save the resized image to a new file.
Make sure to install OpenCV first if you haven’t already:
pip install opencv-python
Adjust the code based on your specific requirements and file paths
Resize an image using OpenCV in Python