15 Mar Resize an image with OpenCV
Resizing an image with OpenCV is quite straightforward. You can use the cv2.resize() function to achieve this. The cv2.resize(image, new_dimensions) resizes the image.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Read an image and resize it import cv2 # Load an image image = cv2.imread(r'C:\Users\hp\Downloads\amit.jpeg', 1) # Define new dimensions (width, height) new_dimensions = (600, 600) # Resize the image resized_image = cv2.resize(image, new_dimensions) print('Resized Dimensions : ', resized_image.shape) # Display the resized image cv2.imshow("Image Resized:", resized_image) # Wait for a key press and close the window cv2.waitKey(0) cv2.destroyAllWindows() |
The image is resized to 600×600 dimensions now. Initially, the image size was 1280×1280.
The following is the output:
Explanation:
The above Python script uses the OpenCV library to load, resize, and display an image. The code starts by importing the OpenCV library.
- It then reads an image from the specified file path and loads it into a variable named
image
. - The
cv2.imread()
function is used for this purpose, with1
indicating that the image should be loaded in color. - The script then defines new dimensions for resizing the image, setting both the width and height to 600 pixels. Using the
cv2.resize()
function, the image is resized to the specified dimensions and stored in a variable namedresized_image
. - The new dimensions of the resized image are printed to the console using
print()
. - Finally, the script displays the resized image in a window titled “Image Resized:” with the
cv2.imshow()
function. - To keep the image window open, the script includes a
cv2.waitKey(0)
function, which waits indefinitely for a key press. - Once a key is pressed, the script closes all OpenCV windows using the
cv2.destroyAllWindows()
function. This process allows users to view the resized image and close the display window at their convenience.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- Generative AI Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments