0
0
Computer Visionml~20 mins

Writing/saving images in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Writing/saving images
Problem:You have processed images in your computer vision project and want to save them correctly to disk for later use or sharing.
Current Metrics:Currently, images are displayed correctly in memory but not saved properly, resulting in corrupted or unreadable files.
Issue:The images are not saved with the correct format or encoding, causing file corruption or loss of data.
Your Task
Save processed images to disk in a standard format (e.g., PNG or JPEG) ensuring the saved files are readable and correctly represent the image data.
Use Python and OpenCV or PIL libraries only.
Do not change the image processing pipeline, only focus on saving the images.
Ensure the saved image files can be opened by standard image viewers.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import cv2
from PIL import Image
import numpy as np

# Example image: create a simple red square using numpy
image = np.zeros((100, 100, 3), dtype=np.uint8)
image[:] = (0, 0, 255)  # Red color in BGR for OpenCV

# Saving with OpenCV
cv2.imwrite('red_square_opencv.png', image)

# Convert BGR to RGB for PIL
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Saving with PIL
pil_image = Image.fromarray(image_rgb)
pil_image.save('red_square_pil.png')
Used cv2.imwrite() to save the image in PNG format with correct BGR color order.
Converted image color from BGR to RGB before saving with PIL to ensure correct colors.
Saved image using PIL's Image.save() method with PNG format.
Results Interpretation

Before: Images were not saved or saved incorrectly, resulting in corrupted files.

After: Images saved using cv2.imwrite() and PIL's save() method open correctly and display the expected red square.

Saving images requires using the right library functions and correct color formats. OpenCV uses BGR color order, while PIL uses RGB, so conversion is necessary to preserve colors.
Bonus Experiment
Try saving images in different formats like JPEG and BMP and compare file sizes and quality.
💡 Hint
Change the file extension in the save function and observe differences in saved file properties.