#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void createAlphaMat(Mat& mat)
{
for (size_t i = 0; i < mat.rows; i++)
{
for (size_t 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 - j) / ((float)mat.rows)*UCHAR_MAX);
rgba[3] = saturate_cast<uchar>(0.5*(rgba[1] + rgba[2]));
}
}
}
int main()
{
Mat mat(480, 640, CV_8UC4, Scalar(0, 0, 0, 0));
createAlphaMat(mat);
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
imwrite("alpha.png", mat, compression_params);
return 0;
}
其中saturate_cast模板函数的作用是溢出保护