Search code examples
pythonopencvvideo-processing

How can I combine a multiple videos into one single video and set the position of them using Python


My problem is that, I have 4 videos and I would like to combine and fit them into one single video and play them at once using Python. Each of the video are set in the position (e.g. top, bottom, left, right) like a hologram video like this. Are there any ways which can help me implement this? I've found some related source which is similar to my problem but I cannot manage to apply it for my problem.

Thank you in advance


Solution

  • You can try to merge all images together by copying them into one black frame. Here is an example with the same image in all 4 places:

    import cv2
    import numpy as np
    
    #loads images and gets data
    img = cv2.imread("img.png")
    h,w,_ = img.shape    
    
    # creates the resulting image with double the size and 3 channels 
    output = np.zeros((h * 2, w * 2, 3), dtype="uint8")
    
    # copies the image to the top left
    output[0:h, 0:w] = img 
    # copies the image to the top right
    output[0:h, w:w * 2] = img 
    # copies the image to the bottom left
    output[h:h * 2, w:w * 2] = img 
    # copies the image to the bottom right
    output[h:h * 2, 0:w] = img 
    

    You can always change the img to something different. Also you can concatenate them like this:

    top = np.hstack((img, img))
    bottom = np.hstack((img, img))
    result = np.vstack((top, bottom))
    

    And the result will be the same.

    Here as sample of the resulting img with this code: enter image description here

    However your image is a little bit different, you will need a rotation and is not exactly concatenation, but the copying one. An example of this follows:

    # creates the resulting image with double the size and 3 channels 
    output = np.zeros((w+h+h , w + h + h, 3), dtype="uint8")
    
    # top img
    output[0:h, h:h+w] = img 
    # left img (rotated 90°)
    output[h:h+w, 0:h] = np.rot90(img,1) 
    # right img (rotated 270°)
    output[h:h + w, h + w:h +w +h] = np.rot90(img,3)  
    # bottom img (rotated 180°)
    output[h+w:h+w+h, h:h+w] = np.rot90(img,2) 
    

    and the result is like this:

    enter image description here

    If you use your image with the black background you will get more or less what you have there. You would need to play maybe with the copying parameters, but basically you do something like:

    imgToCopyTo[y1:y2, x1:x2] = imgToCopyFrom
    

    Where y1 and x1 is your top left coordinates where you want to start the copy and y2 and x2 are your bottom right coordinates of where you want to copy to. Also y2-y1 should have the height of the imgToCopyFrom x2-x1 the width (it can be bigger than the width or height but not smaller).