opencv 图像的载入 显示 输出到文件
头文件和命名空间
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv;
Mat类
Mat girl=imread("girl.jpg"); //载入图像到Mat
图像的载入与显示
Mat girl = imread("girl.jpg"); //载入图像到Mat imshow("【1】动漫图", girl); //显示名为 "【1】动漫图"的窗口
图像的载入
CV_EXPORTS_W Mat imread( const string& filename, int flags=1 ); filename:文件名,文件路径 flags:指定一个加载图像的颜色类型
图像的显示
CV_EXPORTS_W void imshow(const string& winname, InputArray mat); winname:窗体的标识名称 mat:需要显示的图像
关于InputArray类型
typedef const _InputArray& InputArray; 把它简单的当成Mat类型即可
创建窗口
CV_EXPORTS_W void namedWindow(const string& winname, int flags = WINDOW_AUTOSIZE); winname:窗体的标识名称 flags :WINDOW_NORMAL,WINDOW_AUTOSIZE,WINDOW_OPENGL
输出图像到文件
CV_EXPORTS_W bool imwrite( const string& filename, InputArray img, const vector<int>& params=vector<int>()); filename:文件名 img:Mat数据类型 params:表示为特定格式保存的参数编码
#include <vector> #include <stdio.h> #include<opencv2/opencv.hpp> using namespace cv; using namespace std; //--------------------------------【createAlphaMat( )函数】-------------------------------- // 描述:创建带alpha通道的Mat //------------------------------------------------------------------------------------------------- void createAlphaMat(Mat &mat) { for(int i = 0; i < mat.rows; ++i) { for(int j = 0; j < mat.cols; ++j) { Vec4b&rgba = mat.at<Vec4b>(i, j); rgba[0]= UCHAR_MAX; rgba[1]= saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) *UCHAR_MAX); rgba[2]= saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) *UCHAR_MAX); rgba[3]= saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2])); } } } int main( ) { //创建带alpha通道的Mat Mat mat(480, 640, CV_8UC4); createAlphaMat(mat); vector<int>compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); //显示图片 try{ imwrite("透明Alpha值图.png", mat, compression_params); imshow("生成的png图", mat); fprintf(stdout, "PNG图片文件的alpha数据保存完毕~\n可以在工程目录下查看由imwrite函数生成的图片\n"); waitKey(0); } catch(runtime_error& ex) { fprintf(stderr,"图像转换成PNG格式发生错误:%s\n", ex.what()); return 1; } return 0; }