필터 지우기
필터 지우기

How to generate gifs using countourf and mutliply file inputs?

조회 수: 5 (최근 30일)
David Kaeser
David Kaeser 2021년 12월 8일
답변: Samay Sagar 2024년 2월 27일
Hello everyone
I have multiple binary inputs files with which I would like to generate a gif using countourf. The mutiply binary files are representing a solution to each timestep where the number of the timestep can vary. Each binary files is saved as "0_100_S_timestep_1.bin" ,"0_100_S_timestep_2.bin" and so one where the integer number at the end indicates the time step. Right now I try to generate the gif using the following code:
clear;
clc;
close('all')
x0=10;
y0=250;
width=1000;
height=200;
figure('Name', 'Temperature field')
fid = fopen('0_100_T_result.bin');
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
T = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(T')
colorbar;
set(gcf,'position',[x0,y0,width,height])
saveas(gcf,'T_10.png');
figure('Name', 'Streamfunction field')
fid = fopen('0_100_S_result.bin');
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
S = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(S')
colorbar;
set(gcf,'position',[x0,y0,width,height])
saveas(gcf,'Streamfunction_10.png');
figure('Name', 'Vorticity field')
fid = fopen('0_100_W_result.bin');
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
W = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(W')
colorbar;
set(gcf,'position',[x0,y0,width,height]);
saveas(gcf,'Vorticity_10.png');
load 0_100_uymax_vs_time.data;
load 0_100_uxmax_vs_time.data;
figure('Name', 'umax over time')
hold on
plot(X0_100_uxmax_vs_time,'DisplayName','ux_{max}');
plot(X0_100_uymax_vs_time,'DisplayName','uy_{max}');
ylabel('velocity')
xlabel('time')
legend
hold off
width=550;
height=400;
set(gcf,'position',[x0,y0,width,height])
saveas(gcf,'umax_vs_time_10.png');
h = figure;
filename = 'gif_10.gif';
for t=1:70 % t is the percent number in the file name
subplot(311)
fn = "0_100_T_timestep_"+t+".bin";
fid = fopen(fn); % file for t-th step
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
T = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(T');
colorbar;
title('Temperature') ;
subplot(312)
fn = "0_100_S_timestep_"+t+".bin";
fid = fopen(fn); % file for t-th stepfid = fopen('S.bin');
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
S = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(S');
colorbar;
title('Streamfunction') ;
subplot(313)
fn = "0_100_W_timestep_"+t+".bin";
fid = fopen(fn); % file for t-th stepfid = fopen('S.bin');
nx = fread(fid,1,'int32');
ny = fread(fid,1,'int32');
W = reshape(fread(fid,nx*ny,'double'),nx,ny);
fclose = (fid);
contourf(W');
colorbar;
title('Vorticity') ;
% Capture the plot as an image
frame = getframe(h);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
% Write to the GIF File
if t == 10
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
pause(0.2)
end
I however get now the following error message:
Warning: Contour not rendered for constant ZData
> In contourf (line 60)
In matlab_0_1 (line 81)
Error using wgifc
Can only append to GIF89a format GIFs.
Error in writegif (line 306)
wgifc(mat, map, filename,writemode,disposalmethod,delaytime,...
Error in imwrite (line 566)
feval(fmt_s.write, data, map, filename, paramPairs{:});
Error in matlab_0_1 (line 104)
imwrite(imind,cm,filename,'gif','WriteMode','append');
and now gif is created. How can I resolve this? And also how can I make the for loop such that it goes automatically over all time step until largest timestep in the files available?
All help is creatly appriaciated and many thanks already in advance.

답변 (1개)

Samay Sagar
Samay Sagar 2024년 2월 27일
Hi David,
The warning about constant “ZData” in the “contour” function suggests that at least one of your binary files may contain uniform data, which cannot produce a contour plot.
The error with “imwrite” indicates a problem with appending frames to the GIF file. The initial frame must be saved in the GIF89a format with the “Loopcount”, inf property to establish the animation. Subsequent frames should then be appended with “WriteMode”, “append”.
To automate the process of iterating over all available timesteps, you can utilize MATLAB's file listing functions to dynamically determine the number of timesteps.
Here’s how you can update your code:
clear;
clc;
close('all');
x0 = 10;
y0 = 250;
width = 1000;
height = 200;
filename = 'gif_10.gif';
h = figure('position', [x0, y0, width, height * 3]);
% Get a list of all files that match the pattern
files = dir('0_100_T_timestep_*.bin');
numFiles = length(files);
for i = 1:numFiles
% Extract the timestep number from the file name
[~, name, ~] = fileparts(files(i).name);
parts = strsplit(name, '_');
timestep = str2double(parts{end});
% Read and plot Temperature
subplot(311);
dataT = readBinaryData(['0_100_T_timestep_' num2str(timestep) '.bin']);
contourf(dataT');
colorbar;
title('Temperature');
% Read and plot Streamfunction
subplot(312);
dataS = readBinaryData(['0_100_S_timestep_' num2str(timestep) '.bin']);
contourf(dataS');
colorbar;
title('Streamfunction');
% Read and plot Vorticity
subplot(313);
dataW = readBinaryData(['0_100_W_timestep_' num2str(timestep) '.bin']);
contourf(dataW');
colorbar;
title('Vorticity');
% Capture the plot as an image
frame = getframe(h);
im = frame2im(frame);
[imind, cm] = rgb2ind(im, 256);
% Write to the GIF File
if i == 1
imwrite(imind, cm, filename, 'gif', 'Loopcount', inf);
else
imwrite(imind, cm, filename, 'gif', 'WriteMode', 'append');
end
pause(0.2); % Adjust this pause as needed
end
% Helper function to read binary data
function data = readBinaryData(filename)
fid = fopen(filename, 'r');
nx = fread(fid, 1, 'int32');
ny = fread(fid, 1, 'int32');
data = reshape(fread(fid, nx * ny, 'double'), nx, ny);
fclose(fid);
end
The above script now includes a helper function “readBinaryData” that reads the binary data files for temperature, streamfunction, and vorticity. It also automatically loops over all files that match the pattern “0_100_T_timestep_*.bin”. Adjust the pattern as necessary for your specific filenames.
For additional information about “imwrite” and “contourf” please refer to the following documentation:

카테고리

Help CenterFile Exchange에서 Colormaps에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by