opencv将图片分成多个256*256像素的小图片

想将一张大图片分成256*256像素的多个小图片,网上搜了很多资料,知道opencv的API中没有这样的函数,只能自己实现。

实现程序环境:

opencv版本:opencv2.4.4

编译环境:vs2010

操作系统:xp

我的实现方法有4步:

          1)将图片转化为长宽都是2的幂次的图片,使用resize函数。(根据本文的图片素材,转化成4096*2048像素)

cv::resize(img,result,cv::Size(4096,2048));

2)用for循环,从坐上角依次选取256*256的矩形ROI(感兴趣区域) 

3)将选取的ROI复制到临时tempimage中,添加到vector<cv::Mat>中

int m,n;
	m = image.rows/height;
	n = image.cols/width;
	vector<cv::Mat> imgOut;
	for (int j = 0;j<m;j++)
	{
		for(int i = 0;i<n;i++)
		{
			cv::Mat temImage(height,width,CV_8UC3,cv::Scalar(0,0,0));//mat(rows,cols,) 
			cv::Mat imageROI = image(cv::Rect(i*width,j*height,temImage.cols,temImage.rows));//rect(x, y, width, height)选定感兴趣区域
			cv::addWeighted(temImage,1.0,imageROI,1.0,0.,temImage);//复制扫描出的边界内数据
			imgOut.push_back(temImage);
		}
	}


4)最后将vector<cv::Mat>中的图片按顺序写入到jpg中

	vector<cv::Mat>::iterator it = imgDiv.begin();
	while(it!=imgDiv.end())
	{
		cv::imwrite(imagename,*it);
		if ((++imagename[2]) == 58)
		{
			imagename[2] = '0';
			if ((++imagename[1])==58)
			{
				imagename[1] = '0';
				imagename[0]++;
			} 
		}
		it++;
	}
程序代码:

astido.h

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>

using namespace cv;
using namespace std;

#define  Dst_img_width 256
#define  Dst_img_height 256
     division.h

#include "astdio.h"
#include <vector>

vector<cv::Mat>  division(cv::Mat &image,int width,int height);

division.cpp

#include "division.h"

vector<cv::Mat>  division(cv::Mat &image,int width,int height)
{
	char name = 1;
	int m,n;
	m = image.rows/height;
	n = image.cols/width;
	vector<cv::Mat> imgOut;
	for (int j = 0;j<m;j++)
	{
		for(int i = 0;i<n;i++)
		{
			cv::Mat temImage(height,width,CV_8UC3,cv::Scalar(0,0,0));//mat(rows,cols,) 
			cv::Mat imageROI = image(cv::Rect(i*width,j*height,temImage.cols,temImage.rows));//rect(x, y, width, height)选定感兴趣区域
			cv::addWeighted(temImage,1.0,imageROI,1.0,0.,temImage);//复制扫描出的边界内数据
			imgOut.push_back(temImage);
		}
	}
	return imgOut;
}

main.cpp

#include "astdio.h"
#include "division.h"

int main()
{
	string imagename = "000.jpg";
	cv::Mat img = cv::imread("image.jpg");
	if (!img.data)
	{
		cout<<"can't open img.jpg"<<endl;
		return -1;
	}
	cout<<"size of original.jpg is "<<img.cols<<"*"<<img.rows;
	cv::Mat result;
	cv::resize(img,result,cv::Size(4096,2048));
	cv::imwrite("result.jpg",result);
	vector<cv::Mat> imgDiv;
	imgDiv = division(result,Dst_img_width,Dst_img_height);
	vector<cv::Mat>::iterator it = imgDiv.begin();
	while(it!=imgDiv.end())
	{

		cv::imwrite(imagename,*it);
		if ((++imagename[2]) == 58)
		{
			imagename[2] = '0';
			if ((++imagename[1])==58)
			{
				imagename[1] = '0';
				imagename[0]++;
			}
			 
		}
		it++;
	}
}

源程序下载:

http://download.csdn.net/detail/skeeee/5322934


你可能感兴趣的:(opencv,图片分割)