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

设置非256的img_size时触发reshape报错,求问题排查与解决

图像加载代码reshape报错问题

代码实现

img_size = 320
def load_img(path):
    img = Image.open(path)
    if img is None:
        raise ValueError(f"Empty Image at {path}")
    img = img.convert("RGB")
    return img

def load_data(path_list, gray=False, img_size=256):
    data = []
    for path in tqdm(path_list):
        img = load_img(path)
        if gray:
            img = img.convert("L")
        img = img.resize((img_size, img_size))
        img_array = np.array(img)
        if gray:
            img_array = img_array.reshape((img_size, img_size, 1))
        data.append(img_array)
    return np.array(data)

X_train= load_data([images_dir +"/"+ x for x in X_train])
X_test= load_data([images_dir +"/"+ x for x in X_test])
Y_train= load_data([masks_dir + '/' + x for x in y_train], gray=True)/255.0
Y_test= load_data([masks_dir + '/' + x for x in y_test], gray=True)/255.0
Y_train= Y_train.reshape( -1,img_size, img_size, 1)

报错信息

----> 1 Y_train= Y_train.reshape( -1,img_size, img_size, 1)
  2 
  3 

ValueError: cannot reshape array of size 983040 into shape (320,320,1)

问题根源

  1. 参数不匹配:load_data函数默认img_size为256,但你全局定义的img_size是320。处理Y_train/Y_test时,未给load_data传入img_size参数,导致函数用默认值256处理图像,每个mask最终被处理成(256,256,1)的形状,总元素数为样本数×256×256×1=983040。
  2. 多余的reshape操作:后续用全局的320执行reshape时,320×320×1=102400,983040无法被102400整除,因此报错。当全局img_size设为256时,参数一致,所以能正常运行。

解决方案

  • 方案一:统一参数:调用load_data处理mask时,显式传入当前全局的img_size:
Y_train= load_data([masks_dir + '/' + x for x in y_train], gray=True, img_size=img_size)/255.0
Y_test= load_data([masks_dir + '/' + x for x in y_test], gray=True, img_size=img_size)/255.0
  • 方案二:移除多余reshape:load_data函数中已经对gray模式的图像做了reshape((img_size, img_size, 1)),返回的数组已经是(样本数, img_size, img_size, 1)的形状,直接删掉最后一行的Y_train= Y_train.reshape( -1,img_size, img_size, 1)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:55:24