2016-12-25 14 views
0

我是Flask和web开发的新手,我想上传一张图片并通过我的深度学习应用程序处理,然后在页面上响应处理后的图片,这里是我的工作框架代码烧瓶,我该如何回复页面上的图片

# coding: utf-8 
import os 
import uuid 

import PIL.Image as Image 
from werkzeug import secure_filename 
from flask import Flask, url_for, render_template, request, url_for, redirect, send_from_directory 


ALLOWED_EXTENSIONS = set(list(['png', 'jpg', 'jpeg'])) 
UPLOAD_FOLDER = '/tmp' 
app = Flask(__name__) 
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 


def process_image(file_path): 
    """ 
    resize image to 32x32 
    :param file_path: file path 
    :return: 
    """ 
    img = Image.open(file_path, mode='r') 
    return img.resize([32,32], Image.ANTIALIAS) 


def allowed_file(filename): 
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS 


@app.route('/', methods=['GET', 'POST']) 
def upload_file(): 
    _path = None 
    if request.method == 'POST': 
     _file = request.files['file'] 
     print(_file) 
     if _file and allowed_file(_file.filename): 
      filename = secure_filename(_file.filename) 
      _path = os.path.join(app.config['UPLOAD_FOLDER'], filename) 
      _file.save(_path) 
      return show_pic(deep_learning(_path)) 

    return ''' 
      <!DOCTYPE html> 
      <title>Web App/title> 
      <h1>Deep Learning Web App</h1> 
      <form action="/" method="POST" enctype="multipart/form-data"> 
      <input type="file" name="file" /> 
      <input type="submit" value="submit" /> 
      </form> 
      ''' 


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

if __name__ == '__main__': 
    app.run() 

正如你可以看到它,我已经实现上传图片的功能和作用deep_learning(path),并返回处理的画面,我需要实现的功能show_pic()的路径,我该怎么办呢?

+1

从你的变量名中的领先'_'。你觉得他们有什么用处? 'allowed_file'就是'return filename.endswith((''。png','.jpg','。jpeg'))' – Daniel

+0

@Daniel,谢谢 –

回答

1

用您的html框架创建一个template,并将图像路径传递给render_template()函数。

result.html

<html> 
    <img src="{{ image_path }}"> 
</html> 

添加到您的视图功能:

return render_template('result.html', image_path=deep_learning(_path)) 

对于这个工作您的文件需要被定位在static目录或子目录。

1

,也可以定义下面的表单标签检查None值_file(处理文件),如果文件中未没有再表现出来:

@app.route('/', methods=['GET', 'POST']) 
def upload_file(): 
    _path = None 
    _file = None 
    if request.method == 'POST': 
     _file = request.files['file'] 
     print(_file) 
     if _file and allowed_file(_file.filename): 
      filename = secure_filename(_file.filename) 
      _path = os.path.join(app.config['UPLOAD_FOLDER'], filename) 
      _file.save(_path) 

    return ''' 
      <!DOCTYPE html> 
      <title>Web App/title> 
      <h1>Deep Learning Web App</h1> 
      <form ...> 
      ... 
      </form> 
      {% if _file%} 
       <img src="{{url_for('uploaded_file', filename=_file) }}" > 
      {% endif %} 
      '''