月度归档:2013年01月

MATLAB读写视频文件

做视频实验最基本的就是视频的读写操作了,写了两个简单的函数来读写视频。

读视频函数readVideo输入读取文件的路径+文件名,输出帧结构数组,用官方的话说就是 Array of frame structures, each of which contains fields cdata and colormap.

%// read vedio
function source = readVideo(filePath)
readerobj = VideoReader(filePath);

%// Read in all video frames.
vidFrames = read(readerobj);

%// Get the number of frames.
% numFrames = get(readerobj, 'NumberOfFrames');
[d1, d2, d3, d4] = size(vidFrames);

%// Create a MATLAB movie struct from the video frames.
for k = 1 : d4
     source(k).cdata = vidFrames(:,:,:,k);
     source(k).colormap = [];
end

写视频函数,cutVideo截取源视频的某部分,写到目标路径,写入的视频格式为avi

%// cut and write video file 
%// srcFile can be avi or mpg, destFile to be avi
function cv = cutVideo(srcFile, destFile, startIndex, endIndex)

source = readVideo(srcFile);
source2 = source(startIndex:endIndex);
writerObj = VideoWriter(destFile);
open(writerObj);
writeVideo(writerObj,source2);
close(writerObj);

cv = source2;

 

参考文章:

http://www.mathworks.cn/cn/help/matlab/ref/videowriter.writevideo.html