OpenCV  4.10.0-pre
Open Source Computer Vision
Loading...
Searching...
No Matches
Modules | Classes | Functions
Image file reading and writing

Modules

 Flags used for image file reading and writing
 
 iOS glue
 
 MacOS(OSX) glue
 

Detailed Description

Classes

class  cv::ImageCollection
 To read Multi Page images on demand. More...
 

Functions

CV_EXPORTS_W bool cv::haveImageReader (const String &filename)
 Returns true if the specified image can be decoded by OpenCV.
 
CV_EXPORTS_W bool cv::haveImageWriter (const String &filename)
 Returns true if an image with the specified filename can be encoded by OpenCV.
 
CV_EXPORTS_W size_t cv::imcount (const String &filename, int flags=IMREAD_ANYCOLOR)
 Returns the number of images inside the give file.
 
CV_EXPORTS_W Mat cv::imdecode (InputArray buf, int flags)
 Reads an image from a buffer in memory.
 
CV_EXPORTS Mat cv::imdecode (InputArray buf, int flags, Mat *dst)
 
CV_EXPORTS_W bool cv::imdecodemulti (InputArray buf, int flags, CV_OUT std::vector< Mat > &mats, const cv::Range &range=Range::all())
 Reads a multi-page image from a buffer in memory.
 
CV_EXPORTS_W bool cv::imencode (const String &ext, InputArray img, CV_OUT std::vector< uchar > &buf, const std::vector< int > &params=std::vector< int >())
 Encodes an image into a memory buffer.
 
CV_EXPORTS_W Mat cv::imread (const String &filename, int flags=IMREAD_COLOR)
 Loads an image from a file.
 
CV_EXPORTS_W void cv::imread (const String &filename, OutputArray dst, int flags=IMREAD_COLOR)
 Loads an image from a file.
 
CV_EXPORTS_W bool cv::imreadmulti (const String &filename, CV_OUT std::vector< Mat > &mats, int flags=IMREAD_ANYCOLOR)
 Loads a multi-page image from a file.
 
CV_EXPORTS_W bool cv::imreadmulti (const String &filename, CV_OUT std::vector< Mat > &mats, int start, int count, int flags=IMREAD_ANYCOLOR)
 Loads a of images of a multi-page image from a file.
 
CV_EXPORTS_W bool cv::imwrite (const String &filename, InputArray img, const std::vector< int > &params=std::vector< int >())
 Saves an image to a specified file.
 
static CV_WRAP bool cv::imwritemulti (const String &filename, InputArrayOfArrays img, const std::vector< int > &params=std::vector< int >())
 multi-image overload for bindings
 

Function Documentation

◆ haveImageReader()

CV_EXPORTS_W bool cv::haveImageReader ( const String filename)
Python:
cv.haveImageReader(filename) -> retval

#include <opencv2/imgcodecs.hpp>

Returns true if the specified image can be decoded by OpenCV.

Parameters
filenameFile name of the image

◆ haveImageWriter()

CV_EXPORTS_W bool cv::haveImageWriter ( const String filename)
Python:
cv.haveImageWriter(filename) -> retval

#include <opencv2/imgcodecs.hpp>

Returns true if an image with the specified filename can be encoded by OpenCV.

Parameters
filenameFile name of the image

◆ imcount()

CV_EXPORTS_W size_t cv::imcount ( const String filename,
int  flags = IMREAD_ANYCOLOR 
)
Python:
cv.imcount(filename[, flags]) -> retval

#include <opencv2/imgcodecs.hpp>

Returns the number of images inside the give file.

The function imcount will return the number of pages in a multi-page image, or 1 for single-page images

Parameters
filenameName of file to be loaded.
flagsFlag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.

◆ imdecode() [1/2]

CV_EXPORTS_W Mat cv::imdecode ( InputArray  buf,
int  flags 
)
Python:
cv.imdecode(buf, flags) -> retval

#include <opencv2/imgcodecs.hpp>

Reads an image from a buffer in memory.

The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ).

See cv::imread for the list of supported formats and flags description.

Note
In the case of color images, the decoded images will have the channels stored in B G R order.
Parameters
bufInput array or vector of bytes.
flagsThe same flags as in cv::imread, see cv::ImreadModes.

◆ imdecode() [2/2]

CV_EXPORTS Mat cv::imdecode ( InputArray  buf,
int  flags,
Mat dst 
)
Python:
cv.imdecode(buf, flags) -> retval

#include <opencv2/imgcodecs.hpp>

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
bufInput array or vector of bytes.
flagsThe same flags as in cv::imread, see cv::ImreadModes.
dstThe optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size. In case of decoder failure the function returns empty cv::Mat object, but does not release user-provided dst buffer.

◆ imdecodemulti()

