这篇文章只介绍对单张图片进行合成处理,即利用单张图片(1*1)合成指定(m*n)的图片,输出并保存到指定的文件夹,算是对之前文章 FreeImage库在C++与C#中的简单使用:的一个补充,这次主要利用了opencv库中rowRange()与colRange()函数,简单的讲就是对Mat型数据内存的一个简单组合应用。
rowRange():Creates a matrix header for the specified row span,以指定行距创建一个矩阵头指针
//C++: Mat Mat::rowRange(int startrow, int endrow) const
//C++: Mat Mat::rowRange(const Range& r) const
//Parameters
//startrow – An inclusive 0-based start index of the row span.
//endrow – An exclusive 0-based ending index of the row span.
//r – Range structure containing both the start and the end indices.
colRange()与上面类似,只不过是以列宽创建一个矩阵的头指针。利用一个(1*1)的图片合成一个(n*n)的图片的思路是:
1.利用rowRange()合成(n*1)的图片块。
2.利用colRange()将n个(n*1)的图片块合成一个(n*n)的图片。
convertTo():Converts an array to another data type with optional scaling.将矩阵数据按指定类型进行转换
//C++: void Mat::convertTo(OutputArray m, int rtype, double alpha=1, double beta=0 ) const
//Parameters
//m – output matrix; if it does not have a proper size or type before the operation, it is reallocated.
//rtype – desired output matrix type or, rather, the depth since the number of channels are the
//same as the input has; if rtype is negative, the output matrix will have the same type as the
//input.
利用rowRange或colRange选定对应的图像块内存空间,然后以convertTo进行数据的填充。
下面直接贴上代码:
#include <iostream>
#include <cv.h>
#include <highgui.h>
using namespace cv;
using namespace std;
//实现图片的拼接
int main()
{
Mat src=imread("show.png");
int row=src.rows;
int col=src.cols;
cout<<"The Image width and height:"<<"width:"<<col<<"height:"<<row<<endl;
int n=0;
cout<<"Please inout the n: "<<endl;
cin>>n;
if(n==0) {
cout<<"n is not the reasonable number"<<endl;
return 0;
}
Mat dst(n*row,n*col,src.type());
Mat ex1(row,col,src.type());
Mat temp1(n*row,col,src.type());
for(int i=0;i<n;i++) {
src.copyTo(ex1);
Mat tmp=temp1.rowRange(Range(i*src.rows,(i+1)*src.rows));
ex1.convertTo(tmp,src.type());
}
Mat ex2(row,n*col,src.type());
for(int i=0;i<n;i++) {
temp1.copyTo(ex2);
Mat tmp=dst.colRange(Range(i*temp1.cols,(i+1)*temp1.cols));
ex2.convertTo(tmp,src.type());
}
imwrite( "show_dst.png", dst );
//imshow("lena_src",src);
//imshow("lena_dst",dst);
waitKey();
return 0;
}