imwrite()函数用于输出图像到文件。
imwrite()格式:
bool imwrite(const string& filename, InputArray img, const vector<int>& params=vector<int>())
参数说明:
第一个参数:const string&类型的filename,指写入的文件名。需要带上后缀,如“123.jpg”。
第二个参数:InputArray类型的img,一个mat类型的图像数据。
第三个参数:constvector<int>(),一般情况下不需要填写。如果需要填写,有下面需要了解:
- 对于JPEG格式的图片,这个参数从0到100的图片质量(CV_IMWRITE_JPEG_QUALITY),默认值是95。
- 对于PNG格式的图片,这个参数表示压缩级别(CV_IMWRITE_PNG_COPRESSION)从0到9。较高的值表示更小的尺寸和更长的压缩时间,默认值时3。
- 对于PPM,PGM,或PBM格式的图片,这个参数表示一个二进制格式标志(CV_IMWRITE_PXM_BINARY),取值0或1,默认值时1。
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(IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
//显示图片
try{
imwrite("透明Alpha值图.png", mat, compression_params);
imshow("生成的png图", mat);
fprintf(stdout, "PNG图片文件的alpha数据保存完毕~\n可以在工程目录下查看由imwrite函数生成的图片\n");
waitKey(0);
}
catch (runtime_error& ex) {
fprintf(stderr, "图像转换成PNG格式发生错误:%s\n", ex.what());
return 1;
}
return 0;
}
运行结果: