Advertisement
dan-masek

Simple stitching in Python

Mar 18th, 2017
1,261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4. # ============================================================================
  5.  
  6. def find_overlap_start(left_img, right_img):
  7.     assert left_img.shape == right_img.shape
  8.     height, width = left_img.shape[:2]
  9.    
  10.     haystack = left_img
  11.     needle = right_img[:,0:width/2]
  12.  
  13.     res = cv2.matchTemplate(haystack, needle, cv2.TM_CCORR_NORMED)
  14.     min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
  15.  
  16.     return max_loc[0]
  17.  
  18.  
  19. def find_overlaps(images):
  20.     overlap_starts = []
  21.     for i in range(len(images) - 1):
  22.         overlap_starts.append(find_overlap_start(images[i], images[i+1]))
  23.     # And the last image is used whole
  24.     overlap_starts.append(images[-1].shape[1])
  25.     return overlap_starts
  26.  
  27.    
  28. # Simple stitch, no blending, right hand slice overlays left hand slice
  29. def stitch_images(images, overlap_starts):
  30.     height, width = images[0].shape[:2]
  31.     total_width = sum(overlap_starts)
  32.     result = np.zeros((height, total_width), np.uint8)
  33.  
  34.     current_column = 0
  35.     for i,start in enumerate(overlap_starts):
  36.         result[:,current_column:current_column+width] = images[i]
  37.         current_column += start
  38.        
  39.     return result
  40.    
  41. # ============================================================================
  42.  
  43. images = [cv2.imread("slice_%d.png" % i, 0) for i in range(4)]
  44.  
  45. overlap_starts = find_overlaps(images)
  46.  
  47. cv2.imwrite("slices_out.png", stitch_images(images, overlap_starts))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement