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

Keras构建自动驾驶模型报错:int()参数应为字符串/数字而非PngImageFile

解决Keras模型输入报错:int() argument must be a string, a bytes-like object or a number, not 'PngImageFile'

嘿,作为刚入门深度学习的新手,遇到这个问题太正常啦!我来给你拆解一下原因和解决办法:

问题根源

你现在直接把PIL库加载出来的PngImageFile对象喂给Keras模型了,但Keras的Sequential模型只认数值型的numpy数组,不认图像对象本身——这就是报错的核心原因。

具体解决方案

1. 把图像对象转换成numpy数组(必做)

不管你是单张图像测试还是批量加载数据集,都要先把PIL图像转成数组,同时记得做像素值归一化(把0-255的像素值缩到0-1之间,这能让模型训练更稳定):

from PIL import Image
import numpy as np

# 示例:加载单张图像并转换
img = Image.open("your_race_car_image.png")
# 转换成numpy数组 + 归一化
img_array = np.array(img) / 255.0

2. 确保模型输入层和图像形状匹配

你的模型输入层要和图像的尺寸、通道数对应上。比如如果是RGB彩色图像(3通道),假设图像尺寸是160x320,那Sequential模型的第一层要指定input_shape:

from keras.models import Sequential
from keras.layers import Dense, Flatten

model = Sequential()
# 输入层:Flatten层需要明确图像的形状(高度, 宽度, 通道数)
model.add(Flatten(input_shape=(160, 320, 3)))
# 后续的全连接层
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
# 输出层:转向角是回归任务,用linear激活
model.add(Dense(1, activation='linear'))

# 编译模型(回归任务用MSE损失)
model.compile(optimizer='adam', loss='mean_squared_error')

3. 批量数据集处理的注意事项

如果是用自定义数据生成器加载大量赛车图像,要在生成器内部完成图像转数组的操作,确保每个批次的数据都是numpy数组:

def custom_generator(image_paths, steering_angles, batch_size=32):
    while True:
        batch_images = []
        batch_angles = []
        # 按批次取数据
        for i in range(batch_size):
            idx = np.random.randint(len(image_paths))
            img = Image.open(image_paths[idx])
            # 转数组+归一化
            img_array = np.array(img) / 255.0
            batch_images.append(img_array)
            batch_angles.append(steering_angles[idx])
        # 转换成numpy数组返回
        yield np.array(batch_images), np.array(batch_angles)

额外小提示

  • 所有输入图像的尺寸要统一!如果有的图是160x320,有的是200x400,模型会直接报错,加载图像时记得用img.resize((width, height))统一尺寸。
  • 自动驾驶的转向角预测是回归任务,别用分类任务的损失函数(比如categorical_crossentropy),用mean_squared_error才对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:20:38