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

ResNet50单张灰度OCT图像预测时出现IndexError问题求助

解决ResNet50单张灰度OCT图像预测时的IndexError问题

问题背景

我正在开展基于深度学习的中心性浆液性视网膜病变(CSR)检测项目,尝试过VGG16、ResNet、EfficientNetB0等架构。现有数据集包含约100张CSR病变OCT图像(其中41张经Label Studio标注)及200张正常视网膜OCT图像,已用ResNet50完成训练,但运行单张灰度图像预测代码时出现错误:

IndexError: index 1 is out of bounds for axis 3 with size 1

错误原因

这个错误的核心是输入图像通道数与模型期望的输入通道数不匹配:

  • ResNet50的默认输入规格是(224, 224, 3)(3通道RGB图像)
  • 预测时传入的是单通道灰度图像,轴3的维度大小为1,而模型的卷积层在处理时会尝试访问第1索引的通道(对应RGB的G通道),导致越界

解决方案

根据你的训练数据格式,选择以下两种方案之一:

方案1:将灰度图转换为3通道格式(适用于训练时用RGB图像的场景)

如果训练阶段使用的是3通道RGB图像,只需将单通道灰度图复制为3通道即可匹配模型输入要求:

import cv2
import numpy as np
from tensorflow.keras.models import load_model

# 加载训练好的模型
model = load_model('resnet50_csr_model.h5')

# 读取单通道灰度图
img = cv2.imread('test_oct.png', 0)
# 调整为模型要求的输入尺寸
img = cv2.resize(img, (224, 224))
# 复制单通道数据到3个通道,转换为(224,224,3)
img = np.stack((img,)*3, axis=-1)
# 增加batch维度,变为(1,224,224,3)
img = np.expand_dims(img, axis=0)
# 保持与训练时一致的归一化操作(示例为除以255)
img = img / 255.0

# 执行预测
prediction = model.predict(img)

方案2:修改模型适配单通道输入(适用于训练时用灰度图的场景)

如果训练阶段实际使用的是单通道灰度图,说明初始化ResNet50时未指定正确的输入形状,需要重新定义模型并训练:

from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model

# 加载ResNet50时指定单通道输入形状,不加载预训练权重(预训练权重针对RGB图像)
base_model = ResNet50(weights=None, include_top=False, input_shape=(224, 224, 1))

# 添加自定义分类头
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
# 二分类任务:输出CSR/正常的概率
predictions = Dense(2, activation='softmax')(x)

# 构建完整模型
model = Model(inputs=base_model.input, outputs=predictions)

# 编译并重新训练(使用你的灰度数据集)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# model.fit(...)  # 此处替换为你的训练代码

# 训练完成后,直接用单通道灰度图预测
img = cv2.imread('test_oct.png', 0)
img = cv2.resize(img, (224, 224))
img = np.expand_dims(img, axis=(0, -1))  # 变为(1,224,224,1)
img = img / 255.0
prediction = model.predict(img)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:12:39