برای ایجاد تصویر با کانال شفافیت بایستی تصویر 4 کاناله ایجاد کنید 3 کانال اول به صورت BGR و کانال آخر هم مربوط به شفافیت هستش .
#include <vector>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void createAlphaMat(Mat &mat)
{
vector<Mat> imgs(4);
for (size_t n = 0; n < 4; n++)
imgs[n].create(mat.size(), CV_8UC1);
for (size_t n = 0; n < 3;n++)
for (int i = 0; i < mat.rows; ++i) {
uchar* row = imgs[n].ptr<uchar>(i);
for (int j = 0; j < mat.cols; ++j) {
// Vec4b& rgba = mat.at<Vec4b>(i, j);
//rgba[0] = 22;
if (n == 0)
row[j] = saturate_cast<uchar>((float(mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX);
else if (n == 1)
row[j] = saturate_cast<uchar>((float(mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX);
else if (n == 2)
row[j] = saturate_cast<uchar>(0.5 * (row[j-2] + row[j-1]));
}
}
Point center(mat.cols / 2, mat.rows / 2);
Size size(mat.cols / 2, mat.rows / 2);
imgs[3].setTo(255);
cv::ellipse(imgs[3],center, size,0,0,360, Scalar::all(200), -1);
merge(imgs, mat);
}
void createPng(){
// Create mat with alpha channel
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("d:\\alpha.png", mat, compression_params);
}
catch (runtime_error& ex) {
fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
return ;
}
fprintf(stdout, "Saved PNG file with alpha data.\n");
}
int main(){
createPng();
return 0;
}