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

Flask应用中fastai Image模块未找到及load_learner报错求助

问题解决方案

1. 解决"No module named 'Image'"错误

你代码里的Image.open()调用的是PIL库的Image类,但未导入;而fastai的Image是用于模型推理的张量对象,和PIL的Image不是同一概念,二者不能混用。

  • 先安装PIL(未安装的话):
    pip install pillow
    
  • 在代码顶部添加PIL的导入:
    from PIL import Image as PILImage
    
  • 修改图片加载函数,将PIL Image转换为fastai可识别的Image对象:
    def load_image_url(url: str) -> Image:
        response = requests.get(url)
        img = PILImage.open(BytesIO(response.content))
        return Image.create(img)
    
    def load_image_bytes(raw_bytes: ByteString) -> Image:
        img = PILImage.open(BytesIO(raw_bytes))
        return Image.create(img)
    

2. 修复load_learner()函数错误

常见问题及解决方法:

  • 版本不兼容:确保fastai与torch版本匹配,模型导出时的fastai版本要和当前加载环境一致。可通过以下代码检查版本:
    import fastai
    import torch
    print(fastai.__version__)
    print(torch.__version__)
    
  • 路径错误:确认export.pkl文件存在于指定路径下,可添加路径校验:
    def load_model(path=".", model_name="export.pkl"):
        model_path = os.path.join(path, model_name)
        if not os.path.exists(model_path):
            raise FileNotFoundError(f"模型文件不存在:{model_path}")
        learn = load_learner(path, file=model_name)
        return learn.to_fp32()
    
  • 依赖缺失:如果训练模型时用到了自定义类、函数或数据集,加载模型时需要确保这些代码在当前Flask环境中存在。

修正后的完整代码片段

from fastai import *
from fastai.vision import *
from fastai.data.external import *
from PIL import Image as PILImage
import yaml
import sys
from io import BytesIO
from typing import List, Dict, Union, ByteString, Any
import os
import flask
from flask import Flask
import requests
import torch
import json

def load_model(path=".", model_name="export.pkl"):
    model_path = os.path.join(path, model_name)
    if not os.path.exists(model_path):
        raise FileNotFoundError(f"模型文件不存在:{model_path}")
    learn = load_learner(path, file=model_name)
    return learn.to_fp32()

def load_image_url(url: str) -> Image:
    response = requests.get(url)
    img = PILImage.open(BytesIO(response.content))
    return Image.create(img)

def load_image_bytes(raw_bytes: ByteString) -> Image:
    img = PILImage.open(BytesIO(raw_bytes))
    return Image.create(img)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:47:25