图片压缩OpenCV
配置OpenCV环境
参见该链接:配置OpenCV环境
注意事项:
(1)解决方案平台那一栏要换成X64.
(2)选V15而不是V14.
(3)将opencv\build\x64\vc15\bin中的opencv_world450d.dll放在新建项目的x64\Debug中,否则会找不到dll.
测试代码
#include <string>
#include <iostream>
#include <opencv2/opencv.hpp>
static bool compressPicture(std::string file, int presslev = 4)
{
cv::Mat img = cv::imread(file);
if (!img.data)
{
printf("invalid image!\n");
return false;
}
int width = img.cols;
int height = img.rows;
int shorter = width > height ? height : width;
double ratio;
switch (presslev) {
case 1:
ratio = 0.2; break;
case 2:
ratio = 0.4; break;
case 3:
ratio = 0.6; break;
case 4:
ratio = 0.8; break;
default:
ratio = 0.2; break;
}
if (shorter * ratio <= 64) {
ratio = 64.0 / shorter;
cv::resize(img, img, cv::Size(width * ratio, height * ratio));
cv::imwrite(file, img);
return true;
}
else {
cv::resize(img, img, cv::Size(width * ratio, height * ratio));
cv::imwrite(file, img);
return true;
}
}
int main()
{
bool compress = compressPicture("图片路径", 3);
if (compress)
{
std::cout << "压缩成功!";
}
}