基于Flask部署Segformer到Web端

我用到是pycharm完成

首先出创建flask项目

这是py文件的代码 

from flask import Flask,render_template,request,Response,send_file,jsonify
import os
import cv2
import base64
import numpy as np
from PIL import Image
import datetime
import io
import json
from segformer_pytorch.segformer import SegFormer_Segmentation
#调用Sgeformer的文件
segformer=SegFormer_Segmentation()
#要对图进行什么处理
def process_image(img):

    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(np.uint8(img))
    img = np.array(segformer.detect_image(img))
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

    return img
# 获得处理好的图片
def get_img(file_data,filename):
    nparr=np.frombuffer(file_data,np.uint8)
    img=cv2.imdecode(nparr,cv2.IMREAD_COLOR)
    img=process_image(img)
    pa = os.path.join('data/get_data/',filename)
    cv2.imwrite(pa,img)
    return img

# 获得视频处理好每一帧的图片
def get_fps_img(video_path,filename):
    cap=cv2.VideoCapture(video_path)
    num=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))#获得视频正整数总帧数
    frame_width=int(cap.get(3))#获得视频帧的宽
    frame_height=int(cap.get(4))#获得视频帧的高
    path=os.path.join('data/get_data/',filename)#处理好的视频保存的地址
    out=cv2.VideoWriter(path,cv2.VideoWriter_fourcc(*'mp4v'),25,(frame_width, frame_height))
    for i in range(num):
        r,img=cap.read()
        img=process_image(img)
        # 在最后一帧图写入文字
        if i+1==num:
            cv2.putText(img, 'OVER', (50, 180), cv2.FONT_HERSHEY_SIMPLEX, 5.0, (0,0,255), 10)
        out.write(img)
        _,buffer=cv2.imencode('.jpg',img)
        img=buffer.tobytes()
        yield (b'--frame\r\n'
                b'Conten-Type: image/jpeg\r\n\r\n'+img+b'\r\n')
app=Flask(__name__)
@app.route('/',methods=['GET','POST'])
def my():
    if request.method=='POST':
        try:
            f=request.files['file']
            data_type=f.filename.rsplit('.',1)[1]
        except:

            return render_template('real_time.html')
        global img_name
        img_name=f.filename
        if data_type=='jpg' or data_type=='png':
            image_data=f.read()
            #把照片数据存入img_data中
            img_path = os.path.join('data/img', f.filename)
            image = Image.open(io.BytesIO(image_data))
            image.save(img_path)
            #调用函数对图进行处理
            img=get_img(image_data,f.filename)

            _,img=cv2.imencode('.jpg',img)
            image_base64=base64.b64encode(img).decode('utf-8')
            return render_template('img_save.html',img=image_base64)
        elif data_type=='mp4' or data_type=='ts' or data_type=='avi':
            global fps_path
            # 把视频数据存入img_data中
            fps_path=os.path.join('data/video',f.filename)
            f.save(fps_path)
            return render_template('video.html')
    return render_template('index.html')
@app.route('/detext',methods=['GET','POST'])
def detect():
    global fps_path,img_name
    return Response(get_fps_img(fps_path,img_name),mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/download_video',methods=['GET'])
def download_video():
    global img_name
    video_path='data/get_data/'+img_name
    return send_file(video_path,as_attachment=True)
@app.route('/get_feedback', methods=['POST'])
def get_feedback():
    feedback = request.form['feedback']
    timestamp=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open('用户反馈.txt','a',encoding='utf-8') as f:
        f.write(timestamp+'     '+feedback+'\n')
    return '感谢你的反馈'
if __name__ == '__main__':
    app.run(host='0.0.0.0',threaded=True)

html的代码

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title elevation="center">图像分割</title>
        <link rel="stylesheet" type="text/css" href="../static/style.css">
    </head>
    <body id="bg-1">
        <h1 id="green-h">SegFormer语义分割</h1>
        <div class="index-div">
            <form method="POST" action="" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="提交">
            </form>
            <p>本网站支持视频和图片的形式,为您解决分割问题。</p>
            <p>只需上传文件就可以实现左图变右图,狗变绿。</p>
            <h1>预览图</h1>
        </div>
        <div class="index-div">
            <img src="../static/dog.jpg">
            <img src="../static/image.jpg"  >
        </div>


    </body>
</html>

 img_save.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图像分割</title>
    <script src="../static/common.js"></script>
    <link rel="stylesheet" type="text/css" href="../static/style.css">
</head>
<body id="bg-1">
    <div id="div1" >
        <h1 id="green-h">效果展示</h1>
        <a href="data:image/jpeg;base64,{{img}}" download="image.jpg"><p style="color: black;font-size: 27px;">下载照片</p></a><br>
        <img src="data:image/jpeg;base64,{{ img }}">
    </div>
    <div id="div2">
        <form method="POST" action="/get_feedback" >
            <p id="p1">反馈意见</p>
            <textarea id="feedback" name="feedback" rows="5" cols="50" onkeyup="filterSensitiveWords()"></textarea><br><br>
            <input type="submit" value="提交">
        </form>
    </div>
</body>
</html>

video.html 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>图像分割</title>
        <script src="../static/common.js"></script>
        <link rel="stylesheet" type="text/css" href="../static/style.css">
    </head>
    <body id="bg-2">
        <div id="div1">
            <h1 id="green-h">segformer效果展示</h1>
            <a href="/download_video"><p style="color: aliceblue;font-size: 27px;">下载视频</p></a>
            <p  style="color: aliceblue">温馨提示:下载视频要等效果展示完毕才可下载</p>
            <img src="{{ url_for('detect') }}" width="1300" height="800">
        </div>
        <div id="div2">
            <form method="POST" action="/get_feedback" >
                <p id="p1">反馈意见</p>
                <textarea id="feedback" name="feedback" rows="5" cols="50" onkeyup="filterSensitiveWords()"></textarea><br><br>
                <input type="submit" value="提交">
            </form>
        </div>
    </body>
</html>

css文件代码

style.css

#bg-1{
     background-image: url("../static/kkk.jpeg");
}
#bg-2{
    background-image: url("../static/b1.jpg");
}
#green-h{
    color: green;
    text-align: center;/*文本居中*/
    font-size: 45px;/*文本大小*/
}
.index-div {
    text-align: center;
    height: 200px;
}
#div1{
    text-align: center;
    height: 1500px;
}
#div2{
    position: relative;/*相对定位*/
    left: 1400px;
    bottom: 1500px;
    text-align: center;
    vertical-align: middle;/*垂直居中*/
    width: 500px;/*盒子的宽*/
    height: 200px;/*盒子的高*/
    display: table-cell;
}
#p1{
    color: aliceblue;
    display: flex;/*弹性盒子*/
    align-items: center;/*垂直居中*/
    justify-content: center;/*水平居中*/
    font-size: 25px;
}

js文件代码

common.js

function filterSensitiveWords() {
    var textarea=document.getElementById('feedback');
    var sensitiveWords=['sb','傻逼','傻'];
    var feedback=textarea.value;
    sensitiveWords.forEach(function (word) {
        var regex=new RegExp(word,'gi')
        feedback=feedback.replace(regex,'*'.repeat(word.length));
    });
    textarea.value=feedback;
}

复制粘贴就能用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值