In our previous tutorials – cv2.imread() – Read Image using OpenCV Python and cv2.resize() – Resizing Image using OpenCV Python, we have learned to read and resize an image. We will now learn to save the array into an image file. For this, we are going to use cv2.imwrite() function from the OpenCV library.
To use OpenCV in Python install the following libraries:
- NumPy
- OpenCV
To install the above libraries, use the following command.
pip3 install opencv-python
pip3 install numpy
Syntax – cv2.imwrite()
The syntax for the cv2.imwrite() function is:
cv2.imwrite(path, image)
- path: (required) The complete path where the file needs to be saved on the disk. The path must include an image format like .jpg, .png, etc,
- image: (required) The image is basically a NumPy array.
The cv2.imwrite() function returns a boolean value: True or False. The return value True means that the image is successfully written and False when the image is not successfully written.
Saving an image with cv2.imwrite()
Saving an image is quite easy and simple. Here we are going to learn to save an image to a disk.
Example 1: Reading and Saving Image
In this example, we will read an image, apply some functions to it and then save the image back to the disk.
import cv2
## Reading an image
image = cv2.imread("image.jpg", cv2.IMREAD_COLOR)
## Convert it to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
## Saving an image
val = cv2.imwrite("gray.jpg", gray)
if val == True:
print("Image is successfully saved on the disk.")
else:
print("Image is not saved on the disk.")
Output
Image is successfully saved on the disk.
The above program reads the input image as an RGB image and converts it to a grayscale image. After that, we save the grayscale image on the disk.
Example 2: Saving a Random NumPy Array
This example will create a three-dimensional NumPy array with the shape: 512 x 512 x 3. We would use the randint function provided by the NumPy library to create a random array.
import numpy as np
import cv2
## Creating a random array
image = np.random.randint(255, size=(512, 512, 3))
## Saving an image
val = cv2.imwrite("random.jpg", image)
if val == True:
print("Image is successfully saved on the disk.")
else:
print("Image is not saved on the disk.")
Output
Image is successfully saved on the disk.
The following image is generated and saved on the disk.
Conclusion
In this OpenCV tutorial, we have learned how to save an image by using the cv2.imwrite() function.
More
- Wallpics: https://www.wallpics.com