CV_EXPORTS_W bool cv::imdecodemulti ( InputArray  buf,
int  flags,
CV_OUT std::vector< Mat > &  mats,
const cv::Range range = Range::all() 
)
Python:
cv.imdecodemulti(buf, flags[, mats[, range]]) -> retval, mats

#include <opencv2/imgcodecs.hpp>

Reads a multi-page image from a buffer in memory.

The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns false.

See cv::imreadmulti for the list of supported formats and flags description.

Note
In the case of color images, the decoded images will have the channels stored in B G R order.
Parameters
bufInput array or vector of bytes.
flagsThe same flags as in cv::imread, see cv::ImreadModes.
matsA vector of Mat objects holding each page, if more than one.
rangeA continuous selection of pages.

◆ imencode()

CV_EXPORTS_W bool cv::imencode ( const String ext,
InputArray  img,
CV_OUT std::vector< uchar > &  buf,
const std::vector< int > &  params = std::vector< int >() 
)
Python:
cv.imencode(ext, img[, params]) -> retval, buf

#include <opencv2/imgcodecs.hpp>

Encodes an image into a memory buffer.

The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description.

Parameters
extFile extension that defines the output format. Must include a leading period.
imgImage to be written.
bufOutput buffer resized to fit the compressed image.
paramsFormat-specific parameters. See cv::imwrite and cv::ImwriteFlags.

◆ imread() [1/2]

CV_EXPORTS_W Mat cv::imread ( const String filename,
int  flags = IMREAD_COLOR 
)
Python:
cv.imread(filename[, flags]) -> retval
cv.imread(filename[, dst[, flags]]) -> dst

#include <opencv2/imgcodecs.hpp>

Loads an image from a file.

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

Currently, the following file formats are supported:

  • Windows bitmaps - *.bmp, *.dib (always supported)
  • JPEG files - *.jpeg, *.jpg, *.jpe (see the Note section)
  • JPEG 2000 files - *.jp2 (see the Note section)
  • Portable Network Graphics - *.png (see the Note section)
  • WebP - *.webp (see the Note section)
  • AVIF - *.avif (see the Note section)
  • Portable image format - *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
  • PFM files - *.pfm (see the Note section)
  • Sun rasters - *.sr, *.ras (always supported)
  • TIFF files - *.tiff, *.tif (see the Note section)
  • OpenEXR Image files - *.exr (see the Note section)
  • Radiance HDR - *.hdr, *.pic (always supported)
  • Raster and Vector geospatial data supported by GDAL (see the Note section)
Note
  • The function determines the type of an image by the content, not by the file extension.
  • In the case of color images, the decoded images will have the channels stored in B G R order.
  • When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available. Results may differ to the output of cvtColor()
  • On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX.
  • On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian* and Ubuntu*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake.
  • In the case you set WITH_GDAL flag to true in CMake and IMREAD_LOAD_GDAL to load the image, then the GDAL driver will be used in order to decode the image, supporting the following formats: Raster, Vector.
  • If EXIF information is embedded in the image file, the EXIF orientation will be taken into account and thus the image will be rotated accordingly except if the flags IMREAD_IGNORE_ORIENTATION or IMREAD_UNCHANGED are passed.
  • Use the IMREAD_UNCHANGED flag to keep the floating point values from PFM image.
  • By default number of pixels must be less than 2^30. Limit can be set using system variable OPENCV_IO_MAX_IMAGE_PIXELS
Parameters
filenameName of file to be loaded.
flagsFlag that can take values of cv::ImreadModes

◆ imread() [2/2]

CV_EXPORTS_W void cv::imread ( const String filename,
OutputArray  dst,
int  flags = IMREAD_COLOR 
)
Python:
cv.imread(filename[, flags]) -> retval
cv.imread(filename[, dst[, flags]]) -> dst

#include <opencv2/imgcodecs.hpp>

Loads an image from a file.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts and the return value.

Parameters
filenameName of file to be loaded.
dstobject in which the image will be loaded.
flagsFlag that can take values of cv::ImreadModes
Note
The image passing through the img parameter can be pre-allocated. The memory is reused if the shape and the type match with the load image.

◆ imreadmulti() [1/2]

CV_EXPORTS_W bool cv::imreadmulti ( const String filename,
CV_OUT std::vector< Mat > &  mats,
int  flags = IMREAD_ANYCOLOR 
)
Python:
cv.imreadmulti(filename[, mats[, flags]]) -> retval, mats
cv.imreadmulti(filename, start, count[, mats[, flags]]) -> retval, mats

#include <opencv2/imgcodecs.hpp>

Loads a multi-page image from a file.

The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects.

Parameters
filenameName of file to be loaded.
matsA vector of Mat objects holding each page.
flagsFlag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.
See also
cv::imread

