图像的读取和显示以及Mat的理解

一、图像的读取和显示

  参考链接:http://blog.csdn.net/poem_qianmo/article/details/20537737

二、代码分析

  

 1 #include <vector>
 2 #include <stdio.h>
 3 #include<opencv2/opencv.hpp>
 4  
 5 using namespace cv;
 6 using namespace std;
 7  
 8 void createAlphaMat(Mat &mat)
 9 {
10 for(int i = 0; i < mat.rows; ++i) {
11         for(int j = 0; j < mat.cols; ++j) {
12                Vec4b&rgba = mat.at<Vec4b>(i, j);
13                rgba[0]= UCHAR_MAX;
14                rgba[1]= saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) *UCHAR_MAX);
15                rgba[2]= saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) *UCHAR_MAX);
16                rgba[3]= saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
17         }
18 }
19 }
20  
21 int main( )
22 {
23 //创建带alpha通道的Mat
24 Mat mat(480, 640, CV_8UC4);
25 createAlphaMat(mat);
26  
27 vector<int>compression_params;
28 compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
29 compression_params.push_back(9);
30  
31 try{
32         imwrite("透明Alpha值图.png", mat, compression_params);
33 }
34 catch(runtime_error& ex) {
35         fprintf(stderr,"图像转换成PNG格式发生错误:%s\n", ex.what());
36         return1;
37 }
38  
39 fprintf(stdout,"PNG图片文件的alpha数据保存完毕~\n");
40 return 0;
41 }
View Code

分析:

  Vec4b &rgba = mat.at<Vec4b>(i, j);

  分析:

    mat.at(i,j),从mat中取出一个像素,像素的类型是Vec4b,该类型含义是,有4个UCHAR类型的元素,

    其中rgba[0]、rgba[1]、rgab[2]代表像素的三原色,BGR,即为蓝色(Blue)、Green(绿色)、红色(Red)。

    rgba[3]代表像素的的Alpha值,表示像素的透明度。

posted @ 2018-01-10 17:01  马帅领  阅读(2730)  评论(0编辑  收藏  举报