#include <opencv2/opencv.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace cv;
using namespace std;
//切割成2*2个子图片
#define cut_rows 2
#define cut_cols 2
//数字量转变成字符串量子函数
string num2str(int i)
{
stringstream ss;
ss << i;
return ss.str();
}
//切割图片子函数
void CutPics(string path, string fileTarget,string fileName)
{
Mat srcImg = imread(path);
vector<Mat> ceilImg;
int height = srcImg.rows;
int width = srcImg.cols;
int ceil_height = (int)(height / cut_rows);
int ceil_width = (int)(width / cut_cols);
int ceil_down_height = height - (cut_rows - 1)*ceil_height;
int ceil_right_width = width - (cut_cols - 1)*ceil_width;
for (int i = 0; i<cut_rows - 1; i++)
for (int j = 0; j<cut_cols; j++)
{
if (j<cut_cols - 1)
{
Rect rect(j*ceil_width, i*ceil_height, ceil_width, ceil_height);
ceilImg.push_back(srcImg(rect));
}
else
{
Rect rect((cut_cols - 1)*ceil_width, i*ceil_height, ceil_right_width, ceil_height);
ceilImg.push_back(srcImg(rect));
}
}
for (int i = 0; i<cut_cols; i++)
{
if (i<cut_cols - 1)
{
Rect rect(i*ceil_width, (cut_rows - 1)*ceil_height, ceil_width, ceil_down_height);
ceilImg.push_back(srcImg(rect));
}
else //右下角这个图像块
{
Rect rect((cut_cols - 1)*ceil_width, (cut_rows - 1)*ceil_height, ceil_right_width, ceil_down_height);
ceilImg.push_back(srcImg(rect));
}
}
cout << "分块个数:" << ceilImg.size() << endl;
Mat dst;
for (int i = 0; i < ceilImg.size(); i++)
{
dst = ceilImg[i];
/*imwrite( "F:/pic/00.jpg", dst);*/
imwrite("F:/" + fileTarget + "/" + fileName +"-"+num2str(i+1) + ".jpg", dst);
imshow("dst", dst);
/*waitKey(0);*/
}
//waitKey(0);
}
//主函数
int main()
{
vector<string> paths;
for (int i = 0; i <= 7; i++)
{
string s = "F:/water/water." + num2str(i) + ".ppm";
paths.push_back(s);
}
for (int j = 0; j < paths.size(); j++)
{
CutPics(paths[j], "pic","water"+num2str(j));
}
return 0;
}
这是我的分割结果