This program reads an image named 'input.jpg' and saves it as 'saved_image.jpg'. It prints messages to confirm success or failure.
Computer Vision
import cv2
# Read an image from file
image = cv2.imread('input.jpg')
# Check if image was loadedif image isNone:
print('Failed to load image.')
else:
# Save the image with a new name
success = cv2.imwrite('saved_image.jpg', image)
if success:
print('Image saved successfully.')
else:
print('Failed to save image.')
OutputSuccess
Important Notes
Make sure the folder where you save the image exists, or saving will fail.
Supported formats depend on the file extension you use, like .jpg, .png, .bmp.
Saving large images may take more time and disk space.
Summary
Use cv2.imwrite() to save images to files.
Provide the filename and image data as arguments.
Check if saving was successful to avoid errors.
Practice
(1/5)
1. What does the function cv2.imwrite() do in computer vision?
easy
A. Converts an image to grayscale
B. Reads an image from a file
C. Displays an image in a window
D. Saves an image to a file on disk
Solution
Step 1: Understand the purpose of cv2.imwrite()
This function is used to save image data to a file on your computer.
Step 2: Differentiate from other OpenCV functions
Functions like cv2.imread() read images, and cv2.imshow() display images, but cv2.imwrite() specifically saves images.
Final Answer:
Saves an image to a file on disk -> Option D
Quick Check:
cv2.imwrite() = Save image [OK]
Hint: Remember 'imwrite' means 'image write' to file [OK]
Common Mistakes:
Confusing imwrite with imread
Thinking it displays images
Assuming it converts image formats automatically
2. Which of the following is the correct syntax to save an image stored in variable img to a file named output.jpg using OpenCV?
easy
A. cv2.save('output.jpg', img)
B. cv2.imwrite('output.jpg', img)
C. cv2.write('output.jpg', img)
D. cv2.saveImage('output.jpg', img)
Solution
Step 1: Recall the correct OpenCV function name
The function to save images is cv2.imwrite(), not save or write.
Step 2: Check the argument order
The first argument is the filename as a string, the second is the image variable.
Final Answer:
cv2.imwrite('output.jpg', img) -> Option B
Quick Check:
Correct function and argument order = cv2.imwrite('output.jpg', img) [OK]
Hint: Use 'imwrite' with filename first, then image [OK]
Common Mistakes:
Using non-existent functions like cv2.save
Swapping argument order
Missing quotes around filename
3. What will be the output of the following code snippet?