◆ imreadmulti() [2/2]

CV_EXPORTS_W bool cv::imreadmulti ( const String filename,
CV_OUT std::vector< Mat > &  mats,
int  start,
int  count,
int  flags = IMREAD_ANYCOLOR 
)
Python:
cv.imreadmulti(filename[, mats[, flags]]) -> retval, mats
cv.imreadmulti(filename, start, count[, mats[, flags]]) -> retval, mats

#include <opencv2/imgcodecs.hpp>

Loads a of images of a multi-page image from a file.

The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects.

Parameters
filenameName of file to be loaded.
matsA vector of Mat objects holding each page.
startStart index of the image to load
countCount number of images to load
flagsFlag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.
See also
cv::imread

◆ imwrite()

CV_EXPORTS_W bool cv::imwrite ( const String filename,
InputArray  img,
const std::vector< int > &  params = std::vector< int >() 
)
Python:
cv.imwrite(filename, img[, params]) -> retval

#include <opencv2/imgcodecs.hpp>

Saves an image to a specified file.

The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function, with these exceptions:

  • With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved.
    • 8-bit unsigned (CV_8U) images are not supported.
  • With Radiance HDR encoder, non 64-bit float (CV_64F) images can be saved.
    • All images will be converted to 32-bit float (CV_32F).
  • With JPEG 2000 encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved.
  • With PAM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved.
  • With PNG encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved.
    • PNG images with an alpha channel can be saved using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below).
  • With PGM/PPM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved.
  • With TIFF encoder, 8-bit unsigned (CV_8U), 16-bit unsigned (CV_16U), 32-bit float (CV_32F) and 64-bit float (CV_64F) images can be saved.
    • Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below).
    • 32-bit float 3-channel (CV_32FC3) TIFF images will be saved using the LogLuv high dynamic range encoding (4 bytes per pixel)

If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way.

If the format, depth or channel order is different, use Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format.

The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. It also demonstrates how to save multiple images in a TIFF file:

using namespace cv;
using namespace std;
static void paintAlphaMat(Mat &mat)
{
CV_Assert(mat.channels() == 4);
for (int i = 0; i < mat.rows; ++i)
{
for (int j = 0; j < mat.cols; ++j)
{
Vec4b& bgra = mat.at<Vec4b>(i, j);
bgra[0] = UCHAR_MAX; // Blue
bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
}
}
}
int main()
{
Mat mat(480, 640, CV_8UC4); // Create a matrix with alpha channel
paintAlphaMat(mat);
vector<int> compression_params;
compression_params.push_back(IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
bool result = false;
try
{
result = imwrite("alpha.png", mat, compression_params);
}
catch (const cv::Exception& ex)
{
fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
}
if (result)
printf("Saved PNG file with alpha data.\n");
else
printf("ERROR: Can't save PNG file.\n");
vector<Mat> imgs;
imgs.push_back(mat);
imgs.push_back(~mat);
imgs.push_back(mat(Rect(0, 0, mat.cols / 2, mat.rows / 2)));
imwrite("test.tiff", imgs);
printf("Multiple files saved in test.tiff\n");
return result ? 0 : 1;
}
Class passed to an error.
Definition core.hpp:115
virtual const char * what() const CV_OVERRIDE
n-dimensional dense array class
Definition mat.hpp:812
_Tp & at(int i0=0)
Returns a reference to the specified array element.
int channels() const
Returns the number of matrix channels.
int cols
Definition mat.hpp:2138
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition mat.hpp:2138
Template class for short numerical vectors, a partial case of Matx.
Definition matx.hpp:369
Rect2i Rect
Definition types.hpp:489
#define CV_8UC4
Definition interface.h:91
uchar saturate_cast< uchar >(schar v)
Definition saturate.hpp:101
#define CV_Assert(expr)
Checks a condition at runtime and throws exception if it fails.
Definition base.hpp:342
@ IMWRITE_PNG_COMPRESSION
For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer ...
Definition imgcodecs.hpp:93
CV_EXPORTS_W bool imwrite(const String &filename, InputArray img, const std::vector< int > &params=std::vector< int >())
Saves an image to a specified file.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3
"black box" representation of the file storage associated with a file on disk.
Definition core.hpp:102
STL namespace.
Parameters
filenameName of the file.
img(Mat or vector of Mat) Image or Images to be saved.
paramsFormat-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags

◆ imwritemulti()

static CV_WRAP bool cv::imwritemulti ( const String filename,
InputArrayOfArrays  img,
const std::vector< int > &  params = std::vector<int>() 
)
inlinestatic
Python:
cv.imwritemulti(filename, img[, params]) -> retval

#include <opencv2/imgcodecs.hpp>

multi-image overload for bindings

Here is the call graph for this function: