save image to file with filename same as index in matlab

You can save an image to file in MATLAB using the imwrite function. To save the image with filename same as index, you can use a loop and index variable to construct the filename. Here's an example code:

main.m
% read images from directory
imgDir = 'path/to/images';
imgFiles = dir(fullfile(imgDir, '*.jpg')); % read only JPG files
numImages = numel(imgFiles);

% loop through images and save with filename same as index
for idx = 1:numImages
    % read image
    img = imread(fullfile(imgDir, imgFiles(idx).name));
    
    % save image with filename same as index
    filename = sprintf('%03d.jpg', idx); % format index to 3 digits with leading zeros
    imwrite(img, fullfile(imgDir, filename));
end
492 chars
15 lines

In this example, the loop iterates through all the JPG files in the specified directory and reads each image using the imread function. The loop variable idx is used to construct the filename using the sprintf function, which formats the index as a 3-digit number with leading zeros (e.g., 001.jpg, 002.jpg). Finally, the imwrite function is used to save the image to file with the constructed filename.

gistlibby LogSnag