如何使用Flask实时更新图像?

时间:2019-06-04 18:25:34

标签: python jquery image flask slider

我正在使用flask(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)

upload.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>

1 个答案:

答案 0 :(得分:0)

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

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

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

您可能需要更改代码的一部分才能使所有功能正常工作,但这可能与以下内容类似:

app.py:

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

completed.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>

此代码可能需要修复,我没有太多时间来完善它。希望你能明白!