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

使用np.pad为CNN图像添加对称填充时遇类型错误求助

图像对称填充报错修复方案

问题场景

需要为150×150像素的图像四周各添加5像素对称填充,调整为160×160像素用于CNN模型,运行以下代码时出现错误:

for need_pad_img in os.listdir(old_images_path+'split_images'):   
    if need_pad_img.endswith(".jpg") and not need_pad_img.startswith("."):
        image = Image.open(old_images_path + 'split_images/' + need_pad_img)
        data = asarray(image)
        new_data = np.pad(data, pad_width=5, mode='symmetric')
        gen_img = Image.fromarray(new_data).astype(np.uint8).convert('RGB').save(old_images_path + 'split_images/' + "pad_" + need_pad_img)

错误信息

File "/opt/homebrew/Caskroom/miniforge/base/envs/env_tf/lib/python3.9/site-packages/PIL/Image.py", line 2751, in fromarray
    raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e

TypeError: Cannot handle this data type: (1, 1, 13), |u1

查看new_data.shape得到(160,160,13),new_data.dtype为dtype('uint8')。

错误原因

np.pad(data, pad_width=5)会对数组的所有维度应用5像素的填充。如果原图像是单通道灰度图(shape为(150,150,1)),填充后通道维度会被扩展为1 + 5*2 = 13,生成不符合图像规范的13通道数据,导致PIL无法识别处理。

修复方案

指定pad_width仅对图像的高度、宽度维度填充,通道维度保持不变:

  • 使用pad_width=((5,5), (5,5), (0,0)),分别对应高度(上下各5)、宽度(左右各5)、通道(无填充)的填充参数。

同时建议用os.path.join拼接路径,避免字符串拼接的路径分隔符问题。

修复后完整代码

import os
from PIL import Image
import numpy as np
from numpy import asarray

for need_pad_img in os.listdir(os.path.join(old_images_path, 'split_images')):   
    if need_pad_img.endswith(".jpg") and not need_pad_img.startswith("."):
        img_path = os.path.join(old_images_path, 'split_images', need_pad_img)
        image = Image.open(img_path)
        data = asarray(image)
        # 仅对高度、宽度维度填充,通道维度不填充
        new_data = np.pad(data, pad_width=((5,5), (5,5), (0,0)), mode='symmetric')
        # 转换为PIL图像并保存
        gen_img = Image.fromarray(new_data.astype(np.uint8)).convert('RGB')
        save_path = os.path.join(old_images_path, 'split_images', f"pad_{need_pad_img}")
        gen_img.save(save_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:06:17