2.5BGRA图像保存为PNG格式文件

目录

1.实验原理

2.实验代码

3.运行结果


1.实验原理

函数imwrite用来输出图像到文件

bool imwrite(const string& filename, InputArray image, const vector<int>& params=vector<int>());


参数说明如下:
filename:要保存的文件的名称。
image:要保存的图像。
params:格式特定的保存参数,以参数ID和参数值的配对形式传递,即 paramId_1, paramValue_1, paramId_2, paramValue_2, ...。目前支持的参数如下:
格式特定的保存参数
JPEG
CV_IMWRITE_JPEG_QUALITY:JPEG 图像的质量等级,范围为 0 到 100(数值越高,质量越好)。默认值为 95。
PNG
CV_IMWRITE_PNG_COMPRESSION:PNG 图像的压缩级别,范围为 0 到 9。数值越高意味着更小的文件大小和更长的压缩时间。默认值为 3。
PPM, PGM, 或 PBM
CV_IMWRITE_PXM_BINARY:是否使用二进制格式保存 PPM, PGM, 或 PBM 文件。可以是 0 或 1,其中 1 表示使用二进制格式。默认值为 1。

2.实验代码

//此项目未跑通!!!



#include <iostream>
#include <opencv2\opencv.hpp>
// comment(lib, "opencv_world450d.lib")  //引用引入库 
using namespace cv;
using namespace std;
static void createAlphaMat(Mat &mat)
{
	CV_Assert(mat.channels() == 4);
	for (int i = 0; i < mat.rows; ++i)
	{
		for (int j = 0; j < mat.cols; ++j)
		{
			Vec4b& bgra = mat.at<Vec4b>(i, j);
			bgra[0] = UCHAR_MAX; // Blue
			bgra[1] = saturate_cast<uchar>((float(mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
			bgra[2] = saturate_cast<uchar>((float(mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
			bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
		}
	}
}
int main()
{
	// Create mat with alpha channel
	//Mat mat(480, 640, CV_8UC4);
	Mat mat = imread("020.png");
	createAlphaMat(mat);
	vector<int> compression_params;
	compression_params.push_back(IMWRITE_PNG_COMPRESSION);
	compression_params.push_back(9);
	bool result = false;
	try
	{
		result = imwrite("alpha.png", mat, compression_params);
	}
	catch (const cv::Exception& ex)
	{
		fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
	}
	if (result)
		printf("Saved PNG file with alpha data.\n");
	else
		printf("ERROR: Can't save PNG file.\n");
	return result ? 0 : 1;
}

下面是一个使用这些参数的例子,展示如何保存一张 JPEG 图像,并设置 JPEG 的质量为 80:

#include <iostream>
#include <opencv2/opencv.hpp>

int main()
{
    cv::Mat image = cv::imread("input.jpg");//牛雪丽

    if (image.empty()) 
    {
        std::cerr << "Could not read the image" << std::endl;
        return -1;
    }

    std::vector<int> params;
    params.push_back(cv::IMWRITE_JPEG_QUALITY);
    params.push_back(80); // 设置 JPEG 质量为 80

    cv::imwrite("output.jpg", image, params);

    return 0;
}

3.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值