AI项目六:WEB端部署YOLOv5

news2024/10/7 10:21:07

若该文为原创文章,转载请注明原文出处。

一、介绍

最近接触网页大屏,所以就想把YOLOV5部署到WEB端,通过了解,知道了两个方法:

1、基于Flask部署YOLOv5目标检测模型。

2、基于Streamlit部署YOLOv5目标检测。

代码在github上,个人感觉两个比较好的,所以基于两份代码测试。

https://github.com/ngzhili/Yolov5-Real-Time-Object-Detection

GitHub - harshit-tech03/Fire_Detection: A fire detection web app using yolov5.

一、虚拟环境创建

1、创建虚拟环境

conda create -n yolov5_env python=3.8  

2、激活环境

conda activate yolov5_env

3、下载yolov5

https://github.com/ultralytics/yolov5

4、安装yolov5

pip install -r requirements.txt

注意以下测试都是基于此环境测试

二、基于Flask部署YOLOv5目标检测模型。

1、安装环境

requirements.txt

flask
requests
black

matplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.2
Pillow
PyYAML>=5.3.1
scipy>=1.4.1
torch>=1.7.0
torchvision>=0.8.1
tqdm>=4.41.0

tensorboard>=2.4.1

seaborn>=0.11.0
pandas

thop  # FLOPs computation

代码感觉相对简单,而且也挺详细的,所以直接上代码。

2、前端代码

index.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <title>YOLOV5 Real Time Inference</title>
    <style>
      .corner {
        border-radius: 25px;
        border: 5px solid #212aad;
        padding: 0px;
        width:60%;
        height:auto;
        text-align: center;
      }

      .video-container {
        justify-content: center;
        text-align: center;
        height:100%;
        /*border: 1px solid black;*/
      }
      
    </style>
  </head>
  
  <body >
      <div class="container">
        <div class="row" style="text-align: center; width:100%;">
          <img src="../static/pytorch.png" style="width:40px; position:relative; left: -10px; display:inline-block;">
            <h1 style="text-align: center; display:inline-block;">Template for YOLOV5 Object Detection Model Real-Time Inference Using Web Cam</h1>
          </img>
          <h2 style="text-align: center;">Built by Zhili</h2>
        </div>
      </div>
  
      <div class="video-container">
          <img src="{{ url_for('video') }}" class="corner"></img>
          <!--<img src="../static/pytorch.png" class="corner"></img>-->
          <!--<img src="{{ url_for('video') }}" width="50%"/>-->
      </div>
    </body>
</html>

3、后端代码

app.py

"""
Simple app to upload an image via a web form 
and view the inference results on the image in the browser.
"""
import argparse
import io
import os
from PIL import Image
import cv2
import numpy as np

import torch
from flask import Flask, render_template, request, redirect, Response

app = Flask(__name__)


#'''
# Load Pre-trained Model
#model = torch.hub.load(
#        "ultralytics/yolov5", "yolov5s", pretrained=True, force_reload=True
#        )#.autoshape()  # force_reload = recache latest code
#'''
# Load Custom Model
#model = torch.hub.load("ultralytics/yolov5", "custom", path = "./best_damage.pt", force_reload=True)
model = torch.hub.load('./yolov5', 'custom', './yolov5s.pt',source='local')
# Set Model Settings
model.eval()
model.conf = 0.6  # confidence threshold (0-1)
model.iou = 0.45  # NMS IoU threshold (0-1) 

from io import BytesIO

