본문 바로가기

Software/MATLAB

MATLAB figure 창의 변화하는 그래프를 동영상(avi)으로 녹화/저장하기

MATLAB에서 많이 사용하는 plot 명령으로 그려진 figure에서 움직이는 그림을 구현하는 경우 MATLAB은 이를 AVI 형태로 저장하는 기능을 제공합니다. 이번에는 이 기능을 소개해 보겠습니다.

먼저 형식은

객체이름 = avifile('파일이름.avi')

<일반적 코드>

프레임이름 = getframe;
객체이름 = addframe(객체이름, 프레임이름);

객체이름 = close(객체이름);

의 형태입니다. 

순서는 avifile로 열고, getframe으로 프레임정보를 받고, addframe으로 프레임을 추가하고 close로 닫으면, avi화일이 만들어 집니다. 사용할 만한 예제로 예전에 올렸던 애니메이션 만들기라는 글에서 다루었던 내용(참조)을 대상으로 하겠습니다. 당시 그렸던 그림은


이었는데요. 저기서 빨간색 부분이 트랙을 따라 움직이는 것이었습니다. 이때 사용한 코드가

AniTest = figure('name','Animation Test','numbertitle','off');
x = [-3 -3.5  -4 -4 -3];
y = [1 1.5 1 -1 -1];
 
box = fill(x,y, 'r','EraseMode','normal');
grid on
hold on
axis([-5 5 -5 5]);
 
t = 0:0.01:2*pi;
plot(3*cos(t), 3*sin(t))
plot(17^0.5*cos(t), 17^0.5*sin(t))
plot((3.5^2+1.5^2)^0.5*cos(t), (3.5^2+1.5^2)^0.5*sin(t), 'c')
 
for t = 0:0.01:2*pi
    updatedX = [10^0.5*cos(-(t+pi+atan(1/3))) (3.5^2+1.5^2)^0.5*cos(-(t+pi+atan(3/7))) 17^0.5*cos(-(t+pi+atan(1/4))) 17^0.5*cos(-(t+pi-atan(1/4))) 10^0.5*cos(-(t+pi-atan(1/3)))];
    updatedY = [10^0.5*sin(-(t+pi+atan(1/3))) (3.5^2+1.5^2)^0.5*sin(-(t+pi+atan(3/7))) 17^0.5*sin(-(t+pi+atan(1/4))) 17^0.5*sin(-(t+pi-atan(1/4))) 10^0.5*sin(-(t+pi-atan(1/3)))];
    set(box, 'Xdata', updatedX,'Ydata', updatedY);
    drawnow;
    
    for i=1:5000000
        temp = i;
    end
end

입니다. 이 코드에서 for문앞 14번행쯤에 avifile을 삽입하고, getframe을 23번과 24번행 사이에 위치시키고, addframe코드를 그 다음으로, close를 마지막에 삽입하도록 하겠습니다. 그러면 실제로는

AniTest = figure('name','Animation Test','numbertitle','off');
x = [-3 -3.5  -4 -4 -3];
y = [1 1.5 1 -1 -1];
 
box = fill(x,y, 'r','EraseMode','normal');
grid on
hold on
axis([-5 5 -5 5]);
 
t = 0:0.01:2*pi;
plot(3*cos(t), 3*sin(t))
plot(17^0.5*cos(t), 17^0.5*sin(t))
plot((3.5^2+1.5^2)^0.5*cos(t), (3.5^2+1.5^2)^0.5*sin(t), 'c')

aviobj = avifile('test.avi');
 
for t = 0:0.01:2*pi
    updatedX = [10^0.5*cos(-(t+pi+atan(1/3))) (3.5^2+1.5^2)^0.5*cos(-(t+pi+atan(3/7))) 17^0.5*cos(-(t+pi+atan(1/4))) 17^0.5*cos(-(t+pi-atan(1/4))) 10^0.5*cos(-(t+pi-atan(1/3)))];
    updatedY = [10^0.5*sin(-(t+pi+atan(1/3))) (3.5^2+1.5^2)^0.5*sin(-(t+pi+atan(3/7))) 17^0.5*sin(-(t+pi+atan(1/4))) 17^0.5*sin(-(t+pi-atan(1/4))) 10^0.5*sin(-(t+pi-atan(1/3)))];
    set(box, 'Xdata', updatedX,'Ydata', updatedY);
    drawnow;
    
    for i=1:5000000
        temp = i;
    end
    
    mo = getframe;
    aviobj = addframe(aviobj, mo);
end

aviobj = close(aviobj);

이렇게 만들어 지는 군요. 그러면, 해당코드가 실행되는 current folder에 test.avi라는 화일이 생성되어 있을 겁니다. 결과를 한 번 보실까요...^^



이렇게 되는군요^^


반응형