输出图像到文件——imwrite函数

#include <vector>
#include <stdio.h>
#include<opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void createAlphaMat(Mat &mat)
{
	for (int i = 0; i < mat.rows; ++i) {
		for (int 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 - i)) / ((float)mat.rows) *UCHAR_MAX);
			rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
		}
	}
}

int main()
{
	//创建带alpha通道的Mat
	Mat mat(480, 640, CV_8UC4);
	createAlphaMat(mat); //填充像素?

	vector<int>compression_params;
	compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);//设置compression_params为 CV_IMWRITE_PNG_COMPRESSION 9
	compression_params.push_back(9);

	try{
		imwrite("透明Alpha值图.png", mat, compression_params);//存储为透明Alpha值图.png mat类型
	}
	catch (runtime_error& ex) {
		fprintf(stderr, "图像转换成PNG格式发生错误:%s\n", ex.what()); //捕获错误
		return 1;
	}

	fprintf(stdout, "PNG图片文件的alpha数据保存完毕~\n"); //窗口中输出文字
	return 0;
}

from:https://blog.csdn.net/poem_qianmo/article/details/20537737

猜你喜欢

转载自blog.csdn.net/zyckhuntoria/article/details/81319805