在Matlab中读取和裁剪电影中的帧

问题描述

| 我想阅读电影的第一帧,裁剪(丢弃)该帧的上半部分,然后将此新(想要的)帧保存到新电影中,然后再保存第二帧,依此类推..我该怎么做? 到目前为止,我已经尝试过了:
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
    

解决方法

如果您想一次完成所有操作而无需循环执行...
%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);
请注意,大型avi文件存在一个问题,即尝试一次全部读取它,可能会耗尽内存。在这种情况下,最好逐帧读取文件,然后逐帧写出文件。
for k=1:obj.NumberOfFrames
  mov(k).cdata = read(xyloObj,k);
end
并在转换后保存数据(请注意矩阵中的顺序将更改)
vidObj = VideoWriter(\'cropped_video.avi\');
open(vidObj);
for k=1:obj.NumberOfFrames
  imshow(mov(k));
  writeVideo(vidObj,currFrame);
end
close(vidObj);