开发者

Reading and Cropping a frame from a movie in Matlab

I want to read the first frame of a movie, crop (discard) the upper half portion of the frame and then save this new (wanted) frame into a new movie,then second frame and so on.. how can I do this? So far I have tried this:

clc;
clear all;
obj=mmreader('2.avi');  % input movie file
mov=read(obj);
frames=get(obj,'numberOfFrames'); %get the number of frames
cmap=zeros(256,3);
for i=1:10
cmap(i,1)=(i-1)/255;
cmap(i,2)=(i-1)/255;
cmap(i,3)=(i-1)/255;
end;


aviobj=avifile('c:\new_movie_file.avi','compression','none','colormap',cmap);

for k = 1 : 10
I(k).cdata = mov(:,:,:,k);       %store frame information in an array vector
I(k).colormap = [];
end 



for j = 1 : 10
%get the first frame from the movie
%frame1=mov(1,k);
%extract the colour data AND crop
frame2=I(j).cdata(:,100:end);开发者_开发技巧   % I am confused how to write this statement properly to crop the image frame from desired row number
%add to avi file
aviobj=addframe(aviobj,frame2);
end;
%close file!
aviobj=close(aviobj);
implay(aviobj);   % It displays a movie which contains three separate overlaped frames(windows) of the original movie in distorted form


If you want to do it all at once without doing it in the loop...

%read the entire video
obj=VideoReader('2.avi');
mov=read(obj);
size(mov) %mov is in 4D matrix: [Height (Y), Width (X), RGB (color), frame] 

%determine the height of the video
vidHeight = obj.Height;

%only use the top half of the image:
mov_cropped=mov(1:vidHeight/2,:,:,:);
aviObj = VideoWriter('cropped_video.avi','Uncompressed AVI');

%save the cropped video
open(aviObj);
writeVideo(aviObj,mov_cropped);
close(aviObj);

Note that there is a problem for large avi files that by trying to read it in all at once, you can run out of memory. In this case, it is better to read in the file frame by frame, and write out the file frame by frame.

for k=1:obj.NumberOfFrames
  mov(k).cdata = read(xyloObj, k);
end

And to save the data after you have transformed it (note the order in the matrix will have changed)

vidObj = VideoWriter('cropped_video.avi');
open(vidObj);
for k=1:obj.NumberOfFrames
  imshow(mov(k));
  writeVideo(vidObj,currFrame);
end
close(vidObj);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