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

Django中调用Keras model.predict触发UnicodeEncodeError报错排查

Django中model.predict触发UnicodeEncodeError排查方案

报错核心原因

该错误大概率是图片路径包含非ASCII字符(如中文、特殊符号),Windows系统默认的charmap编码无法处理这类字符,导致模型预测过程中底层IO操作编码失败。

具体解决步骤

1. 修复图片路径的编码处理

修改image_predict函数中load_img的调用方式,强制用utf-8编码处理路径:

import keras.api.models
from keras.api.preprocessing.image import load_img, img_to_array
from keras.api.applications.vgg16 import VGG16, preprocess_input
import numpy as np

def image_predict(image_data):
    # 用utf-8编码路径,解决特殊字符问题
    image = load_img(image_data.encode('utf-8'), target_size=(224, 224))
    image = img_to_array(image)
    image = np.array(image)
    image = preprocess_input(image)
    image = np.reshape(image, (1, 224, 224, 3))
    prediction = np.argmax(nermodel.predict(image)[0])
    return prediction

或改用pathlib处理路径,自动兼容编码:

import keras.api.models
from keras.api.preprocessing.image import load_img, img_to_array
from keras.api.applications.vgg16 import VGG16, preprocess_input
import numpy as np
from pathlib import Path

def image_predict(image_data):
    image_path = Path(image_data)
    image = load_img(image_path, target_size=(224, 224))
    image = img_to_array(image)
    image = np.array(image)
    image = preprocess_input(image)
    image = np.reshape(image, (1, 224, 224, 3))
    prediction = np.argmax(nermodel.predict(image)[0])
    return prediction

2. 检查模型加载路径的编码

如果模型是从文件加载,确保模型文件路径无特殊字符,同样用pathlib或utf-8编码加载:

nermodel = keras.api.models.load_model(Path("你的模型文件路径"))

3. 验证路径有效性

在循环调用前打印所有路径,确认是否存在特殊字符:

images = Image.objects.filter(user_id=user)
image_list = []
for image in images:
    img_path = image.image.path
    print(f"当前图片路径:{img_path}")
    image_list.append(img_path)
for img in image_list:
    result = image_predict(img)

若路径存在特殊字符,直接重命名文件或修改存储路径,移除非ASCII字符。

4. 强制Python使用UTF-8编码(Windows环境)

在Django项目的manage.py开头添加以下代码,强制运行时编码为UTF-8:

import sys
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')

或在系统环境变量中添加PYTHONUTF8=1,全局强制Python使用UTF-8编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:38:30