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

如何从图片列表创建numpy数组?TypeError报错如何解决

错误原因

Image.open()返回的是PIL库的JpegImageFile图像对象,而非数值类型的像素矩阵。你直接将该对象存入列表后调用np.array()并指定dtype='float32'时,numpy无法将图像对象转换为浮点数值,因此触发类型错误。

解决方法

读取图像后先将PIL图像对象转换为数值类型的numpy数组,再存入列表即可,修改后的代码如下:

import os
import numpy as np
from PIL import Image

w = []
count = 0 # 补充原代码缺失的count变量初始化
PATH = "替换为你的图片文件夹实际路径"
directory = os.listdir(PATH)
directory = sorted(directory, key=len)
for item in directory:
    img = Image.open(os.path.join(PATH, item))
    # 可选:如果所有图片尺寸不一致,可先统一尺寸,示例统一为256*256
    # img = img.resize((256, 256))
    # 将PIL图像对象转为float32类型的像素数组
    img_arr = np.array(img, dtype='float32')
    w.append(img_arr)
    count += 1

w_np = np.array(w)
print('w_shape: ', w_np.shape)
补充说明
  • 若所有图片尺寸、通道数一致,最终得到的w_np维度为(图片总数, 高度, 宽度, 通道数),灰度图会省略通道数维度
  • 如有需要可在转换数组时添加/255.,将0-255范围的像素值归一化到0-1区间:img_arr = np.array(img, dtype='float32') / 255.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 23:15:02