将图像放在项目工程里,本程序将图像分割成64*64大小的子图像。先看结果图:
当然,可以用能整除图片的宽和高的其他数字代替代码中所有64,来改变子图大小。
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>
using namespace std;
using namespace cv;
//出现to_string重载时的模板!
#include <string>
#include <type_traits>
namespace std
{
template<typename T>
typename enable_if<is_convertible<T, _Longlong>::value, string>::type to_string(T rhs)
{
return to_string(static_cast<_Longlong>(rhs));
}
}
void main()
{ //设置分割后图像存储路径
string outpath = "E:\\result\\";
Mat img = imread("girl_1088x768.jpg"); //将图像放在项目工程里,使用imread函数读取
int t = 0;
int m = img.cols / 64; //m*n是切割后子图像的个数
int n = img.rows /64;
Vector<Mat> ceil_img; //迭代器ceil_img存储子图像
Vector<int> name; //迭代器name存储子图像的名字,从0到m*n-1
for (t; t < m*n; t++)
name.push_back(t);
Mat image_cut, roi_img, tim_img;
for (int j = 0; j <n; j++)
{
for (int i = 0; i < m; i++)
{
Rect rect(i * 64, j * 64, 64, 64);
image_cut = Mat(img, rect);
roi_img = image_cut.clone();
ceil_img.push_back(roi_img);
}
}
for (int t=0; t < m*n;t++)
imwrite(outpath +to_string(name[t])+".png", ceil_img[t]);
}