Search code examples
matlabfor-looppngtransformmat

How to make a single 256*256*N (double) .mat from multiple .png image


There are 100 PNG images,size=256*256,channel=1 Here is my test code(test for save 2 images in a mat):

label = {sprintf('%01d.png\n', 0:100)};
img = regexp(label{:}(1:end-1), '\n', 'split');
F1=im2double(imread(img{1}));
F2=im2double(imread(img{2}));
label=cat(1,F1,F2);`
save('test.mat', 'label')

-> The test.mat is 256X256X2 double

However,I want to save 100 images in the mat. My idea is F1~100 <=> 1~100.png then cat(1,F1,F2...F100),and save at last. So I try to use eval() in for loop create F1~100 to load 1~100.png correspondingly like this:

for i=1:100
    eval(["F",num2str(c),"=",im2double(imread(img_names{c}))]);
end

But it's not work. Any solution for this problem?


Solution

  • Just preallocate your matrix:

    last=im2double(imread(img_names{c}))
    F(:,:,length(img_names))=last;
    

    then just loop and fill

    for i=1:100
        F(:,:,i)=im2double(imread(img_names{i}));
    end
    

    This will only work for images that are the same size, and grayscale images.

    NOTE: eval is the worst MATLAB function and its highly discouraged by Mathworks themselves. Never use it.