训练Unet模型时访问掩码触发ValueError错误求助
多类别语义分割Unet代码ValueError排查
问题场景
参考DigitalSreeni的YouTube第208期多类别语义分割Unet教程复现代码,仅替换自有同尺寸图像后,在Spyder中运行时执行n, h, w = train_masks.shape触发错误:
ValueError: not enough values to unpack (expected 3, got 1)
相关代码
from simple_multi_unet_model import multi_unet_model #Uses softmax from keras.utils import normalize import os import glob import cv2 import numpy as np from matplotlib import pyplot as plt #Resizing images, if needed SIZE_X = 128 SIZE_Y = 128 n_classes=5 #Number of classes for segmentation #Capture training image info as a list train_images = [] for directory_path in glob.glob("/Hydro/128bit/images/"): for img_path in glob.glob(os.path.join(directory_path, "*.tif")): img = cv2.imread(img_path, 0) #img = cv2.resize(img, (SIZE_Y, SIZE_X)) train_images.append(img) #Convert list to array for machine learning processing train_images = np.array(train_images) #Capture mask/label info as a list train_masks = [] for directory_path in glob.glob("/Hydro/128bit/masks/"): for mask_path in glob.glob(os.path.join(directory_path, "*.tif")): mask = cv2.imread(mask_path, 0) #mask = cv2.resize(mask, (SIZE_Y, SIZE_X), interpolation = cv2.INTER_NEAREST) #Otherwise ground truth changes due to interpolation train_masks.append(mask) #Convert list to array for machine learning processing train_masks = np.array(train_masks) ############################################### #Encode labels... but multi dim array so need to flatten, encode and reshape from sklearn.preprocessing import LabelEncoder labelencoder = LabelEncoder() n, h, w = train_masks.shape train_masks_reshaped = train_masks.reshape(-1,1) train_masks_reshaped_encoded = labelencoder.fit_transform(train_masks_reshaped) train_masks_encoded_original_shape = train_masks_reshaped_encoded.reshape(n, h, w)
错误信息
File "C:\Users\anish\208_multiclass_Unet_sandstone.py", line 63, in <module> n, h, w = train_masks.shape ValueError: not enough values to unpack (expected 3, got 1)
问题原因与解决方法
核心原因
train_masks的维度为1维,而非预期的3维(样本数、高度、宽度),本质是未成功加载到掩码图像,导致数组维度异常。
具体排查方向
路径匹配失败
- 若使用Windows系统,路径格式错误:原路径
/Hydro/128bit/masks/是Linux风格,Windows需改为C:/Hydro/128bit/masks/或\\Hydro\\128bit\\masks\\,同时确认目录真实存在。 - 检查
glob.glob("/Hydro/128bit/masks/")是否返回空列表,若为空则说明路径未匹配到目标目录。
- 若使用Windows系统,路径格式错误:原路径
文件匹配规则问题
- 掩码文件后缀可能是大写
.TIF,原规则*.tif无法匹配,可修改为兼容大小写的匹配:glob.glob(os.path.join(directory_path, "*.[tT][iI][fF]"))。 - 确认掩码目录下确实存在
.tif格式文件,无拼写错误。
- 掩码文件后缀可能是大写
图像加载失败
- 部分掩码文件损坏或无读取权限,
cv2.imread返回None,导致列表中混入无效值,转数组后维度异常。可在循环中添加验证:mask = cv2.imread(mask_path, 0) if mask is not None: train_masks.append(mask) else: print(f"无法加载文件: {mask_path}")
- 部分掩码文件损坏或无读取权限,
验证步骤
在train_masks = np.array(train_masks)后添加打印语句,确认数据加载状态:
print("掩码列表长度:", len(train_masks)) print("掩码数组形状:", train_masks.shape)
若长度为0,优先排查路径和文件匹配问题;若形状不是(n, 128, 128),则检查图像加载和尺寸是否符合预期。
内容的提问来源于stack exchange,提问作者Anish Nayak
相关产品推荐
相关产品推荐

