本代码缩放图片后图片清晰的保持不变
前提必须有opencv_world343的dll和lib库,版本随意选,一般安装的opencv软件只有64位的库,这是最操蛋的地方
#include <WINDOWS.H>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2//highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include <iostream>
#include <direct.h>
#include <io.h>
using namespace std;
#pragma comment(lib, "opencv_world343.lib")
//图片等比压缩
cv::Mat PicRatioCompre(cv::Mat &srcImage, float fWidth, float fHeight)
{
//获取输出图像分辨率
int nRows = cvRound(srcImage.rows * fWidth);
int nCols = cvRound(srcImage.cols * fHeight);
cv::Mat resultImage(nRows, nCols, srcImage.type());
for (int i = 0; i < nRows; i++)
{
for (int j = 0; j < nCols; j++)
{
//根据水平因子计算坐标,static_cast用于类型转换
int x = static_cast<int>((i + 1) / fWidth + 0.5) - 1;
//根据垂直因子计算坐标
int y = static_cast<int>((j + 1) / fHeight + 0.5) - 1;
resultImage.at<cv::Vec3b>(i, j) = srcImage.at<cv::Vec3b>(x, y);
}
}
return resultImage;
}
//加载所有图片用于等比压缩
void main()
{
intptr_t hFile = 0;
struct _finddata_t fileinfo;
vector<string> imagesVector;
vector<string> imagesNewVector;
string p;
std::string strPath;
std::string strNewPath;
strPath = "C:/Users/User/Desktop/标注工具纸筒侧面测试数据";
strNewPath = strPath + "_new";
bool flag = CreateDirectory(strNewPath.c_str(), NULL);
strPath += "/";
strNewPath += "/";
//获取所有jpg图片名
hFile = _findfirst(p.assign(strPath).append("/*.jpg").c_str(), &fileinfo);
if (hFile != -1) {
do {
imagesVector.push_back(strPath + fileinfo.name);//保存类名
imagesNewVector.push_back(strNewPath + fileinfo.name);//保存类名
} while (_findnext(hFile, &fileinfo) == 0);
}
//获取所有bmp图片名
hFile = _findfirst(p.assign(strPath).append("/*.bmp").c_str(), &fileinfo);
if (hFile != -1) {
do {
imagesVector.push_back(strPath + fileinfo.name);//保存类名
imagesNewVector.push_back(strNewPath + fileinfo.name);//保存类名
} while (_findnext(hFile, &fileinfo) == 0);
}
vector<std::string>::iterator iter = imagesVector.begin();
vector<std::string>::iterator iterNew = imagesNewVector.begin();
for (; iter != imagesVector.end(); iter++)
{
cv::Mat srcImage = cv::imread(*iter);
if (srcImage.empty())
{
return;
}
//cv::imshow("原图像", srcImage);显示图像
cv::Mat resultImage1 = PicRatioCompre(srcImage, 0.2, 0.2);//压缩为原图的五分之一
FILE * rgba_file = fopen((*iterNew).c_str(), "wb");
cv::imwrite(*iterNew, resultImage1);
iterNew++;
}
return;
}