Search code examples
matlabvideomp4video-processingavi

Saving to .mp4 file in MATLAB


I'm editing all frames of an existing mp4 video in MATLAB (doing it in a for loop). After I'm done editing, I want to save the new set of frames to a new output video file, but in mp4 rather than .avi (that seems to be the default). I thought changing the filename extension is sufficient, but apparently it's not. Any ideas?

newVid = VideoWriter(outputfilename);
newVid.FrameRate = fps;
newVid.Quality = 100;
open(newVid)
for...
writeVideo(newVid,imgs{i})%within the for loop saving one frame at a time
end
close(newVid)

Solution

  • Renaming the file is not sufficient. You also need to specify the codec you want. In your case, you need to include an additional parameter into the VideoWriter constructor that consists of the codec you want to use as a MATLAB string. In your case, specify 'MPEG-4':

    newVid = VideoWriter(outputfilename, 'MPEG-4'); % New
    newVid.FrameRate = fps;
    newVid.Quality = 100;
    open(newVid);
    for ...
    % Rest of your code here
    

    BTW, have a look at the documentation in the future. It clearly shows you what to do if you want to save to a new format, and not AVI: https://www.mathworks.com/help/matlab/ref/videowriter.html#input_argument_d0e1094625