如何在print语句中显示图像通道数?代码调试失败求助
解决图像通道数显示问题
1. 先确保数据包含通道维度
你的黑白图像数据目前大概率是(样本数, 高度, 宽度)的形状,没有单独的通道维度,所以直接打印shape不会显示1。先给所有数据集添加通道维度:
# 给数组末尾添加通道维度,shape从(N, H, W)变成(N, H, W, 1) x_train_full = np.expand_dims(x_train_full, axis=-1) x_train = np.expand_dims(x_train, axis=-1) x_val = np.expand_dims(x_val, axis=-1) x_test = np.expand_dims(x_test, axis=-1)
如果是用框架加载的数据(比如TensorFlow的image_dataset_from_directory),可以在加载时设置color_mode="grayscale",自动生成单通道数据。
2. 修正print语句的错误
你当前的代码有两个明显问题:
- 第一个print里的
img变量还没定义(要到后面循环才赋值),img.channel会直接报错; - print的format字符串只有2个占位符,却传了3个参数,语法不匹配。
直接打印数据的shape就够了,因为已经给数据加了通道维度,shape会自动包含1:
print("train data : {}\tlabel : {}".format(x_train_full.shape, y_train_full.shape)) print("train data : {}\tlabel : {}".format(x_train.shape, y_train.shape)) print("val data : {}\tlabel : {}".format(x_val.shape, y_val.shape)) print("test data : {}\tlabel : {}".format(x_test.shape, y_test.shape))
这样输出就会是你想要的train data : (60000, 28, 28, 1)格式。
3. 快速排查技巧
先执行print(x_train_full.shape)看看当前数据的形状:
- 如果输出是
(60000,28,28),说明需要加通道维度; - 如果已经是
(60000,28,28,1),那只需要修正print语句的错误即可。
内容的提问来源于stack exchange,提问作者Jun
相关产品推荐
相关产品推荐

