代码实现
强调一下:主要是用到了cv::imencode和cv::imdecode两个函数,具体的用法与cv::imread和cv::imwrite类似。 可参考opencv的相应API文档帮助理解:[Image file reading and writing] 使用函数cv2.imwrite(file,img,num)保存一个图像。第一个参数是要保存的文件名,第二个参数是要保存的图像。可选的第三个参数,它针对特定的格式:对于JPEG,其表示的是图像的质量,用0 - 100的整数表示,默认95;对于png ,第三个参数表示的是压缩级别。默认为3.
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
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!
";
return 0;
}
cv::Mat dest;
//质量等级为设为50
Jpegcompress(src,dest,50);
//
//cv2.IMWRITE_JPEG_QUALITY类型为 long ,必须转换成 int
//cv2.IMWRITE_PNG_COMPRESSION, 从0到9 压缩级别越高图像越小。
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(98);
cv::imwrite(1.png,src, params)
//cv::imwrite(1.png,src, [int(cv::IMWRITE_PNG_COMPRESSION), 9])
cvWaitKey(0);
return 0;
}
读取二进制文件
/**参考地址:https://www.cnblogs.com/rainbow70626/p/8371743.html**/
#include <string>
#include <stdio.h>
#include <iostream>
#include <opencv2/opencv.hpp>
//#include <opencv2/imgcodecs/legacy/constants_c.h>
typedef unsigned char uchar_t;
int read(){
uchar_t buf[300] = {
0 };
#ifdef _WIN32
FILE* pf = NULL;
errno_t err ;
if ((err = fopen_s(&pf, "conv.bin", "rb")) != 0) {
printf("The file conv.bin was not opened
");
return -1;
}
else {
fread_s(buf, 1024, sizeof(char), 253, pf);
}
if (fclose(pf)){
printf("The file ptr was not closed
");
}
#else
FILE* pf = fopen("conv.bin", "rb");
fread(buf, sizeof(char), 253, pf);
fclose(pf);
#endif
return 0;
}
int main(int argc, char** argv)
{
const char* binfilePath = "../1.jpg";
FILE* pFile;
#if _WIN32
size_t err = fopen_s(&pFile, binfilePath, "rb");
#else
pFile = fopen(binfilePath, "rb");
#endif
fseek(pFile, 0, SEEK_END);
long lSize = ftell(pFile);
rewind(pFile);
char* pData = new char[lSize];
fread(pData, sizeof(char), lSize, pFile);
fclose(pFile);
//! 解码内存数据,变成cv::Mat数据
std::vector<uchar> data;
for (int i = 0; i < lSize; ++i) {
data.push_back(pData[i]);
}
delete[] pData;
pData = NULL;
cv::Mat img = cv::imdecode(data, cv::IMREAD_COLOR);
cv::imshow("windows_0", img);
cv::waitKey(0);
return 0;
}
参考文献