def gen():
    cap=cv2.VideoCapture(0)
    # Read until video is completed
    while(cap.isOpened()):
        
        # Capture frame-by-fram ## read the camera frame
        success, frame = cap.read()
        if success == True:

            ret,buffer=cv2.imencode('.jpg',frame)
            frame=buffer.tobytes()
            
            #print(type(frame))

            img = Image.open(io.BytesIO(frame))
            results = model(img, size=640)
            #print(results)
            #print(results.pandas().xyxy[0])
            #results.render()  # updates results.imgs with boxes and labels
            results.print()  # print results to screen
            #results.show() 
            #print(results.imgs)
            #print(type(img))
            #print(results)
            #plt.imshow(np.squeeze(results.render()))
            #print(type(img))
            #print(img.mode)
            
            #convert remove single-dimensional entries from the shape of an array
            img = np.squeeze(results.render()) #RGB
            # read image as BGR
            img_BGR = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) #BGR

            #print(type(img))
            #print(img.shape)
            #frame = img
            #ret,buffer=cv2.imencode('.jpg',img)
            #frame=buffer.tobytes()
            #print(type(frame))
            #for img in results.imgs:
                #img = Image.fromarray(img)
            #ret,img=cv2.imencode('.jpg',img)
            #img=img.tobytes()

            #encode output image to bytes
            #img = cv2.imencode('.jpg', img)[1].tobytes()
            #print(type(img))
        else:
            break
        #print(cv2.imencode('.jpg', img)[1])

        #print(b)
        #frame = img_byte_arr

        # Encode BGR image to bytes so that cv2 will convert to RGB
        frame = cv2.imencode('.jpg', img_BGR)[1].tobytes()
        #print(frame)
        
        yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/')
def index():
    
    return render_template('index.html')

@app.route('/video')
def video():
    """Video streaming route. Put this in the src attribute of an img tag."""

    return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
'''                        
@app.route('/video')
def video():
    return Response(generate_frames(),mimetype='multipart/x-mixed-replace; boundary=frame')
'''
'''
@app.route("/", methods=["GET", "POST"])
def predict():
    if request.method == "POST":
        if "file" not in request.files:
            return redirect(request.url)
        file = request.files["file"]
        if not file:
            return

        img_bytes = file.read()
        img = Image.open(io.BytesIO(img_bytes))
        results = model(img, size=640)

        # for debugging
        # data = results.pandas().xyxy[0].to_json(orient="records")
        # return data

        results.render()  # updates results.imgs with boxes and labels
        for img in results.imgs:
            img_base64 = Image.fromarray(img)
            img_base64.save("static/image0.jpg", format="JPEG")
        return redirect("static/image0.jpg")

    return render_template("index.html")
'''

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Flask app exposing yolov5 models")
    parser.add_argument("--port", default=5000, type=int, help="port number")
    args = parser.parse_args()
    '''
    model = torch.hub.load(
        "ultralytics/yolov5", "yolov5s", pretrained=True, force_reload=True
    ).autoshape()  # force_reload = recache latest code
    model.eval()
    '''
    app.run(host="0.0.0.0", port=args.port)  # debug=True causes Restarting with stat

# Docker Shortcuts
# docker build --tag yolov5 .
# docker run --env="DISPLAY" --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" --device="/dev/video0:/dev/video0" yolov5

4、运行结果

执行python app.py

三、基于Streamlit部署YOLOv5目标检测。

1、什么是Streamlit

Streamlit 是一个用于数据科学和机器学习的开源 Python 框架。它提供了一种简单的方式来构建交互式应用程序,使数据科学家和机器学习工程师可以更轻松地将他们的模型展示给其他人。

以下是 Streamlit 常用的一些方法:

  • st.write():打印文本、数据框、图表等。
  • st.title():创建标题。
  • st.header():创建大标题。
  • st.subheader():创建小标题。
  • st.text():打印文本。
  • st.markdown():打印 Markdown 文本。
  • st.latex():打印 LaTeX 公式。
  • st.dataframe():显示数据框。
  • st.table():显示表格。
  • st.line_chart():创建线形图。
  • st.area_chart():创建面积图。
  • st.bar_chart():创建条形图。
  • st.map():创建地图。
  • st.pyplot():显示 Matplotlib 图表。
  • st.altair_chart():显示 Altair 图表。
  • st.vega_lite_chart():显示 Vega-Lite 图表。
  • st.bokeh_chart():显示 Bokeh 图表。
  • st.plotly_chart():显示 Plotly 图表。
  • st.image():显示图像。
  • st.audio():显示音频。
  • st.video():显示视频。
  • st.file_uploader():上传文件。
  • st.download_button():下载文件。

以上是 Streamlit 的一些常用方法,可以根据需要选择使用。

只能説Streamlit比Flask更简单,更容易看懂。

在上面环境的基础上在安装一次环境

2、安装环境

requirements.txt

yolov5
opencv_python_headless
streamlit
numpy
Pillow
torch
torchvision
PyYAML
tqdm
matplotlib
requests
scipy
tensorboard
pandas
seaborn
streamlit-webrtc
IPython

3、代码

