opencv3实现一幅图像分割成多幅图像

 

#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;
}

 

 

 

 

 

这是我的分割结果


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值