image_alignment_simple_example.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/python
  2. '''
  3. OpenCV Image Alignment Example
  4. Copyright 2015 by Satya Mallick <spmallick@learnopencv.com>
  5. '''
  6. import cv2
  7. import numpy as np
  8. if __name__ == '__main__':
  9. # Read the images to be aligned
  10. im1 = cv2.imread("images/image1.jpg");
  11. im2 = cv2.imread("images/image2.jpg");
  12. # Convert images to grayscale
  13. im1_gray = cv2.cvtColor(im1,cv2.COLOR_BGR2GRAY)
  14. im2_gray = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
  15. # Find size of image1
  16. sz = im1.shape
  17. # Define the motion model
  18. warp_mode = cv2.MOTION_TRANSLATION
  19. # Define 2x3 or 3x3 matrices and initialize the matrix to identity
  20. if warp_mode == cv2.MOTION_HOMOGRAPHY :
  21. warp_matrix = np.eye(3, 3, dtype=np.float32)
  22. else :
  23. warp_matrix = np.eye(2, 3, dtype=np.float32)
  24. # Specify the number of iterations.
  25. number_of_iterations = 5000;
  26. # Specify the threshold of the increment
  27. # in the correlation coefficient between two iterations
  28. termination_eps = 1e-10;
  29. # Define termination criteria
  30. criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)
  31. # Run the ECC algorithm. The results are stored in warp_matrix.
  32. (cc, warp_matrix) = cv2.findTransformECC (im1_gray,im2_gray,warp_matrix, warp_mode, criteria)
  33. if warp_mode == cv2.MOTION_HOMOGRAPHY :
  34. # Use warpPerspective for Homography
  35. im2_aligned = cv2.warpPerspective (im2, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
  36. else :
  37. # Use warpAffine for Translation, Euclidean and Affine
  38. im2_aligned = cv2.warpAffine(im2, warp_matrix, (sz[1],sz[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP);
  39. # Show final results
  40. cv2.imshow("Image 1", im1)
  41. cv2.imshow("Image 2", im2)
  42. cv2.imshow("Aligned Image 2", im2_aligned)
  43. cv2.waitKey(0)