圖像的讀取和顯示以及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值,表示像素的透明度。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM