Before we can display an image in our window, we'll need to know how to load an image
from disk. The function for this is cvLoadImage()
:
IplImage* cvLoadImage( const char* filename, int iscolor = CV_LOAD_IMAGE_COLOR );
When opening an image, cvLoadImage()
does not look at
the file extension. Instead, cvLoadImage()
analyzes the
first few bytes of the file (aka its signature or
"magic sequence") and determines the appropriate codec using that. The second argument
iscolor
can be set to one of several values. By
default, images are loaded as three-channel images with 8 bits per channel; the optional
flag CV_LOAD_IMAGE_ANYDEPTH
can be added to allow loading
of non-8-bit images. By default, the number of channels will be three because the iscolor
flag has the default value of CV_LOAD_IMAGE_COLOR
. This means that, regardless of the number of channels in
the image file, the image will be converted to three channels if needed. The alternatives to
CV_LOAD_IMAGE_COLOR
are CV_LOAD_IMAGE_GRAYSCALE
and CV_LOAD_IMAGE_ANYCOLOR
. Just as CV_LOAD_IMAGE_COLOR
forces any image into a three-channel image, CV_LOAD_IMAGE_GRAYSCALE
automatically converts any image into a
single-channel image. CV_LOAD_IMAGE_ANYCOLOR
will simply
load the image as it is stored in the file. Thus, to load a 16-bit color image you would use
CV_LOAD_IMAGE_COLOR | CV_LOAD_IMAGE_ANYDEPTH
. If you
want both the color and depth to be loaded exactly "as is", you could instead use the
all-purpose flag CV_LOAD_IMAGE_UNCHANGED
. Note that
cvLoadImage()
does not signal a runtime error when it
fails to load an image; it simply returns a null pointer.
The obvious complementary function to cvLoadImage()
is cvSaveImage()
, which takes two arguments:
int cvSaveImage( const char* filename, const CvArr* image );
The first argument gives the filename, whose extension is used to determine the format
in which the file will be stored. The second argument is the name of the image to be stored.
Recall that CvArr
is kind of a C-style way of creating
something equivalent to a base-class in an object-oriented language; wherever you see
CvArr*
, you can use an IplImage*
. The cvSaveImage()
function will
store only 8-bit single- or three-channel images for most file formats. Newer back ends for
flexible image formats like PNG, TIFF or JPEG2000 allow storing 16-bit or even float formats
and some allow four-channel images (BGR plus alpha) as well. The return value will be
1
if the save was successful and should be 0
if the save was not.[41]
[41] The reason we say "should" is that, in some OS environments, it is possible to issue save commands that will actually cause the operating system to throw an exception. Normally, however, a zero value will be returned to indicate failure.
Get Learning OpenCV now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.