I am doing CNN image classification, but i keep getting this error ; Error using trainNetwork Unexpected input size: All observations must have the same channel and spatial Di
11 次查看(过去 30 天)
显示 更早的评论
outputFolder=fullfile('seaTech');
rootFolder=fullfile(outputFolder,'seacreaturesDataset');
categories={'Crab','Shark','Starfish','Turtle','Octopus'};
imds=imageDatastore(fullfile(rootFolder,categories),'LabelSource','foldernames');
tbl=countEachLabel(imds)
figure;
perm = randperm(500,20);
for i = 1:20
subplot(4,5,i);
imshow(imds.Files{perm(i)});
end
img = readimage(imds,1);
size(img)
numTrainFiles = 75;
[imdsTrain,imdsValidation] = splitEachLabel(imds,numTrainFiles,'randomize');
layers = [
imageInputLayer([100 100 3])
convolution2dLayer(3,8,'Padding','same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(1,'Stride',1)
convolution2dLayer(3,16,'Padding','same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(1,'Stride',1)
convolution2dLayer(3,32,'Padding','same')
batchNormalizationLayer
reluLayer
fullyConnectedLayer(5)
softmaxLayer
classificationLayer];
options = trainingOptions('sgdm', ...
'InitialLearnRate',0.01, ...
'MaxEpochs',4, ...
'Shuffle','every-epoch', ...
'ValidationData',imdsValidation, ...
'ValidationFrequency',30, ...
'Verbose',false, ...
'Plots','training-progress');
net = trainNetwork(imdsTrain,layers,options)
2 个评论
KSSV
2023-1-23
What are the dimensions of your input images? They all should be of same size. If not consdier getting them into same size using imresize
回答(1 个)
TED MOSBY
2024-11-15,8:28
编辑:TED MOSBY
2024-11-18,19:50
The error means that there might be inconsistencies in the dimensions or channels of the images within your‘imageDatastore’. Even though you resized the images to[100 100], there can be differences in the number of channels (e.g., some images might be grayscale with a single channel, while others are RGB with three channels).
For that you can:
Ensure All Images Have 3 Channels:
for i = 1:size(d)
I = imread(fullfile(f, d(i,:)));
I = imresize(I, [100 100]);
if size(I, 3) == 1
I = cat(3, I, I, I); % Convert grayscale to RGB
end
imwrite(I, fullfile('NewShark', strcat(num2str(i), '.png')));
Verify All Images in the Datastore:
for i = 1:numel(imds.Files)
img = readimage(imds, i);
if size(img, 1) ~= 100 || size(img, 2) ~= 100 || size(img, 3) ~= 3
error('Image %d does not match the required size or channel count.', i);
end
end
Update the ImageDatastore:
imds = imageDatastore(fullfile(rootFolder, categories), 'LabelSource', 'foldernames');
Hope this helps!
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!