所需头文件
#include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
1.图像旋转
void rotateImage(const std::vector< std::string >& imageList,double angle)
{
for (auto& image : imageList) {
cv::Mat srcimage = cv::imread(image);
cv::Point2d center(srcimage.cols / 2.,srcimage.rows / 2.);
cv::Mat rot_Mat = cv::getRotationMatrix2D(center,angle,1.0);
cv::Rect bbox = cv::RotatedRect(center,srcimage.size(),angle).boundingRect();
rot_Mat.at<double>(0,2) += bbox.width / 2.0 - center.x;
rot_Mat.at<double>(1,2) += bbox.height / 2.0 - center.y;
cv::Mat dstimage;
if(srcimage.rows != 0 && srcimage.cols !=0) {
cv::warpAffine(srcimage,dstimage,rot_Mat,bbox.size());
//create new image name and load dstimage to disk
//给新的图片命名
std::vector<std::string> subStrings = splitString_STL(image,".");
if (subStrings.size() == 2) {
std::string anglestr = std::to_string(static_cast<int>(angle));
std::string newImageName = subStrings[0] + "_r" + anglestr + ".jpg";
// std::cout<<newImageName<<std::endl;
cv::imwrite(newImageName,dstimage);
}
}
// cv::imshow("src",srcimage);
// cv::imshow("dst",dstimage);
// cv::waitKey();
}
}
2.改变图像亮度/对比度
使用convertTo函数,调整alpha值是改变对比度,调整beta值是改变亮度,固定变量时将值设为1即可。
以改变亮度为例:
void changeBright(const std::vector< std::string >& imageList,int bright_beta)
{
for (auto& image : imageList) {
printf("%s\n","*-");
cv::Mat srcimage = cv::imread(image);
cv::Mat dstimage;
srcimage.convertTo(dstimage,srcimage.type(),1,bright_beta);
//给新的图片命名
std::vector<std::string> subStrings = splitString_STL(image,".");
if (subStrings.size() == 2) {
std::string betastr = std::to_string(bright_beta);
std::string newImageName = subStrings[0] + "_b" + betastr + ".jpg";
// std::cout<<newImageName<<std::endl;
cv::imwrite(newImageName,dstimage);
}
}
}
3.高斯滤波
一个函数搞定,调整Size可以得到不同效果。
void GaussianBlur(const std::vector< std::string >& imageList)
{
for (auto& image : imageList) {
printf("%s\n","*-");
cv::Mat srcimage = cv::imread(image);
cv::Mat dstimage;
cv::GaussianBlur(srcimage,dstimage,cv::Size(6,6),0,0);
//给新的图片命名
std::vector<std::string> subStrings = splitString_STL(image,".");
if (subStrings.size() == 2) {
std::string newImageName = subStrings[0] + "_g" + ".jpg";
// std::cout<<newImageName<<std::endl;
cv::imwrite(newImageName,dstimage);
}
}
}
4.改变宽高比
使用resize一个函数就可以了
void resizeImage(const std::vector< std::string >& imageList, float width_time, float height_time,int order)
{
for (auto& image : imageList) {
printf("%s\n","*-");
cv::Mat srcimage = cv::imread(image);
cv::Mat dstimage;
//宽度变成1/2则width_time设为0.5
cv::resize(srcimage,dstimage,cv::Size(),width_time,height_time);
//给新的图片命名
std::vector<std::string> subStrings = splitString_STL(image,".");
if (subStrings.size() == 2) {
std::string orderstr = std::to_string(order);
std::string newImageName = subStrings[0] + "_s" + orderstr + ".jpg";
// std::cout<<newImageName<<std::endl;
cv::imwrite(newImageName,dstimage);
}
}
}