After debugging the code, I found out the section of the code that causes the problem
change this
imr=Mat::zeros(256,256,CV_32F);
imd=Mat::zeros(256,256,CV_32F);
im3.copyTo(imd(Rect(0,0,128,128)));
im4.copyTo(imd(Rect(0,127,128,128)));
im5.copyTo(imd(Rect(127,0,128,128)));
im6.copyTo(imd(Rect(127,127,128,128)));
to this
imr=Mat::zeros(512,512,CV_32F);
imd=Mat::zeros(512,512,CV_32F);
im3.copyTo(imd(Rect(0,0,256,256)));
im4.copyTo(imd(Rect(0,255,256,256)));
im5.copyTo(imd(Rect(255,0,256,256)));
im6.copyTo(imd(Rect(255,255,256,256)));