【问题标题】:How to update image in real time with flask?如何使用烧瓶实时更新图像?
【发布时间】:2019-06-04 18:25:34
【问题描述】:

我正在使用烧瓶 (python) 来托管一个界面,该界面允许用户上传图像,并使用滑块更改函数中变量的值,以减少图像中的噪声。

滑块可以工作,但问题是每次我想看到更新图像上的值变化时,我都必须重新加载页面。

如何添加一个实时更新图像的滑块,这样我就不必不断地重新加载页面来查看更改?

(如果滑块为 0,我希望它查看图像首次上传时的效果)

我正在做一些搜索,看起来我会使用 jquery 或其他东西,但我不知道如何实现它

感谢阅读

app.py:

import os
from flask import Flask, render_template, request, send_from_directory,url_for, session, redirect
import cv2
import shutil


app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))


app.config['UPLOAD_FOLDER'] = os.path.join(APP_ROOT, 'images')
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

@app.route("/")
def index():
    session.clear()
    return render_template("upload.html")

@app.route('/images/<filename>')
def uploadfile(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

@app.route('/home')
def home():
    return render_template("completed.html", imgSrc="images/" + session.get('imgSrc') , message=session.get('message'))

@app.route("/upload" , methods = ['POST'])
def upload():
    target = os.path.join(APP_ROOT, 'images')

    if request.method == 'POST':

        if not os.path.isdir(target):
            os.mkdir(target)

        for file in request.files.getlist("file"):
            filename = file.filename

            destination = "/".join((target, filename))

            file.save(destination)

            filename = destination

            org = open(filename, 'rb')

            base = os.path.basename(filename)

            dir = os.path.dirname(filename)

            filename_cp = os.path.splitext(base)[0]

            filename_cp = "cp_"+filename_cp+os.path.splitext(base)[1]

            destination2 = dir+"/"+filename_cp
            file.save(destination2)

            cpy = open (destination2, 'wb')
            shutil.copyfileobj(org, cpy)

            session['image'] = filename
            session['filename'] = filename
            session['imgSrc'] = os.path.basename(destination)
            session['cimgsrc'] = os.path.basename(destination2)
            session['cpimg'] = destination2

            print("session", session)

    return render_template("completed.html",imgSrc="images/"+session.get('imgSrc'))

@app.route("/imgp/nr", methods=['post'])
def nr():
    print(session)

    img = cv2.imread(session.get('cpimg'), 0)
    #threshold = 40
    threshold = float(request.form['slider'])
    cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY, img)
    print (session['cpimg'])
    cv2.imwrite(session.get('cpimg'),img)
    session['message'] = "NR is done!"
    session['imgSrc'] = os.path.basename(session['cpimg'])
    return redirect(url_for('home', op='nr'))

if __name__ =="__main__":
    app.secret_key = "abcdefghijklmnopqrstuvwxyz"
    app.run(port = 4555, debug = True)

上传.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Upload</title>

</head>

<form id ="upload-form" action="{{ url_for ('upload') }}" method = "POST" enctype="multipart/form-data">
    <input type="file" name="file" accept = image/* multiple>
    <p>Drag your files here or click in this area.</p>
    <button type ="submit" value="Upload"> Upload</button>


</form>


<body>

</body>
</html>

completed.hmtl(滑块和上传图片所在的位置):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> file uploaded</h1>
<img src="{{imgSrc}}" style="height:200px;width:300px;"/>
<h2>{{message}}</h2>


<form action ="imgp/nr" method = "post">
    <input type="range" min={{min}} max={{max}} value={{max}} class="slider" id="myRange" name="slider">
    <input type="submit" value="Apply ga">
</form>

</body>
</html>

【问题讨论】:

    标签: python jquery image flask slider


    【解决方案1】:

    简短的回答是您需要使用 Javascript/jQuery 来执行此操作。有一个类似的问题here 涵盖了两种方法:

    1. 要么通过 ajax 加载(base64 转换的)图像;要么或

    2. 使用 jquery 更改页面上图像的src,使其重新加载。

    您可能需要更改代码的一些部分才能使这一切正常运行,但可能是这样的:

    app.py:

    nr() 函数更改为GET,并返回base64 编码图像see here for exampleupload_file() 函数)

    完成的.html:

    /imgp/nr 添加一个ajax(以下是jquery)调用,当滑块改变时改变页面上图像的显示。例如:

    ...
    <img id="yourImage" style="height:200px;width:300px;">
    ...
    
    
    <script type="text/javascript">
    $("#myRange").change(function(){
        var sliderVal = $(this).val();
        $.ajax({ 
            medthod: 'POST',
            url:'/imgp/nr/',
            data: JSON.stringify({slider: sliderVal}),
            success: function(data){
                $("#yourImage").attr('src', 'data:image/png;base64, ' + data);
            }
        });
    });
    </script>
    

    此代码可能需要一些修复,抱歉,我没有太多时间使其完美。希望您能理解!

    【讨论】:

    • 我正在查看您链接的帖子,但我还是不明白它将如何改变我的 app.py 中的阈值值以展示滑块的更改
    • 我添加了更多细节,希望它能让你开始
    • 抱歉有更多问题,但我尝试实施您在上面发布的内容,但我仍然遇到问题。 .change(function) 应该改变 nr 吗?阈值是多少?
    • .changejquery event handler,所以当范围滑块改变时,该函数将运行。您将需要获取滑块的值以提交到您的端点。我将在$.ajaxurl 上方进行快速编辑以进行演示。
    猜你喜欢
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多