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

ResNet模型训练后评估预测时遭遇图像重塑错误求助

脑部MRI分类Reshape错误解决方法

问题重现

训练ResNet完成4类脑部MRI癌症分类后,测试阶段执行图像转换时出现如下错误:

测试代码

prediction = []
original = []
image = []
count = 0

for item in range(len(test)):

  img= PIL.Image.open(test['Image'].tolist()[item])
  img = img.resize((256,256))
  image.append(img)
  print(image[item])
  img = np.asarray(img, dtype= np.float32)
  img = img / 255
  img = img.reshape(-1,256,256,3) # 错误发生行
  predict = model.predict(img)
  print(predict)
  predict = np.argmax(predict)
  prediction.append(labels[predict])
  original.append(test['Label'].tolist()[item])

错误信息

<ipython-input-48-747eee3f839e> in <module>
     14   img = np.asarray(img, dtype= np.float32)
     15   img = img / 255
---> 16   img = img.reshape(-1,256,256,3)
     17   predict = model.predict(img)
     18   print(predict)

ValueError: cannot reshape array of size 65536 into shape (256,256,3)

错误原因

计算可知:256*256=65536,说明你的MRI图像是单通道灰度图(数组形状为(256,256)),但代码里强行将其重塑为3通道形状(256,256,3),两者元素总数不匹配,因此报错。而ResNet模型训练时大概率是基于3通道图像输入设计的,所以需要将单通道图转换为3通道格式。

解决方案

将单通道灰度图复制三次生成3通道图像,再添加batch维度供模型预测。修改后的代码如下:

prediction = []
original = []
image = []
count = 0

for item in range(len(test)):

  img= PIL.Image.open(test['Image'].tolist()[item])
  img = img.resize((256,256))
  image.append(img)
  print(image[item])
  img = np.asarray(img, dtype= np.float32)
  img = img / 255
  
  # 新增:将单通道转为3通道
  if len(img.shape) == 2:  # 确认是单通道灰度图
      img = np.repeat(img[..., np.newaxis], 3, axis=-1)
  
  # 添加batch维度(等效于原reshape(-1,256,256,3)的效果)
  img = img[np.newaxis, ...]
  
  predict = model.predict(img)
  print(predict)
  predict = np.argmax(predict)
  prediction.append(labels[predict])
  original.append(test['Label'].tolist()[item])

关键修改说明

  • np.repeat(img[..., np.newaxis], 3, axis=-1):先给单通道数组增加一个维度(变为(256,256,1)),再在最后一个轴上重复3次,得到(256,256,3)的3通道图像。
  • img = img[np.newaxis, ...]:添加batch维度,让数组形状变为(1,256,256,3),符合model.predict()的输入要求(模型需要接收批量数据)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:58:32