- Use ‘ImageDatastore’ to read images and labels.
- Use ‘splitEachLabel’ to separate them.
- Physically copy the files into new train and test folders, preserving the label structure.
Split image dataset into two separate folders
20 views (last 30 days)
Show older comments
Hello all,
I need to split an image dataset folder into two seperate folders.
In general i use :
imds = imageDatastore(dataset,...
'IncludeSubfolders',true,'LabelSource','foldernames');
[trainingSet, testSet] = splitEachLabel(imds, 0.7, 'randomize');
but how can I get the two seperate folders, because I need them for other processing things ?
More precisely, I want to divide each category folder to two separate folders one for training and one for test with a definite percentage rate (for example 30% of the category folder images are saved in test folder and the other 70% in training folder).
Thank you for your help!
0 Comments
Answers (1)
Parag
on 14 May 2025
Image dataset can be split into training and testing folders by physically copying the files into two separate directories for each class label. This method is useful when you need to use the separated folders for custom processing or external tools that expect a specific folder structure.
Please follow the below steps to achieve this:
% Source dataset folder (with subfolders per label)
sourceFolder = 'path_to_your_dataset';
% Destination folders
trainFolder = 'path_to_train_folder';
testFolder = 'path_to_test_folder';
% Create image datastore
imds = imageDatastore(sourceFolder, ...
'IncludeSubfolders', true, ...
'LabelSource', 'foldernames');
% Split datastore (70% train, 30% test)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.7, 'randomize');
% Function to copy files to new folder structure
copyImagesToFolder(imdsTrain, trainFolder);
copyImagesToFolder(imdsTest, testFolder);
disp('Images successfully copied to training and test folders.');
%% ------- Helper Function --------
function copyImagesToFolder(imds, destFolder)
% Ensure the destination folder exists
if ~exist(destFolder, 'dir')
mkdir(destFolder);
end
% Loop through all files
for i = 1:numel(imds.Files)
% Get image path and label
srcFile = imds.Files{i};
label = string(imds.Labels(i));
% Create subfolder if needed
destSubFolder = fullfile(destFolder, label);
if ~exist(destSubFolder, 'dir')
mkdir(destSubFolder);
end
% Copy image
[~, name, ext] = fileparts(srcFile);
destFile = fullfile(destSubFolder, [name ext]);
copyfile(srcFile, destFile);
end
end
You can refer to MATLAB documentation of ‘copyfile’ for more details:
Hope it helps!
0 Comments
See Also
Categories
Find more on Deep Learning Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!