如何重塑80x60 32FC1图像数据集适配CNN训练并解决reshape报错
错误原因分析
- 第一个
AttributeError: 'list' object has no attribute 'reshape'报错是因为reshape是numpy数组的专属方法,Python原生列表没有该方法,必须先将列表转换为numpy数组才能调用。 - 第二个
cannot reshape array of size 1 into shape (26308,80,60)报错说明你转换得到的numpy数组总元素数只有1,远小于目标形状要求的26308*80*60个元素,本质原因是你的ds_negatives列表结构不符合预期,所有图像数据被嵌套存在了列表的第一个元素中,而非每个图像单独作为列表的一个元素存储。
解决步骤
- 先排查数据集列表的结构,执行以下代码确认结构:
# 查看负样本列表长度 print(len(ds_negatives)) # 查看第一个元素的内容结构 print(type(ds_negatives[0]), ds_negatives[0].shape if hasattr(ds_negatives[0], 'shape') else len(ds_negatives[0]))
- 根据排查结果处理:
- 若
len(ds_negatives)输出为1,说明所有图像都存在列表的第一个元素里,转换时要提取该元素再转numpy数组:
# 提取嵌套的实际数据集再转数组 ds_negatives_arr = np.array(ds_negatives[0]) # 正样本同理处理 ds_positives_arr = np.array(ds_positives[0])
- 若
len(ds_negatives)输出已经是26308,说明每个列表元素对应一个图像,直接转数组即可,无需额外reshape:
ds_negatives_arr = np.array(ds_negatives)
- 验证转换后的数组形状,确认符合要求:
print(ds_negatives_arr.shape) # 如果输出是(26308, 4800),说明每个图像被压平为一维,再执行reshape if ds_negatives_arr.shape == (n_negatives_img, img_width*img_height): arraynegativos = ds_negatives_arr.reshape(n_negatives_img, img_width, img_height) # 如果输出已经是(26308,80,60),直接使用即可
额外注意事项
你使用的是32FC1单通道图像,用于CNN训练时通常需要额外补充通道维度,以适配框架的输入要求(TensorFlow默认通道在后,PyTorch默认通道在前):
# TensorFlow通道在后格式 arraynegativos = arraynegativos[..., np.newaxis] # PyTorch通道在前格式 arraynegativos = np.expand_dims(arraynegativos, axis=1)
内容的提问来源于stack exchange,提问作者Javier Decena Castillo
相关产品推荐
相关产品推荐

