Как сделать анимацию в матлабе
Перейти к содержимому

Как сделать анимацию в матлабе

Gif-анимация в MATLAB

Пример 1: пошаговое построение анимированной картинки

1. Нарисуем картинку

2. Захватим кадр

3. Преобразуем полноцветное изображение в палитровое

Полноцветное изображение хранится в f.cdata . Оно имеет размер NxMx3 . Вместо него получаем палитровое изображение im размера NxM , цвет каждого пиксела которого определяется цветовой картой (палитрой) map . 256 — ограничение на количество цветов в палитре (больше нам не нужно).

4. Задаем массив, в котором будем хранить кадры анимации

Результатом работы rgb2ind может быть двумерный или четырехмерный массив. Так что введение дополнительного (третьего) измерения — дело вынужденное. Значение индекса четвертого измерения ( 10 ) — количество кадров будущей анимации. Таким образом мы заранее резервируем место под массив im .

5. Цикл рисования и запоминания кадров

Рисуем очередной кадр, захватываем его ( getframe ) и добавляем в массив im .

6. Записываем полученную анимацию в файл

DelayTime — определяет время задержки между кадрами анимации, LoopCount задает число повторений. Один раз анимация воспроизводится всегда, так что LoopCount=0 означает, что анимация будет воспроизведена один раз, при LoopCount=1 анимация выполняется дважды и т.д. LoopCount=inf зацикливает анимацию (повторяет ее бесконечное число раз).

Теперь все вместе:

Пример 2: еще один способ создания анимации

Если нам понадобится дробные показатели степени, нужно будет ввести еще один индекс для элементов массива im , вместо k . Другой вариант — создать первый кадр изображения и постепенно добавлять к нему новые кадры.

Можно поместить оба imwrite в цикл, проверяя номер итерации: для первой итерации создается графический файл, для остальных в него добавляются кадры:

С помощью такого подхода реализована анимация простых методов сортировки.

Пример 3: анимация поверхности

Основная идея — та же, что и в примере 1.

Самое интересное в этом примере находится в строках:

Первая не позволяет изменится размеру кадра. Вторая — стирает изображение в текущих координатных осях, не изменяя при этом остальных свойств осей (принятое по умолчанию для nextplot значение replace «сбрасывает» все свойства осей в их значения по умолчанию).

Пример 4: анимация нескольких графиков в разных координатных осях

Пример 5: анимация нескольких графиков в общих координатных осях

Пример 6: анимация нескольких поверхностей

Объединим результаты примеров 3 и 4.

Обратите внимание, что здесь Loopcount=0 , так что анимация будет выполняться один раз.

Здесь может возникнуть следующая проблема: некоторое программы просмотра графических файлов, например, IrfanView, сами по умолчанию зацикливают анимацию. Так что если в результате выполнения этого примера вы получите зацикленную анимацию, то просто смените программу просмотра, например, на браузер.*

Читайте также

Комментарии

Дмитрий Храмов
Компьютерное моделирование и все, что с ним связано: сбор данных, их анализ, разработка математических моделей, софт для моделирования, визуализации и оформления публикаций. Ну и за жизнь немного.

Creating movies and animations using Matlab

Animation is a series of still images one after another. If you show these images together in rapid succession, the brain interprets them as continuous fluid motion.

The animation follows a similar workflow to that of creating a flip-flop book. A flip-flop book is a booklet with a series of images that gradually change from one page to the next.

When you view the pages quickly, the images appear to animate by simulating motion or some other change. Animation has a wide advantage and is widely used in the science and engineering field. It helps to bring ideas into real-life or give the context of the idea.

In this article, we will look at how you can create an animation using Matlab. We will also look at the various steps involved and use the Matlab inbuilt functions to make the activity simpler.

Prerequisites

To follow along with this tutorial, you will need:

    installed.
  • Proper understanding of MATLAB basics.

