opencv实现图像的JPEG质量等级压缩

代码实现

  • 强调一下:主要是用到了cv::imencodecv::imdecode两个函数,具体的用法与cv::imreadcv::imwrite类似。
  • 可参考opencv的相应API文档帮助理解:Image file reading and writing
#include 
#include 
#include 
#include 

void Jpegcompress(const cv::Mat& src, cv::Mat& dest, int quality)
{
	std::vector<uchar> buff;
	std::vector<int> params;
	/*IMWRITE_JPEG_QUALITY For JPEG, it can be a quality from 0 to 100 
	(the higher is the better). Default value is 95 */
	params.push_back(cv::IMWRITE_JPEG_QUALITY);
	params.push_back(quality);
	//将图像压缩编码到缓冲流区域
	cv::imencode(".jpg", src, buff, params);
	//将压缩后的缓冲流内容解码为Mat,进行后续的处理
	dest = cv::imdecode(buff, -1);
	cv::imshow("src", src);
	cv::imshow("dst", dest);
}

int main()
{
	std::string fileName = "test.jpg";
	cv::Mat src = cv::imread(fileName, -1);
	if (src.empty())
	{
		std::cerr<<" image open error!\n";
		return 0;
	}
	cv::Mat dest;
	//质量等级为设为50
	Jpegcompress(src,dest,50);
	cvWaitKey(0);
	return 0;
}

参考文献

  • https://blog.csdn.net/dcrmg/article/details/79155233
  • opencv压缩与保存

你可能感兴趣的:(C++,机器学习)