You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matlab Augmented Image Datastore调图转灰度时维度不匹配报错

问题

需要将文件夹中所有图像调整为[224 224 3]尺寸并转为灰度图,使用augmentedImageDatastore设置ColorPreprocessing为rgb2gray后,图像维度变为224×224×1,与imageInputLayer要求的224×224×3不匹配,导致trainNetwork报错。

代码示例

aug_imds = augmentedImageDatastore([224 224 3], imdsTrain,'ColorPreprocessing', 'rgb2gray');

layers = [
    imageInputLayer([224 224 3])
    convolution2dLayer(3, 8, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 16, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 32, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    fullyConnectedLayer(8)
    softmaxLayer
    classificationLayer];

报错信息

Error:
Error using trainNetwork
The training images are of size 224×224×1 but the input layer expects images of size 224×224×3.

Error in training (line 49)
net = trainNetwork(aug_imds, layers, options);

解决办法

方法1:自定义预处理函数,将单通道灰度图复制为三通道

放弃ColorPreprocessing参数,自定义预处理函数完成转灰度、复制通道和尺寸调整:

function img = preprocessGrayTo3Channel(img)
    % 转为灰度图
    img = rgb2gray(img);
    % 将单通道复制为三通道
    img = repmat(img, [1 1 3]);
    % 调整到目标尺寸
    img = imresize(img, [224 224]);
end

% 创建增强数据存储
aug_imds = augmentedImageDatastore([224 224 3], imdsTrain, 'PreprocessingFcn', @preprocessGrayTo3Channel);

方法2:修改输入层为单通道

如果无需强制三通道输入,直接修改imageInputLayer的通道数为1,匹配预处理后的图像维度:

layers = [
    imageInputLayer([224 224 1]) % 此处通道数改为1
    convolution2dLayer(3, 8, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 16, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 32, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    fullyConnectedLayer(8)
    softmaxLayer
    classificationLayer];

方法3:在imageDatastore阶段提前处理图像

创建imageDatastore时自定义读取函数,直接输出符合要求的三通道灰度图:

% 自定义图像读取函数
function img = readGrayAs3Channel(filename)
    img = imread(filename);
    img = rgb2gray(img);
    img = repmat(img, [1 1 3]);
    img = imresize(img, [224 224]);
end

% 创建数据存储
imdsTrain = imageDatastore('你的图像文件夹路径', 'ReadFcn', @readGrayAs3Channel);
% 若需额外数据增强,再创建augmentedImageDatastore
aug_imds = augmentedImageDatastore([224 224 3], imdsTrain);

内容的提问来源于stack exchange,提问作者Kavya Shree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:55:33