代码不分前后端

Fire_Detection.py

import streamlit as st
import cv2
import numpy as np
import av
import torch
import tempfile
from PIL import Image

@st.cache
def load_model():
    model = torch.hub.load('ultralytics/yolov5','custom',path="weights/last.pt",force_reload=True)
    return model

demo_img = "fire.9.png"
demo_video = "Fire_Video.mp4"

st.title('Fire Detection')
st.sidebar.title('App Mode')


app_mode = st.sidebar.selectbox('Choose the App Mode',
                                ['About App','Run on Image','Run on Video','Run on WebCam'])

if app_mode == 'About App':
    st.subheader("About")
    st.markdown("<h5>This is the Fire Detection App created with custom trained models using YoloV5</h5>",unsafe_allow_html=True)
    
    st.markdown("- <h5>Select the App Mode in the SideBar</h5>",unsafe_allow_html=True)
    st.image("Images/first_1.png")
    st.markdown("- <h5>Upload the Image and Detect the Fires in Images</h5>",unsafe_allow_html=True)
    st.image("Images/second_2.png")
    st.markdown("- <h5>Upload the Video and Detect the fires in Videos</h5>",unsafe_allow_html=True)
    st.image("Images/third_3.png")
    st.markdown("- <h5>Live Detection</h5>",unsafe_allow_html=True)
    st.image("Images/fourth_4.png")
    st.markdown("- <h5>Click Start to start the camera</h5>",unsafe_allow_html=True)
    st.markdown("- <h5>Click Stop to stop the camera</h5>",unsafe_allow_html=True)
    
    st.markdown("""
                ## Features
- Detect on Image
- Detect on Videos
- Live Detection
## Tech Stack
- Python
- PyTorch
- Python CV
- Streamlit
- YoloV5
## 🔗 Links
[![twitter](https://img.shields.io/badge/Github-1DA1F2?style=for-the-badge&logo=github&logoColor=white)](https://github.com/AntroSafin)
""")
    

if app_mode == 'Run on Image':
    st.subheader("Detected Fire:")
    text = st.markdown("")
    
    st.sidebar.markdown("---")
    # Input for Image
    img_file = st.sidebar.file_uploader("Upload an Image",type=["jpg","jpeg","png"])
    if img_file:
        image = np.array(Image.open(img_file))
    else:
        image = np.array(Image.open(demo_img))
        
    st.sidebar.markdown("---")
    st.sidebar.markdown("**Original Image**")
    st.sidebar.image(image)
    
    # predict the image
    model = load_model()
    results = model(image)
    length = len(results.xyxy[0])
    output = np.squeeze(results.render())
    text.write(f"<h1 style='text-align: center; color:red;'>{length}</h1>",unsafe_allow_html = True)
    st.subheader("Output Image")
    st.image(output,use_column_width=True)
    
if app_mode == 'Run on Video':
    st.subheader("Detected Fire:")
    text = st.markdown("")
    
    st.sidebar.markdown("---")
    
    st.subheader("Output")
    stframe = st.empty()
    
    #Input for Video
    video_file = st.sidebar.file_uploader("Upload a Video",type=['mp4','mov','avi','asf','m4v'])
    st.sidebar.markdown("---")
    tffile = tempfile.NamedTemporaryFile(delete=False)
    
    if not video_file:
        vid = cv2.VideoCapture(demo_video)
        tffile.name = demo_video
    else:
        tffile.write(video_file.read())
        vid = cv2.VideoCapture(tffile.name)
    
    st.sidebar.markdown("**Input Video**")
    st.sidebar.video(tffile.name)
    
    # predict the video
    while vid.isOpened():
        ret, frame = vid.read()
        if not ret:
            break
        frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
        model = load_model()
        results = model(frame)
        length = len(results.xyxy[0])
        output = np.squeeze(results.render())
        text.write(f"<h1 style='text-align: center; color:red;'>{length}</h1>",unsafe_allow_html = True)
        stframe.image(output)
        
