matlabvideomatlab-cvstavisplit-screen

Matlab - combine two videos into a single split-screen video


I have 2 videos I would like to play side by side in a split screen. They are same duration and dimensions. I found a code developed few years back to do the job. The problem is, it is full of errors maybe due to the fact I am using a newer Matlab version (2014a). The errors start from (%name of the new avi file) onward.

Can anyone please try and fix it:

% select two files:
[filename1,pathname1] = uigetfile('.avi','pick first AVI file');
[filename2,pathname2] = uigetfile('.avi','pick second AVI file');
file1 = fullfile(pathname1,filename1);
file2 = fullfile(pathname2,filename2);  
pdMovie1 = aviread(file1);
pdMovie2 = aviread(file2);
fileinfo1 = aviinfo(file1);
fileinfo2 = aviinfo(file2);

% check if AVI files have the same length and height:
if fileinfo1.NumFrames~=fileinfo2.NumFrames || ...
    fileinfo1.Height~=fileinfo2.Height
errordlg('files are not compatible!')
else
% inspired by Herbert Ramoser in Message-ID:
% <art0c0$l9fip$1@ID-148798.news.dfncis.de>
for i=1:size(pdMovie1,2)
  output(i).cdata = [pdMovie1(i).cdata, pdMovie2(i).cdata];
  output(i).colormap = pdMovie1(i).colormap;
end;

% name of the new avi file:
[pathstr,name,ext,versn] = fileparts(filename1);
newmoviename = [pathname1,name,'_combined', ...
                num2str(fileinfo1.FramesPerSecond;),ext];

% create the avi file:
movie2avi(output, newmoviename, ...
          'fps', fileinfo1.FramesPerSecond;, ...
          'compression', 'none');
close
end

Solution

  • If it is just for playing the videos side-by-side, this simplker code will work,

    close all
    clc
    clear
    
    vid1 = vision.VideoFileReader('video1.avi');
    vid2 = vision.VideoFileReader('video2.avi');
    vidP = vision.VideoPlayer;
    
    while ~isDone(vid1)
       frame1 = step(vid1);
       frame2 = step(vid2);
    
       frame = horzcat(frame1, frame2);
    
       step(vidP,frame);
    end
    
    release(vid1);
    release(vid2);
    release(vidP);
    

    UPDATE: I'm assuming both input videos have the same length and frame dimension.

    Ok, now if you want to record a new video from the first 2, with the same frame rate of the previous, it is better to use the following code,

    close all
    clc
    clear
    
    vid1 = VideoReader('video1.avi');
    vid2 = VideoReader('video2.avi');
    
    videoPlayer = vision.VideoPlayer;
    
    % new video
    outputVideo = VideoWriter('newvideo.avi');
    outputVideo.FrameRate = vid1.FrameRate;
    open(outputVideo);
    
    while hasFrame(vid1) && hasFrame(vid2)
        img1 = readFrame(vid1);
        img2 = readFrame(vid2);
    
        imgt = horzcat(img1, img2);
    
        % play video
        step(videoPlayer, imgt);
    
        % record new video
        writeVideo(outputVideo, imgt);
    end
    
    release(videoPlayer);
    close(outputVideo);