Search code examples
matlabimage-processingvideo-capture

In Matlab, writing images to AVI without displaying using VideoWriter


I'm trying to write images within a loop to an AVI file. Right now, I'm using VideoWriter and getframe to achieve that goal. The code generally goes something like this:

FoodVideo = VideoWriter('tempp.avi');
FoodVideo.FrameRate = 25;
open(FoodVideo);
hh=figure('Visible','off');
for i=1:20
  imshow(example_image{i});
  hold on;
  text(100,100,sprintf('Frame Number: %d',i));
  hold off;
  currFrame = getframe(hh);
  writeVideo(FoodVideo,currFrame);
end
close(FoodVideo);

The problem is that getframe displays the image before writing it. I can't think of a way of incorporating the text into the image data, so I eliminated that way of handling the matter (using im2frame...). I know I can use avifile and addframe, but I want to use VideoWriter because matlab says avifile will be removed... Is there any way to write the images using VideoWriter without displaying first?

Another related question: When I run my code, it seems like I capture my screen instead of the figure; I recently switched a computer, and this started happening only in the new computer. Does anyone have a clue as to why that might be?

Thanks, Aviram


Solution

  • I managed to find a solution after some searching. I am using the hardcopy function to incorporate the text into the image data and then using im2frame I can change it into a format fit to be used with VideoWriter. This seems to work perfectly:

          orig_mode = get(hfig, 'PaperPositionMode');
          set(hfig, 'PaperPositionMode', 'auto');
          cdata = hardcopy(hfig, '-Dzbuffer', '-r0');
          set(hfig, 'PaperPositionMode', orig_mode);
          currFrame = im2frame(cdata);