Animation in Matlab follows a workflow like that of creating a flipbook. The steps involved in creating an animation in Matlab are as follows:

  1. Run a simulation or generate data.
  2. Draw/render the scenario at some time t_k .
  3. Take a snapshot of the scenario.
  4. Advance time t_k to t_(k+1) .
  5. Saving the movie.

Note that you have to repeat steps 2 to 4 to keep going through building one frame or one page in the flipbook one at a time and saving it to the large flipbook before proceeding to step 5.

Matlab functions that can be important at each of the steps

1. Run a simulation or generate a data

Maybe you have a fancy flight simulator that will run a scenario, kick out all this data, and save it to a file. So all you need here is to load the data. It means that You use the load function here. Also, if you are familiar with Simulink, you know that you can run a Simulink model from a Matlab script to generate data using the sim function.

2. Drawing/ rendering the scenario at some point t_x

This deals with plotting or drawing one single frame of the animation. It means that you will use the plot functions such as plot , plot3 , surf . A couple of things that can be helpful include the hold on function for complicated scenarios or animations. Also, it helps to draw many figures on the same plot. Because of jamming the plot function inside the for loop, you have to periodically wipe the slate clean after every time. In this, we use the clf function.

3. Take a snapshot of the scenario

Once you have drawn one page of the flipbook, we want to grab that frame and save it into the large flipbook. Matlab has the function get frame for doing this.

4. Advance time tk to t(k+1)

Like we said before, If we put the process inside a for loop or a while loop, the step is automatically handled. If you have data that you are simulating that is very temporally timely spaced, you might have tons of data.

You may not want to plot every single point of your data since that will be a very dense movie. So we will implement the logic of skipping some data and using the continue function for this.

5. Saving the movie

To save the movie, we will use VideoWriter and WriteVideo functions.

Example

We want to animate the trajectory of a point. Let us say we run some simulations or have some equations that generate the trajectory at some point in the space. The position vector describing where the point is located at any given x , y , z location given time t is:

The range of t is from 0 to 2pi . If you look at that position vector long enough, you will see that it describes the particle moving in the upward elliptical single helix.

Implementation in Matlab

We create a script file for this and do the normal clearance of the workspace and the command window.

Now let us work through the five steps. As we said earlier, the time is going to go through from 0 to 2*pi and we will use 100 points for this.

Step 1

To generate 100 equally spaced points, we use the linspace function. We also define our x , y , and z positions.

Step 2

We then start a new figure using figure functions and use a for loop to extract data at the current time.

So that is the current location of the particle. Let us go ahead and plot this current location.

Step 3

To draw the entire trajectory, we execute the code below:

Let’s add the title and the labels to our plot and set the viewpoint.

Let us run the script and see what we have at this point.

the plot

We noticed from the image above that Matlab plotted all the points because we had the hold on function that kept on plotting and plotting.

One of the things that we need to do is to make a change. Our expectation is not to plot all the points but to have a point moving on the spiral. Now let us wipe the slate clean so that every time we are plotting, it is on a blank figure.

Step 4

To do this, add the code below after the k=length(t) so that we have:

If we run the code now, we will have:

the plot

Surprisingly, this, too, didn’t work. As we can see, it ended up drawing the very last image here, which is not what we expected. What we expect is a particle moving up a spiral. It did not happen because Matlab noticed that our plot command was inside a for loop.

Matlab is smart to realize that it will slow down if it draws every single image here in this loop. So it suppresses the plotting until you drop out of the loop and then render the very last seen.

Since that is not the behavior we need here, we will force Matlab to draw the image. We do this by using the drawnow function. This function forces Matlab to flush the graphics to plot this as it goes.

Let us now run the code:

the animated plot

Now it seems reasonable. Or, we can use the pause function. This function takes the pause time as the argument.

What we are doing now is watching flipbooks occur one time on our screen. This isn’t exactly what we would like to do here because we want to save the flipbook.

Let us call the getframe function to force the graphics to render and return a bitmap or matrix of the values of the current figure. This function works as the drawnow function.

Comment out the drawnow and have the code below:

When we run this program, every time it hits a point, it will grab the current picture and jam it into the variable movieVector . Thus, you will see a vector movieVector in the workspace when the program has completed running.

