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

Flask部署PyTorch图像预测模型遇PIL.UnidentifiedImageError求助

问题:Flask+PyTorch图片预测时PIL无法识别图片文件

我用Python-Flask开发了一个图片上传应用,参考PyTorch官方教程实现了DenseNet模型对上传图片的预测功能,但运行时抛出错误:PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f4ceb257950>。


预测路由代码(app.py)

@app.route('/predict', methods=['POST'])
@login_required
def predict():
    if request.method == 'POST':

        filename = ""
        if len(request.form) == 0:
            flash("Please select a file to perform a prediction on")
            return redirect(url_for('index'))
        else:

            filename = request.form['file']
            filepath = os.path.join(app.config['UPLOAD_PATH'], \
                                     current_user.username, filename)
            
            file = open(filepath, 'rb')
            img_bytes = file.read()
            class_id, class_name = models.get_prediction(image_bytes=img_bytes)
            print(class_id, class_name)


    return render_template('predict.html', filename=filename)

模型代码(models.py)

import io
import json
import os

from torchvision import models
import torchvision.transforms as transforms
from PIL import Image

imagenet_class_index = json.load(open('imagenet_class_index.json'))
model = models.densenet121(pretrained=True)
model.eval()

def transform_image(image_bytes):
    my_transforms = transforms.Compose([transforms.Resize(255),
                                        transforms.CenterCrop(224),
                                        transforms.ToTensor(),
                                        transforms.Normalize(
                                            [0.485, 0.456, 0.406],
                                            [0.229, 0.224, 0.225])])
    
    image = Image.open(io.BytesIO(image_bytes))
    return my_transforms(image).unsqueeze(0)

def get_prediction(image_bytes):
    tensor = transform_image(image_bytes=image_bytes)
    outputs = model.forward(tensor)
    _, y_hat = outputs.max(1)
    predicted_idx = str(y_hat.item())
    return imagenet_class_index[predicted_idx]

错误栈信息

[2023-03-03 13:49:32,564] ERROR in app: Exception on /predict [POST]
Traceback (most recent call last):
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request        
    rv = self.handle_user_exception(e)
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request        
    rv = self.dispatch_request()
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/flask_login/utils.py", line 290, in decorated_view        
    return current_app.ensure_sync(func)(*args, **kwargs)
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/cloudsystem/app.py", line 311, in predict
    class_id, class_name = models.get_prediction(image_bytes=img_bytes)
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/cloudsystem/models.py", line 25, in get_prediction
    tensor = transform_image(image_bytes=image_bytes)
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/cloudsystem/models.py", line 21, in transform_image
    image = Image.open(io.BytesIO(image_bytes))
  File "/mnt/c/Users/sahan/Desktop/Senior Year/CS 81a/Sahana-cs81a/venv/lib/python3.8/site-packages/PIL/Image.py", line 3283, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f4c48b2ea40>

已尝试的解决方案

  • 确保上传的都是.png、.jpg等有效格式图片,参考过相关问题的解决方案
  • 尝试直接传入文件路径而非字节数据,确认路径正确且文件存在,但仍报错
  • 改用OpenCV读取图片,问题依旧

目前只需要能在终端打印出预测结果,求解决办法。


补充信息

  1. 传入PIL的image_bytes前20字节为:b'\xde\xcf\x13J5.p\xf5\xe5Qt9\xd7\xb5 \xda\x1d\xab4\xa0'
  2. 尝试直接用路径调用Image.open(path),路径验证有效,但报错:PIL.UnidentifiedImageError: cannot identify image file 'uploads/test/Cat03.jpg',修改后的相关代码:

app.py部分:

if os.path.isfile(filepath):
        print(filepath + " is a valid file from app.py")
class_id, class_name = models.get_prediction(filepath)

models.py部分:

def transform_image(path):
    my_transforms = transforms.Compose([transforms.Resize(255),
                                        transforms.CenterCrop(224),
                                        transforms.ToTensor(),
                                        transforms.Normalize(
                                            [0.485, 0.456, 0.406],
                                            [0.229, 0.224, 0.225])])
    
    if os.path.isfile(path):
        print(path + " is a valid file from models.py")    
    image = Image.open(path)
    return my_transforms(image).unsqueeze(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:07:59