服务端代码
# coding:utf-8
from __future__ import print_function
from tkinter import Variable
from flask import Flask, render_template, request, redirect, url_for, make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time
import numpy as np
from PIL import Image
import keras
import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.models import load_model
import scipy.misc
import numpy as np
from datetime import timedelta
#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
#标签数组
label = ['T-shirt/top','Trouser','Pullover','Dress','Coat','Sandal','Shirt','Sneaker','Bag','Ankle ','boot']
# 0(T恤)1(裤子)2(套衫)3(裙子)4(外套)5(凉鞋)6(汗衫)7(运动鞋)8(包)9(踝靴)
# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/', methods=['POST', 'GET']) # 添加路由
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})
user_input = request.form.get("name")
basepath = os.path.dirname(__file__) # 当前文件所在路径
# upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename)) # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
upload_path = os.path.join(basepath, 'static/images','test.jpg') #注意:没有的文件夹一定要先创建,不然会提示没有该路径
f.save(upload_path)
# 使用Opencv转换一下图片格式和名称
# img = cv2.imread(upload_path)
# cv2.imwrite(os.path.join(basepath,'static\images', 'test.jpg'), img)
image = Image.open(upload_path)
image = image.resize((28,28))
image = np.copy(image) # 这一句
imgs = np.array(image) / 255 # 归一化
imgs = imgs.reshape([-1,28,28,1])
model = load_model('my_model.h5')
result = model.predict(imgs)
result = label[np.argmax(result)]
print(label[np.argmax(result)])
# r_image = yolo.detect_image(image)
# r_image.show()
# imgs.save(upload_path)
variable_1 = "https://aistudio.baidu.com/paddle/forum"
return render_template('upload_ok.html',userinput=user_input,variable=result,variable_1=variable_1,val1=time.time())
return render_template('upload.html')
if __name__ == '__main__':
# app.debug = True
app.run(host='0.0.0.0', port=8987, debug=True)
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask上传图片演示</title>
</head>
<body>
<h1>使用Django上传本地图片并显示示例一</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<i>请输入你当前的心情(开心、超开心、超超开心):</i>
<input type="text" class="txt_input" name="name" value="超超开心" style="margin-top:10px;"/>
<input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
</form>
<h1>阁下的心情是:{{userinput}}!</h1>
<h1>为您推荐的种类为:{{variable}}</h1>
<!-- 这里为可修改变量返回超链接的地方 -->
<a href={{variable_1}}>{{variable_1}}</a>
<img src="{{ url_for('static', filename= './images/test.jpg',_t=val1) }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/>
<!-- <img src="{{ url_for('static', filename= './images/rider.jpg',_t=val1) }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/> -->
</body>
</html>
效果展示(界面主要为了测试功能,没有去完善界面展示,见谅)