Creating Image Datastore as a struct for codegen throwing an error
Show older comments
Hi,
I am trying to create an ImageDatastore object to initialize a bag of features and then run codegen on it. Documentation says I can create it as a struct but it still throws an error.
images = cell(numImages, 1);
labels = cell(numImages, 1);
for k = 0:numImages-1
filename = fullfile(imageFolder, sprintf('%04d.jpg', int32(k)));
images{k+1} = imread(filename);
labels{k+1} = sprintf('%04d.jpg', int32(k));
end
imds.Images = images;
imds.Labels = categorical(labels);
bag = bagOfFeatures(imds, 'CustomExtractor',CustomFeatureExtractor, ...
bowParams{:});
This is the error I get:
- It no longer gives me an error on codegen.
- It doesn't work with regular execution.
Error using bagOfFeatures/parseInputs (line 1005)
The value of 'imds' is invalid. Expected imds to be one of these types:
matlab.io.datastore.ImageDatastore
Instead its type was struct.
Error in
bagOfFeatures (line 119)
[imgSets, params] = bagOfFeatures.parseInputs(varargin{:});
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in
main_vSLAM_VisualHull_RaspPi (line 283)
bag = bagOfFeatures(imds, 'CustomExtractor',CustomFeatureExtractor, ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Am I doing something wrong here?
Answers (1)
Sahithi Kanumarlapudi
26 minutes ago
0 votes
Hi Sankar,
You're not doing anything wrong — this is expected behavior. The struct-based input is only supported in the code generation path, not during regular MATLAB execution.
When you run bagOfFeatures in MATLAB directly, it requires an actual ImageDatastore object. The codegen implementation accepts a struct with:
- Images — cell array of images (numeric arrays from imread)
- Labels (optional) — categorical vector
So your struct format is correct for codegen. For regular MATLAB execution (e.g., testing/prototyping), use an actual ImageDatastore:
imds = imageDatastore(imageFolder, 'FileExtensions', '.jpg');
bag = bagOfFeatures(imds, 'CustomExtractor', CustomFeatureExtractor, bowParams{:});
If you need the same code to work in both paths, you can use coder.target to branch:
if coder.target('MATLAB')
imds = imageDatastore(imageFolder, 'FileExtensions', '.jpg');
else
imds.Images = images;
imds.Labels = categorical(labels);
end
bag = bagOfFeatures(imds, 'CustomExtractor', CustomFeatureExtractor, bowParams{:});
This is the designed workflow — the struct is a codegen-only substitute since ImageDatastore objects are not supported for
code generation
Categories
Find more on Image Category Classification 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!