image_alignment.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. def get_gradient(im) :
  9. # Calculate the x and y gradients using Sobel operator
  10. grad_x = cv2.Sobel(im,cv2.CV_32F,1,0,ksize=3)
  11. grad_y = cv2.Sobel(im,cv2.CV_32F,0,1,ksize=3)
  12. # Combine the two gradients
  13. grad = cv2.addWeighted(np.absolute(grad_x), 0.5, np.absolute(grad_y), 0.5, 0)
  14. return grad
  15. if __name__ == '__main__':
  16. # Read 8-bit color image.
  17. # This is an image in which the three channels are
  18. # concatenated vertically.
  19. im = cv2.imread("images/emir.jpg", cv2.IMREAD_GRAYSCALE);
  20. # Find the width and height of the color image
  21. sz = im.shape
  22. print sz
  23. height = int(sz[0] / 3);
  24. width = sz[1]
  25. # Extract the three channels from the gray scale image
  26. # and merge the three channels into one color image
  27. im_color = np.zeros((height,width,3), dtype=np.uint8 )
  28. for i in xrange(0,3) :
  29. im_color[:,:,i] = im[ i * height:(i+1) * height,:]
  30. # Allocate space for aligned image
  31. im_aligned = np.zeros((height,width,3), dtype=np.uint8 )
  32. # The blue and green channels will be aligned to the red channel.
  33. # So copy the red channel
  34. im_aligned[:,:,2] = im_color[:,:,2]
  35. # Define motion model
  36. warp_mode = cv2.MOTION_HOMOGRAPHY
  37. # Set the warp matrix to identity.
  38. if warp_mode == cv2.MOTION_HOMOGRAPHY :
  39. warp_matrix = np.eye(3, 3, dtype=np.float32)
  40. else :
  41. warp_matrix = np.eye(2, 3, dtype=np.float32)
  42. # Set the stopping criteria for the algorithm.
  43. criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 5000, 1e-10)
  44. # Warp the blue and green channels to the red channel
  45. for i in xrange(0,2) :
  46. (cc, warp_matrix) = cv2.findTransformECC (get_gradient(im_color[:,:,2]), get_gradient(im_color[:,:,i]),warp_matrix, warp_mode, criteria)
  47. if warp_mode == cv2.MOTION_HOMOGRAPHY :
  48. # Use Perspective warp when the transformation is a Homography
  49. im_aligned[:,:,i] = cv2.warpPerspective (im_color[:,:,i], warp_matrix, (width,height), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
  50. else :
  51. # Use Affine warp when the transformation is not a Homography
  52. im_aligned[:,:,i] = cv2.warpAffine(im_color[:,:,i], warp_matrix, (width, height), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP);
  53. print warp_matrix
  54. # Show final output
  55. cv2.imshow("Color Image", im_color)
  56. cv2.imshow("Aligned Image", im_aligned)
  57. cv2.waitKey(0)