#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;
int main(int, char* [])
{
Mat src, dst;
Mat src1, src2, dst1, dst2, hann;
if(src.cols != dst.cols || src.rows != dst.rows)
{
return -1;
}
src = imread("1.jpg");
dst = imread("2.jpg");
cvtColor(src, src1, COLOR_RGB2GRAY);
cvtColor(dst, dst1, COLOR_RGB2GRAY);
createHanningWindow(hann, src1.size(), CV_64F);
createHanningWindow(hann, dst1.size(), CV_64F);
src1.convertTo(src2, CV_64F);
dst1.convertTo(dst2, CV_64F);
Point2d shift = phaseCorrelate(src2, dst2, hann);
cout << "offset_x:" << shift.x << endl << "offset_y:" << shift.y << endl;
Mat roiImg1, roiImg2;
float roi1_x = abs(shift.x), /*roi1_y = abs(shift.y)*/ roi1_y = 0;
float roi1_w = src.cols - roi1_x, roi1_h = src.rows - roi1_y;
float roi2_x = 0, roi2_y = 0;
float roi2_w = roi1_w, roi2_h = roi1_h;
Rect rect1(roi1_x, roi1_y,roi1_w, roi1_h);
Rect rect2(roi2_x, roi2_y,roi2_w, roi2_h);
src(rect1).copyTo(roiImg1);
dst(rect2).copyTo(roiImg2);
//imshow("ROI_L", roiImg1);
//imshow("ROI_R", roiImg2);
//waitKey(100);
// Image blending
double alpha = 1.0, beta = 0.0;
alpha = abs(shift.x) / src.cols;
beta = 1.0 - alpha;
Mat imgTmp1, imgTmp2, imgTmp3;
Rect rect_src(0, 0, roi1_x, src.rows);
//Rect rect_olp(roi1_x, 0, roi1_w, src.rows);
Rect rect_dst(roi2_w, 0, (dst.cols - int(roi2_w)), dst.rows);
src(rect_src).copyTo(imgTmp1);
addWeighted(roiImg1, alpha, roiImg2, beta, 0, imgTmp2);
dst(rect_dst).copyTo(imgTmp3);
//imshow("roi_src", imgTmp1);
//imshow("roi_olp", imgTmp2);
//imshow("roi_dst", imgTmp3);
Mat imgResult(Size((src.cols + int(roi1_x)), src.rows), CV_8UC3);
for( int i=0, col=0; i< imgTmp1.cols, col < (int)roi1_x; i++, col++){
for( int j=0, row=0; j < imgTmp1.rows, row < imgResult.rows; j++, row++){
imgResult.at<Vec3b>(row, col) = imgTmp1.at<Vec3b>(j, i);
}
}
for(int i=0, col = (int)roi1_x; i < imgTmp2.cols, col < src.cols; i++, col++){
for(int j=0, row = 0; j < imgTmp2.rows, row < imgResult.rows; j++, row++){
imgResult.at<Vec3b>(row, col) = imgTmp2.at<Vec3b>(j, i);
}
}
for(int i=0, col = src.cols; i < imgTmp3.cols, col < (src.cols + dst.cols-int(roi2_w)); i++, col++){
for(int j=0, row = 0; j < imgTmp3.rows, row < imgResult.rows; j++, row++){
imgResult.at<Vec3b>(row, col) = imgTmp3.at<Vec3b>(j, i);
}
}
imshow("Stitched", imgResult);
waitKey(0);
return 0;
}