显示一幅图片
我们首先将图片文件用imread
读取然后存储到Mat
类的对象中。
#include <iostream>
#include <opencv2\opencv.hpp>
using namespace cv;
int main() {
Mat img = imread("avatar.jpg");
// 在窗口中显示avatar
imshow("avatar", img);
// 等待按下任意键
waitKey(0);
}
Mat类是用于保存图像以及其他矩阵数据的数据结构,默认情况下大小为0.我么可以为其设置初始值,例如
Mat picture(320, 640, Scalar(100));
imread函数
关于imread
函数,函数原型如下:
Mat imread(const string& filename, int flag = 1);
它的第一个参数filename
,填入我们需要读取图片的路径。在windows下支持如下类型的加载:
- Windows bitmaps - .bmp, .dib (always supported)
- JPEG files - .jpeg, .jpg, .jpe (see the *Notes section)
- JPEG 2000 files - .jp2 (see the *Notes section)
- Portable Network Graphics - .png (see the *Notes section)
- WebP - .webp (see the *Notes section)
- Portable image format - .pbm, .pgm, .ppm .pxm, *.pnm (always supported)
- Sun rasters - .sr, .ras (always supported)
- TIFF files - .tiff, .tif (see the Notes section)
- OpenEXR Image files - .exr (see the *Notes section)
- Radiance HDR - .hdr, .pic (always supported)
- Raster and Vector geospatial data supported by Gdal (see the Notes section)
第二个参数flag的设置,我们通过查看imgcodecs.hpp
(opencv3.3)可以知道如下的枚举变量,默认情况下设置为1(IMREAD_COLOR)。
enum ImreadModes {
IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image.
IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image.
IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format.
IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image.
IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image