if app_mode == 'Run on WebCam':
    st.subheader("Detected Fire:")
    text = st.markdown("")
    
    st.sidebar.markdown("---")
    
    st.subheader("Output")
    stframe = st.empty()
    
    run = st.sidebar.button("Start")
    stop = st.sidebar.button("Stop")
    st.sidebar.markdown("---")
    
    cam = cv2.VideoCapture(0)
    if(run):
        while(True):
            if(stop):
                break
            ret,frame = cam.read()
            frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            model = load_model()
            results = model(frame)
            length = len(results.xyxy[0])
            output = np.squeeze(results.render())
            text.write(f"<h1 style='text-align: center; color:red;'>{length}</h1>",unsafe_allow_html = True)
            stframe.image(output)

4、运行结果

运行指令

 streamlit run Fire_Detection.py

会自动打开网页

demo提供了图片测试,视频测试,和摄像头几个方式的测试方法。由于使用的模型是训练好的模型,所以yolo版本不能修改,只能联网下载。

如果想用自己的yolov5

那修改加载模型,改成本地加载,模型也需要修改。

四、总结

通过两个方式,个人对部署web有了个相对的简单的认识。

在此感谢github,和网友提供的代码。

如有侵权,或需要完整代码,请及时联系博主。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1004881.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Trinitycore学习之在vscode查看远端服务器上源码配置

1&#xff1a;安装vscode&#xff0c;去官网下载&#xff0c;这里下载windows版本安装包 .zip https://code.visualstudio.com/Download 2&#xff1a;安装后&#xff0c;安装扩展chinese&#xff0c;使用中文设置&#xff0c;需要重启vscode。 3&#xff1a;安装ssh相关插件…

C++设计模式_05_Observer 观察者模式

接上篇&#xff0c;本篇将会介绍C设计模式中的Observer 观察者模式&#xff0c;和前2篇模板方法Template Method及Strategy 策略模式一样&#xff0c;仍属于“组件协作”模式。Observer 在某些领域也叫做 Event 。 文章目录 1. 动机&#xff08; Motivation&#xff09;2. 代码…

Thonny安装教程

软件简介 Thonny —— 一个面向初学者的 Python IDE Thonny 由爱沙尼亚的 Tartu 大学开发&#xff0c;它采用了不同的方法&#xff0c;因为它的调试器是专为学习和教学编程而设计的。 下载&安装Thonny 下载地址 打开安装包&#xff0c;进入安装界面&#xff0c;一路Ne…

【每日一题】445. 两数相加 II

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。 你可以假设除了数字 0 之外&#xff0c;这两个数字都不会以零开头。 示例1&#xff1a; 输入&#xff1a;l1 [7,2,4,3], l2 [5,6,4] 输…

电池电动汽车的健康状态 SOH 和充电状态 SOC 估计

完整程序请查看博主主页置顶博客&#xff08;专享优惠&#xff09; 主要内容&#xff1a; 健康状态 SOH采用平均加权最小二乘法&#xff08;AWTLS&#xff09;进行估计&#xff0c;并对比了加权最小二乘 &#xff08;WLS&#xff09;、总最小二乘法&#xff08;TLS&#xff0…

SQL7 查找年龄大于24岁的用户信息

描述 题目&#xff1a;现在运营想要针对24岁以上的用户开展分析&#xff0c;请你取出满足条件的设备ID、性别、年龄、学校。 用户信息表&#xff1a;user_profile iddevice_idgenderageuniversityprovince12138male21北京大学Beijing23214male复旦大学Shanghai36543female20…

GE IS215UCVGM06A IS215UCVGH1A VMIVME-7666-111000燃机模块

数据采集和监测&#xff1a;燃机模块通常具有广泛的数据采集功能&#xff0c;用于监测燃机的性能参数&#xff0c;如温度、压力、振动等。这些数据有助于运营人员实时监测燃机状态。 控制功能&#xff1a;这些模块通常包括控制逻辑和算法&#xff0c;用于管理燃机的启停、负荷…

山东大学图书馆《乡村振兴战略下传统村落文化旅游设计》许少辉八一新著

山东大学图书馆《乡村振兴战略下传统村落文化旅游设计》许少辉八一新著

2023年中国光伏行业研究报告

第一章 行业概况 1.1 定义 光伏行业&#xff0c;也称为太阳能光伏行业&#xff0c;是一个专注于利用光伏技术将太阳能转化为电能的领域。该行业涵盖了太阳能电池的制造、光伏系统的设计、安装和维护&#xff0c;以及电能的销售和供应。光伏技术的核心是光伏效应&#xff0c;通…

