本文用蒙版实现含透明通道的png文件的保存。
要保存透明通道图像必须有四通道,这里alpha通道值由蒙版提供,下列函数由一个图像和用作alpha的蒙版合成另一个包含alpha通道的图像,我们在蒙版上擦除的部分为255,但是这部分alpha为0,所以用255减去蒙版像素的值。
void ConvertToAlphaImage(const cv::Mat& srcMat, cv::Mat& destMat, const cv::Mat& alphaMat)
{
if (destMat.rows != srcMat.rows || destMat.cols != srcMat.cols || destMat.channels() != 4)
{
destMat = cv::Mat(srcMat.size(), CV_8UC4);
}
for (int i = 0; i < destMat.rows; ++i)
{
for (int j = 0; j < destMat.cols; ++j)
{
cv::Vec4b& destColor = destMat.at<cv::Vec4b>(i, j);
if (srcMat.channels() == 3)//srcMat判断有没有alpha通道
{
const cv::Vec3b& srcColor = srcMat.at<cv::Vec3b>(i, j);
destColor[0] = srcColor[0]; // Blue
destColor[1] = srcColor[1];; // Green
destColor[2] = srcColor[2];; // Red
}
else if (srcMat.channels() == 4)
{
const cv::Vec4b& srcColor = srcMat.at<cv::Vec4b>(i, j);
destColor[0] = srcColor[0]; // Blue
destColor[1] = srcColor[1];; // Green
destColor[2] = srcColor[2];; // Red
}
destColor[3] = 255-alphaMat.at<uchar>(i, j); // Alpha
}
}
}
透明的地方一般是用灰白棋盘格显示,所以先