The imwrite() Function of OpenCV
Images are processed as numpy.ndarrays
in Python, and these arrays are three-dimensional and represent the values of the image pixels. Using different libraries and methods, we can read and process images efficiently in Python.
One such library is the OpenCV library which can process images easily using its functionalities and classes. This tutorial will demonstrate using the OpenCV library’s imwrite()
function.
Use the imwrite()
Function From the OpenCV Library
The imwrite()
function saves images to a given path location. As discussed, the images are stored as arrays and, using this function, we can export and save these images on the device.
It accepts three parameters. The first parameter contains the name of the file along with the path. Note that the format in which the image is saved (PNG, JPEG, etc.) should be specified in the filename.
The second parameter contains the required image that needs to be saved. This image should be a numpy.ndarray
object. If the image file is properly saved, the imwrite()
function returns True
; otherwise, it returns False
.
Example Code:
import cv2
i = cv2.imread("deftstack.png")
img = cv2.cvtColor(i, cv2.COLOR_BGR2HSV)
cv2.imwrite("save.png", img)
Output:
True
In the above example, we read a given image using the imread()
function. Then, we perform a task on the image (we are converting it from RGB color space to the HSV color space) using the cvtColor
function.
Finally, we use the imwrite()
function to save this image in the specified directory. Note that the format of the image in the file is PNG
, and we can use any supported formats like BMP
, JPEG
, WebP
, and more.
Another thing to remember is that this function only saves the 8-bit single channel or the BGR ordered 3-channel images with a few exceptions. These exceptions include the 16-bit unsigned, 32-bit floats, Map
vector of multiple images, and PNG images with an alpha channel that can only be saved in some allowed formats.
Every unsupported format automatically gets converted to 8-bit unsigned images.
Conclusion
In this tutorial, we discussed the imwrite()
function of the opencv
library. We demonstrated how the parameter this function accepts and how it can be used to save images in Python.
We also discussed the formats of the images this function can work with and how it deals with unsupported formats.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn