這篇文章只介紹對單張圖片進行合成處理,即利用單張圖片(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;
}