MATLAB:如何以数字顺序命名for循环中的文件



我正在尝试将视频文件中的特定帧提取到图像中。此代码当前正在输出正确的图像,但文件的编号和名称顺序不正确。12个图像的输出文件名的顺序是:frame_0.tif、frame_8.tif、frame_3.tif等

function vid_to_img(NumImages,VideoFile)
VideoRead = VideoReader(VideoFile);
CurFrame = 0;
TotalFrames =  VideoRead.FrameRate*VideoRead.Duration; 
DFrames = fix(TotalFrames/NumImages); %change in frames
ImageFrames = (1:DFrames:TotalFrames); %selected frames
NewImg = (0:1:NumImages);
while hasFrame(VideoRead)
for i = NewImg %file number matrix
CurImage = readFrame(VideoRead);
CurFrame = CurFrame+1;
if ismember(CurFrame, ImageFrames)
imwrite(CurImage, sprintf('frame_%d.tif', i));
end
end

end
end

您应该在循环外添加一个计数器,并且只计算实际拍摄的帧:

output_idx = 0;
while hasFrame(VideoRead)
CurImage = readFrame(VideoRead);
CurFrame = CurFrame+1;
if ismember(CurFrame, ImageFrames)
output_idx = output_idx + 1;   % Only counting the frames you actually take
imwrite(CurImage, sprintf('frame_%d.tif', output_idx));
end
end

相关内容

  • 没有找到相关文章

最新更新