首页 > 解决方案 > 将 Flask 上传的图像传递给类时遇到问题

问题描述

我有一个class接受 aimage作为参数的,如下所示:

import cv2
from PIL import Image

class CocoDataset:

    def __init__(self, img):
        self.img = img

    def detection(self):

        print(type(self.img))
        my_img = cv2.imread(self.img)
        print(my_img)
        print(my_img.shape)
        my_img = cv2.resize(my_img, (800, 800))

        #Some Operations On Image Here
        #___________________________#

        im = Image.fromarray(my_img)
        return im

现在我想保存并显示im在 Flask Web 应用程序中返回的内容。我使用 Flask 上传输入图像并将其作为参数传递给上述类。烧瓶代码如下:

from flask import Flask, render_template, request
from flask.views import MethodView
from files.test1 import CocoDataset
app=Flask(__name__)

class ImageUpload(MethodView):

    def get(self):
        return render_template('index.html')

    def post(self):
        file=request.files['file']
        fileInput=file.filename
        print(type(fileInput))
        coco=CocoDataset(fileInput)
        image=coco.detection()
        filename='detection.jpg'
        image.save('static/images/'+filename)

        return render_template('index.html', upload=True, filename=filename)

app.add_url_rule('/', view_func=ImageUpload.as_view('homepage'))
app.run(debug=True)

但是当我在 Flask 代码上运行并my_imgCocoDataset类中打印时,它会打印None. 这就是它给出以下错误的原因:

AttributeError: 'NoneType' object has no attribute 'shape'

它应该是 Image 而不是NoneType,我在这里做错了什么?我认为我在将image论点传递给班级时犯了一些错误。由于我是 Flask 新手,因此在 Flask 中执行此操作的正确方法是什么。对应的HTML代码index.html如下:

<body>
<h1>File Uploader</h1>
<form action="/" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/*">
    <input type="submit" value="Send">

    {% if upload %}
    <img src='static/images/{{filename}}'>
    {% endif %}
</body>

谢谢。

标签: pythonhtmlflask

解决方案


推荐阅读