flask的web开发,用于机器学习(主要还是DL)模型的简单演示。

2018-01-09 15:40:13 浏览数 (2)

实现的功能很简单:(1)选择图片上传;(2)返回DL模型的识别结果。

代码如下:其中format_string给你模型的输出结果就OK,感兴趣的可以玩一下这个四分类:http://218.107.211.134:11001/

代码语言:javascript复制
# coding=utf-8

import os
import sys
# reload(sys)
#sys.setdefaultencoding("utf-8")
import time
from flask import request, send_from_directory
from flask import Flask, request, redirect, url_for
import uuid
import numpy as np

UPLOAD_FOLDER = '/Users/liupeng/Desktop/anaconda/flask/images'
ALLOWED_EXTENSIONS = set(['jpg','JPG', 'jpeg', 'JPEG', 'png'])
app= Flask(__name__)
app._static_folder = UPLOAD_FOLDER

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

def rename_filename(old_file_name):
    basename = os.path.basename(old_file_name)
    name, ext = os.path.splitext(basename)
    new_name = str(uuid.uuid1())   ext
    return new_name


@app.route("/", methods=['GET', 'POST'])
def hello():
    result = """
        <!doctype html>
        <title>临时测试用</title>
        <h1>来喂一张照片吧</h1>
        <form action="" method=post enctype=multipart/form-data>
        <p><input type=file name=file value='选择图片'>
        <input type=submit value='上传'>
        </form>
        <p>%s</p>
        """ % "<br>"
    if request.method == 'POST':
        file = request.files['file']
        old_file_name = file.filename
        if file and allowed_files(old_file_name):
            filename = rename_filename(old_file_name)
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            file.save(file_path)
            type_name = 'N/A'
            print ('file_path', file_path)
            
            new_url = '/static/%s' % os.path.basename(file_path)
            print ('new_url:',new_url)
            image_tag = '<img src="%s"></img><p>'
            print ('image_tag:', image_tag)
            new_tag = image_tag % new_url
            print ('new_tag:', new_tag)
            format_string = 'hello, deep learning'
            ret_string = new_tag   format_string   '<BR>'
            print ('ret_string:',ret_string)
            return result   ret_string

    return result

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=False, threaded=True)

0 人点赞