Knowpapa.com - a developer's blog

OpenCV: Interlacing Two Images

The code defines two method
1) interlace_two_images(img1, img2)
2) main() – which calls the above method to interlace two images named circle.jpg and polygon.jpg

import sys, os
import numpy as np
import cv2

def interlace_two_images(img1, img2):
  interlacedimg = np.zeros((img1.shape[0]+img2.shape[0], 
                            img1.shape[1],img1.shape[2]), dtype=np.uint8)
  interlacedimg[0::2,:,:]=img1
  interlacedimg[1::2,:,:]=img2
  return interlacedimg

def main():
  imagesdirectory = os.path.join('knowpapa')
  print "Interlace images circle.jpg and polygon.jpg"
  circle = cv2.imread(os.path.join(imagesdirectory, 'circle.jpg'))
  polygon = cv2.imread(os.path.join(imagesdirectory, 'polygon.jpg'))

  if circle == None or polygon == None:
    print "Error: missing circle.jpg/polygon.jpg in {}".format(imagesdirectory)
    sys.exit(0)

  interlacedcircleandpolygon = interlace_two_images(circle, polygon)

  if interlacedcircleandpolygon != None:
    cv2.imwrite(os.path.join(imagesdirectory, 'interlacedcircleandpolygon.jpg'),
                 interlacedcircleandpolygon)

if __name__ == "__main__":
    main()

Here’s the output of the program, assuming you have two images circle.jpg and polygon.jpg stored in a directory ‘knowpapa’ in the same directory as the code.

interlacedimages