1 文件夹路径
2 前端代码
将文件保存为upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask上传图片演示</title>
</head>
<body>
<h1>上传图片</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file"/>
<br>
<input type="submit" value="上传" class="button-new" />
</form>
<img src={{o_img_path}} width="500" />
<img src={{p_img_path}} width="500" />
</body>
</html>
3 后端
from flask import Flask, render_template, request
import os
app = Flask(__name__)
import datetime
import random
import numpy as np
import cv2 # 对图像进行处理
from PIL import Image # 对图像进行处理
@app.route('/', methods=['POST', 'GET']) # 添加路由
def upload():
if request.method == 'POST':
# 1 生成一个随机的文件名:唯一
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
randomNum = random.randint(0, 100)
if randomNum <= 10:
randomNum = str(0) + str(randomNum)
uniqueNum = str(nowTime) + str(randomNum)
# 2 获取图像
f = request.files['file'] # 获取文件
basepath = os.path.dirname(__file__) # 基础路径
suffix = f.filename.split(".")[1] # 后缀名1.jpg ->jpg
# 3 保存原图像
o_img_path = basepath + "/static/images/" + uniqueNum + "_o" + "." + suffix # 原图像
f.save(o_img_path)
# 4 处理图像 yolov5 处理
img = Image.open(f.stream)
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度转换
p_img_path = basepath + "/static/images/" + uniqueNum + "_p" + "." + suffix # 处理后
cv2.imencode("." + suffix, gray2)[1].tofile(p_img_path)
return render_template('upload.html',
o_img_path="/static/images/" + uniqueNum + "_o" + "." + suffix,
p_img_path="/static/images/" + uniqueNum + "_p" + "." + suffix)
return render_template('upload.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8987, debug=True)