这家酒店,管理方式太out了!换个风格后绝了!

在酒店业&#xff0c;我们追求的不仅仅是舒适和奢华&#xff0c;还包括客人的安全与健康。然而&#xff0c;火灾风险是无论在何处都不可忽视的潜在威胁。每年&#xff0c;全球范围内数以千计的火灾事件发生&#xff0c;不仅造成了巨大的财产损失&#xff0c;还可能威胁到人们的…

mysql查所有下级

//向下递归包含本级 WITH RECURSIVE cte AS (SELECT * FROM live_usr_config WHERE supid"lNy5ZNI3WZ3QXSopb0mdr"UNION ALLSELECT d.* FROM live_usr_config d INNER JOIN cte ON d.supid cte.subid ) SELECT * FROM cte;//向下递归包含本级并限制次数为下两层 W…

Mathpix替代者|科研人必备公式识别插件|latexocr安装教程

首先是安装好python、然后直接用命令调用 文章目录 1、安装步骤2、使用步骤 1、安装步骤 也可以安装精简版的python 准备 Python 环境&#xff0c;安装python的步骤可以查看我的上一篇博文&#xff1a; Anaconda最新版2023安装教程Spyder安装教程 确保你的计算机已经安装了 P…

大数据课程L7——网站流量项目的操作步骤

文章作者邮箱:yugongshiye@sina.cn 地址:广东惠州 ▲ 本章节目的 ⚪ 了解网站流量项目的Spark与HBase整合; ⚪ 掌握网站流量项目的实时流业务处理; 一、 Spark 与 HBase 整合基础 1. 实现步骤: 1. 启动 IDEA。 2. 创建 Maven 工程,骨架选择 quickstar…

2023/09/12 qtc++

实现一个图形类(Shape) &#xff0c;包含受保护成员属性:周长、面积&#xff0c; 公共成员函数:特殊成员函数书写 定义一个圆形类(Circle) &#xff0c;继承自图形类&#xff0c;包含私有属性:半径 公共成员函数:特殊成员函数…

使用Langchain+GPT+向量数据库chromadb 来创建文档对话机器人

使用LangchainGPT向量数据库chromadb 来创建文档对话机器人 一.效果图如下&#xff1a; 二.安装包 pip install langchainpip install chromadbpip install unstructuredpip install jieba三.代码如下 #!/usr/bin/python # -*- coding: UTF-8 -*-import os # 导入os模块&…

59-代码随想录--数组--螺旋矩阵

力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 给定一个正整数 n&#xff0c;生成一个包含 1 到 n^2 所有元素&#xff0c;且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 模拟顺时针…

电路电子技术1--关联参考方向及功率的计算

1.判断 电流由元件的低点位端流向高电位端的参考方向称为关联参考方向。() 考点&#xff1a;电流、电压的参考方向 解释&#xff1a;在一些复杂的电路中&#xff0c;往往不能预先确定某段电路上的电流、电压的实际方向&#xff0c;所以引进了 “关联参考方向”。为了能够解决问…

网工内推 | 运营商技术支持,数通基础扎实,最高17k

01 新华三技术有限公司 招聘岗位&#xff1a;运营商技术支持工程师 职责描述&#xff1a; 1、负责新华三产品产品和方案在运营商客户的日常运维和技术支持&#xff1b; 2、为运营商客户提供网上问题处理、业务变更支持&#xff1b; 3、负责对应运营商客户日常维系&#xff0…

RabbitMQ基础概念-02

RabbitMQ是基于AMQP协议开发的一个MQ产品&#xff0c; 首先我们以Web管理页面为 入口&#xff0c;来了解下RabbitMQ的一些基础概念&#xff0c;这样我们后续才好针对这些基础概念 进行编程实战。 可以参照下图来理解RabbitMQ当中的基础概念&#xff1a; 虚拟主机 virtual hos…

绝热量热法反应热测试过程中的温度和压力自动跟踪控制解决方案

摘要&#xff1a;现有的ARC加速量热仪普遍存在单热电偶温差测量误差大造成绝热效果不好&#xff0c;以及样品球较大壁厚造成热惰性因子较大&#xff0c;都使得ARC测量精度不高。为此本文提出了技术改进解决方案&#xff0c;一是采用多只热电偶组成的温差热电堆进行温差测量&…