视频与图片序列之间的互相转换
将视频转换成图片时可以用VideoReader和imwrite函数;将图片序列转换成视频时使用VideoWriter函数。这里是一个matlab的demo程序。详细可见:
【https://cn.mathworks.com/help/matlab/examples/convert-between-image-sequences-and-video.html】
【https://cn.mathworks.com/help/matlab/examples/convert-between-image-sequences-and-video.html】
%建立一个临时目录用于存放图片序列
workingDir = tempname;
mkdir(workingDir)
mkdir(workingDir,'images')
%建立VideoReader用于从文件中读取图像帧
shuttleVideo = VideoReader('shuttle.avi');
ii = 1;
while hasFrame(shuttleVideo)
img = readFrame(shuttleVideo);
filename = [sprintf('%03d',ii) '.jpg'];
fullname = fullfile(workingDir,'images',filename);
imwrite(img,fullname) % Write out to a JPEG file (img1.jpg, img2.jpg, etc.)
ii = ii+1;
end
%找到文件夹下.jpg结尾的图像并将图像名字存在imageNames cell
imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}'; %省去循环的操作
%建立VideoWriter目标用于存放AVI视频
outputVideo = VideoWriter(fullfile(workingDir,'shuttle_out.avi'));
outputVideo.FrameRate = shuttleVideo.FrameRate;
open(outputVideo)
for ii = 1:length(imageNames)
img = imread(fullfile(workingDir,'images',imageNames{ii}));
writeVideo(outputVideo,img)
end
close(outputVideo)
shuttleAvi = VideoReader(fullfile(workingDir,'shuttle_out.avi'));
%建立一个movie结构将图片转化成movie frame
ii = 1;
while hasFrame(shuttleAvi)
mov(ii) = im2frame(readFrame(shuttleAvi));
ii = ii+1;
end
% 显示第一帧
f = figure;
f.Position = [150 150 shuttleAvi.Width shuttleAvi.Height];
ax = gca;
ax.Units = 'pixels';
ax.Position = [0 0 shuttleAvi.Width shuttleAvi.Height];
image(mov(1).cdata,'Parent',ax)
axis off
% 播放movie
movie(mov,1,shuttleAvi.FrameRate)