参考博主Doctor_FEI博客:https://blog.csdn.net/qq_44770178/article/details/111836956
其博客在MATLAB2018B运行时稍有bug,修改后直接点击运行,选择需要转换的 .mp4 文件打开即可
[filename1, pathname1] = uigetfile({'*.mp4';'*.avi';'*.*'},'File Selector'); % 获取MP4或者Avi格式的视频文件路径以及名称
video = VideoReader([pathname1,filename1]); % 读取视频
Framerate=video.FrameRate; % 获取视频帧率
bar = waitbar(0,'Please wait...'); % 设置进度条
start_time = 0; % 开始时间
end_time = 5; % 结束时间
if end_time>video.Duration
end_time=video.Duration;
end
start_frame=round(Framerate*start_time)+1; % 开始帧数
end_frame=round(Framerate*end_time); % 结束帧数
for i=start_frame:2:end_frame
frame=read(video,i); %读取第k帧画面
[I,map]=rgb2ind(frame,256); % 将RGB图像frame转换为索引图像I,map为关联颜色图
waitbar((i-start_frame)/(end_frame-start_frame),bar,['转换中',num2str(round((i-start_frame)*100/(end_frame-start_frame))),'%']);
if i==start_frame
imwrite(I,map,strcat(pathname1,filename1(1:end-4),'_gif.gif'),'gif','Loopcount',inf,'DelayTime',0.067);
else
imwrite(I,map,strcat(pathname1,filename1(1:end-4),'_gif.gif'),'gif','WriteMode','Append','DelayTime',0.067);
end
end
waitbar(1,bar,'finished');
close(bar);