Step 5

The last step is saving the movie. We have a movie vector which is all our flipbook. We need to print it out as an actual .mp4 file. We use a videoWriter function that Matlab uses to do a lot of video writing operations. The argument for this function is the name of the movie and, in our case, curve .

Now, let’s go ahead and change the parameter, e.g. frame rate

We now need to open the video writer, write the movie, and close the file.

To locate your file, you look at the current folder in Matlab and locate it on your device and play it. In case your device cannot open a .avi file, there is an alternative for this. The alternative is specifying .mp4 to the videoWriter function, as shown below:

Conclusion

Matlab provides a better environment for performing the animations because of the in-built functions that makes this process quicker. Also, Matlab is very smart and performs specific operations automatically.

These operations are such as data generation. Movies and animations can be performed for more complex operations in the field of science. It helps to visualize the ideas in the field of science.

I hope this tutorial helps you create movies and animations using Matlab. Happy coding.

Как сделать анимацию в MATLAB и сохранить её в формате GIF

В прошлой заметке мы с вами создавали видеролик при помощи MATLAB. Иногда полезно иметь анимацию не в видео формате, а в виде популярного в интернете формата GIF.

За основу мы возьмём код и данные, которые использовали в вышеупомянутой заметке:

Напомню, что первая часть строит все нужные нам картинки (отдельные кадры будущего видео) и записывает их в переменную frame. Затем, используя эту самую переменную frame во второй части кода мы создаём их этих кадров видеоролик. Сейчас эта вторая часть нам не понадобится, мы теперь используем переменную frame для создания GIF. Давайте я сначала сразу приведу здесь готовый код, а уже потом сделаю некоторые пояснения:

Для уменьшения размера файла я взял только первые 10 дней.

Если вы не хотите разбираться, то можете прямо его использовать и не задумываться о деталях.

Итак, как вы наверное поняли, gif создаётся при помощи функции imwrite, которая создана, вообще говоря, для записи разных типов графических файлов, не только gif (png, jpg и т.п.).

GIF файл создаётся в несколько этапов, сначала создаётся первый кадр (он может остаться единственным, если нам не нужна анимация), в коде это отражено в строке, идущей сразу после «if n == 1». Затем остальные кадры анимации записываются в наш файл при помощи опции ‘WriteMode’,’append’.

Поскольку формат gif работает с индексированными цветами, то нам нужно перевести изображения из RGB в эти самые индексированные цвета, т.е. получить в нашем случае само изображение, которое будет записано в переменную A и карту цветов (т.е. какому цвету соответствует каждое число в переменной A), записанную в переменную map. Делает это всё функция rgb2ind. У нас, как вы видите, в качестве второго входного аргумента этой функции стоит число 256, это количество цветов, которые мы будем иметь в изображении. Если вам нужно уменьшить размер итогового файла, то вы может пожертвовать палитрой и создать гифку, состоящую из меньшего количества цветов. Например, так будет выглядить наша анимация, если мы оставим всего 8 цветов:

Также обратите внимание, что функция rgb2ind не поймёт, если вы попытаетесь скормить ей наши кадры, которые мы записывали в переменную frame, поэтому для начала мы должны перевести из в изображение при помощи функции frame2im.

Осталось только сказать, что ‘LoopCount’,Inf — означает, что наше изображение будет зацикленное, т.е. повторяться снова и снова, а ‘DelayTime’,1 — устанавливает задержку по времени между кадрами (в секундах).

Чтобы не пропустить новые материалы с рецептами по работе с океанологическими данными, подпишитесь на канал в Telegram: https://t.me/koldunovaleksey

Данные для заметки:

NCEP Reanalysis data provided by the NOAA/OAR/ESRL PSD, Boulder, Colorado, USA, from their Web site at https://www.esrl.noaa.gov/psd/

Kalnay et al., The NCEP/NCAR 40-year reanalysis project, Bull. Amer. Meteor. Soc., 77, 437-470, 1996

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *