Python | OpenCV program to read and save an Image

Python | OpenCV program to read and save an Image

To write a Python program that uses OpenCV for reading and saving an image, you first need to have OpenCV installed. If it's not installed, you can install it using pip:

pip install opencv-python 

Once OpenCV is installed, you can use the following Python script to read and save an image:

import cv2 # Load an image image_path = 'path_to_your_image.jpg' # Replace with your image path image = cv2.imread(image_path) # Check if the image is loaded properly if image is not None: # Display the image cv2.imshow('Loaded Image', image) cv2.waitKey(0) # Wait for a key press to close the displayed image # Save the image save_path = 'path_to_save_image.jpg' # Replace with your desired save path cv2.imwrite(save_path, image) print(f"Image saved to {save_path}") else: print("Error: Image not loaded. Please check the file path.") 

This script does the following:

  1. Reads an image from a specified path using cv2.imread.
  2. Checks if the image is loaded correctly.
  3. Displays the loaded image in a window.
  4. Waits for a key press to close the image window.
  5. Saves the image to a specified path using cv2.imwrite.

Replace 'path_to_your_image.jpg' with the path to your image and 'path_to_save_image.jpg' with the path where you want to save the image.


More Tags

react-component hexdump dask hyper-v ado render hierarchical-clustering android-camera2 polymorphism react-android

More Programming Guides

Other Guides

More Programming Examples