Home » OpenCV Read and Save Images

OpenCV Read and Save Images

by Online Tutorials Library

OpenCV Read and Save Image

OpenCV Reading Images

OpenCV allows us to perform multiple operations on the image, but to do that it is necessary to read an image file as input, and then we can perform the various operations on it. OpenCV provides following functions which are used to read and write the images.

OpenCV imread function

The imread() function loads image from the specified file and returns it. The syntax is:

Parameters:

filename: Name of the file to be loaded

flag: The flag specifies the color type of a loaded image:

  • CV_LOAD_IMAGE_ANYDEPTH – If we set it as flag, it will return 16-bits/32-bits image when the input has the corresponding depth, otherwise convert it to 8-BIT.
  • CV_LOAD_IMAGE_COLOR – If we set it as flag, it always return the converted image to the color one.
  • C V_LOAD_IMAGE_GRAYSCALE – If we set it as flag, it always convert image into the grayscale.

The imread() function returns a matrix, if the image cannot be read because of unsupported file format, missing file, unsupported or invalid format. Currently, the following file formats are supported.

Window bitmaps – *.bmp, *.dib
JPEG files – *.jpeg, *.jpg, *.jpe
Portable Network Graphics – *.png
Portable image format– *.pbm, *.pgm, *.ppm
TIFF files – *.tiff, *.tif

Note: The color images, the decoded images will have the channels stored in the BGR order.

Let’s consider the following example:

Output: it will display the following image.

OpenCV Reading Images

OpenCV Save Images

OpenCV imwrite() function is used to save an image to a specified file. The file extension defines the image format. The syntax is the following:

Parameters:

filename- Name of the file to be loaded

image- Image to be saved.

params- The following parameters are currently supported:

  • For JPEG, quality can be from 0 to 100. The default value is 95.
  • For PNG, quality can be the compress level from 0 to 9. The default value is 1.
  • For PPM, PGM, or PBM, it can be a binary format flag 0 or 1. The default value is 1.

Let’s consider the following example:

Output:

Image written to file-system : True  

If the imwrite() function returns the True, which means the file is successfully written in the specified file.


You may also like