Table of contents
1.
Introduction
2.
What is OpenCV cv2.imwrite() Method?
2.1.
Syntax
2.2.
Parameters
2.3.
Example
3.
cv2.imwrite Usage
4.
cv2.imwrite Image
5.
cv2.imwrite Options
6.
Under The Hood
7.
Frequently Asked Questions
7.1.
Why should I use the imwrite function instead of the PIL save function?
7.2.
What exceptions does the imwrite method throw?
7.3.
What is the OpenCV Imwrite default quality?
7.4.
What is the difference between Imwrite and Imshow in cv2?
8.
Conclusion
Last Updated: Jun 10, 2024
Easy

OpenCV cv2.imwrite() Method

Introduction

OpenCV stands for Open Source Computer Vision Library. It is a machine learning and computer vision software library and is available for free use. An image can be saved to any storage medium using the cv2.imwrite() method of OpenCV.

In this article, we will dive into the exciting world of OpenCV cv2.imwrite() Method.

OpenCV cv2.imwrite() Method

What is OpenCV cv2.imwrite() Method?

A software library called OpenCV is utilised for a variety of applications, including feature extraction and image processing. It was initially developed by Intel Inc. and has the ability to process frames, or the smallest unit of a video, in real-time. Overall, this library is an all-arounder of image and video processing.

Note: OpenCV is written in C++ and ∴ it’s one of the fastest CV libraries in the world.

At the high level, today’s highlight, the “cv2.imwrite(path, image_data)” function is just a function to save images in the local file system.

Syntax

The syntax is as follows: 

import cv2 as proc
eg = proc.imread( img_path, proc.IMREAD_GRAYSCALE )
## you did some complex image processing to identify cats
proc.imwrite( path_to_save_image_at, example_image, options)
## the options array is optional and is not even needed in many cases

Parameters

You can pass 3 arguments in this function:

  • Path to the directory in which the image will be stored (required).
     
  • Image object (NumPy array) (required).
     
  • Options (other optional parameters that are not needed in most cases).

Example

import cv2
image = cv2.imread('./data/images/img1.png', cv2.IMREAD_GRAYSCALE)
cv2.imwrite('./data/processed/images/proc1.png', image)

cv2.imwrite Usage

What’s the right time to use this method?

  • Processing batch images or real-time computer vision is a complex process. After this processing is done, only then the role of this method comes. Its use is to post-process the image based on the extension and in the end, save the image in the local file system.
     
  • Another use case of this function is debugging. While designing some image processing algorithms, bugs might occur. To see what's going on, the developer might need to see the processed image.
     
  • But even during this debugging use case, its purpose remains to save input images into the local storage.

cv2.imwrite Image

  • This argument expects a NumPy array that contains information about the image.
     
  • This array is contained in the variable in which you stored the image during imread
img = cv2.imread('./data.img2.png')

 

  • NumPy array is nothing but a regular array with some additional functions attached to it for better and faster image processing.

cv2.imwrite Options

You can provide several optional parameters as the third argument in the function. These options can be very useful in various cases like saving storage space, etc.

  • Option names consist of 3 parts:
    • IMWRITE - function name.
    • JPEG/PNG/WEBP/TIFF - image extension
    • COMPRESSION/QUALITY, etc - property
       
  • All 3 are in upper case and are connected by underscore ‘_’
  • Eg, IMWRITE_JPEG_QUALITY
  • These options can be accessed using cv2 - cv2.<option_name>
     
  • Passing an option:
    options = [option1, value, option2, value, ......]
    cv2.imwrite(path, image, options)
     
  • Commonly used options (classified by extension):
    • JPEG/WEBP
      • Image quality in %
      • Eg. [IMWRITE_JPEG_QUALITY, 50]
         
    • PNG
      • Image compression level
      • Eg. [COMPRESSION, 4]
         
    • TIFF
      • Image compression type
      • Values:
        • IMWRITE_TIFF_UNCOMPRESSED (no compression)
        • IMWRITE_TIFF_LZW
        • IMWRITE_TIFF_PACKBITS
      • [IMWRITE_TIFF_COMPRESSION, IMWRITE_TIFF_PACKBITS]

Under The Hood

The following things are done under the hood when you call the imwrite function:

  • The destination path is processed and the file extension is extracted from it.
     
  • If the input image and the output image had different formats, eg. jpg and png, it performs the necessary tasks to convert one into another.
     
  • If options are provided it processes the image according to them.
     
  • The image object is encoded into the required format using the correct codec library.
     
  • Now that everything is ready, it saves the image to your local file system.
     
  • It then unlocks any locked resources and closes connections.

Frequently Asked Questions

Why should I use the imwrite function instead of the PIL save function?

It provides many functions that are not provided by the ‘save’  function. It makes us consistent with cv2. It is much faster and optimised for the task of image post-processing and saving.

What exceptions does the imwrite method throw?

This method does not throw any exceptions. If it ends in an error, it simply returns False. Therefore you must be very careful while working with this method.

What is the OpenCV Imwrite default quality?

The OpenCV Imwrite default JPEG quality ranges from 0 to 100. The higher is the number, the better is the quality. Generally, 95 is the default value.

What is the difference between Imwrite and Imshow in cv2?

imwrite in OpenCV saves an image to disk, specifying its file format and quality, while imshow displays an image in a window for visualization. imwrite is for saving images, while imshow is for viewing them. Both are essential for image processing tasks, like saving processed images or displaying results.

Conclusion

In this article, we read about the cv2.imwrite method which is the go-to function if you’re using OpenCV in complete detail.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass