image_alignment_simple_example.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * OpenCV Image Alignment Example
  3. *
  4. * Copyright 2015 by Satya Mallick <spmallick@learnopencv.com>
  5. *
  6. */
  7. #include "opencv2/opencv.hpp"
  8. using namespace cv;
  9. using namespace std;
  10. int main(void)
  11. {
  12. // Read the images to be aligned
  13. Mat im1 = imread("images/image1.jpg");
  14. Mat im2 = imread("images/image2.jpg");
  15. // Convert images to gray scale;
  16. Mat im1_gray, im2_gray;
  17. cvtColor(im1, im1_gray, cv::COLOR_BGR2GRAY);
  18. cvtColor(im2, im2_gray, cv::COLOR_BGR2GRAY);
  19. // Define the motion model
  20. const int warp_mode = MOTION_EUCLIDEAN;
  21. // Set a 2x3 or 3x3 warp matrix depending on the motion model.
  22. Mat warp_matrix;
  23. // Initialize the matrix to identity
  24. if ( warp_mode == MOTION_HOMOGRAPHY )
  25. warp_matrix = Mat::eye(3, 3, CV_32F);
  26. else
  27. warp_matrix = Mat::eye(2, 3, CV_32F);
  28. // Specify the number of iterations.
  29. int number_of_iterations = 5000;
  30. // Specify the threshold of the increment
  31. // in the correlation coefficient between two iterations
  32. double termination_eps = 1e-10;
  33. // Define termination criteria
  34. TermCriteria criteria (TermCriteria::COUNT+TermCriteria::EPS, number_of_iterations, termination_eps);
  35. // Run the ECC algorithm. The results are stored in warp_matrix.
  36. findTransformECC(
  37. im1_gray,
  38. im2_gray,
  39. warp_matrix,
  40. warp_mode,
  41. criteria
  42. );
  43. // Storage for warped image.
  44. Mat im2_aligned;
  45. if (warp_mode != MOTION_HOMOGRAPHY)
  46. // Use warpAffine for Translation, Euclidean and Affine
  47. warpAffine(im2, im2_aligned, warp_matrix, im1.size(), INTER_LINEAR + WARP_INVERSE_MAP);
  48. else
  49. // Use warpPerspective for Homography
  50. warpPerspective (im2, im2_aligned, warp_matrix, im1.size(),INTER_LINEAR + WARP_INVERSE_MAP);
  51. // Show final result
  52. imshow("Image 1", im1);
  53. imshow("Image 2", im2);
  54. imshow("Image 2 Aligned", im2_aligned);
  55. waitKey(0);
  56. }