MATLAB File Help: cv.imwrite Index
cv.imwrite

Saves an image to a specified file

cv.imwrite(filename, img)
cv.imwrite(filename, img, 'OptionName', optionValue, ...)

Input

Options

The following format-specific save parameters are currently supported:

For advanced uses, you can directly pass a vector of paramters:

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). Only 8-bit (or 16-bit unsigned uint16 in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with RGB channel order) images can be saved using this function. If the format, depth or channel order is different, use cv.cvtColor to convert it before saving. Or, use the universal cv.FileStorage I/O functions to save the image to XML or YAML format.

(If the chosen encoder does not support the depth of the input image, the image will be implicitly cast to 8-bit).

If the image cannot be saved (because of IO errors, improper permissions, unsupported or invalid format), the function throws an error.

It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image RGBA, 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.

Example

The sample below shows how to create such a RGBA image and store to PNG file. It also demonstrates how to set custom compression parameters:

% Create mat with alpha channel
nrows = 480; ncols = 640;
[I,J] = ndgrid(1:nrows, 1:ncols);
img = zeros(nrows, ncols, 4, 'uint8');
img(:,:,1) = uint8(255 * (nrows-I+1)/nrows);     % red
img(:,:,2) = uint8(255 * (ncols-J+1)/ncols);     % green
img(:,:,3) = uint8(255);                         % blue
img(:,:,4) = uint8(0.5 * sum(img(:,:,[1 2]),3)); % alpha

% save PNG file with alpha data
%imwrite(img(:,:,1:3), 'alpha.png', 'Alpha',img(:,:,4))
cv.imwrite('alpha.png', img, 'PngCompression',9, 'PngStrategy','RLE');
imfinfo('alpha.png')

% show image with alpha transparency
figure('Menubar','none', 'Color','k')
image(img(:,:,1:3), 'AlphaData',img(:,:,4))
axis image off
See also