yolov8目标检测前端界面
时间: 2025-05-28 22:15:13 浏览: 16
### 创建YOLOv8目标检测模型的前端界面
为了实现YOLOv8目标检测系统的前端界面,可以选择使用Streamlit框架。该工具以其简单性和高效性著称,能够快速构建交互式的Web应用程序[^1]。
以下是通过Python和Streamlit创建YOLOv8目标检测前端界面的一个示例:
#### Streamlit集成代码示例
```python
import streamlit as st
from ultralytics import YOLO
from PIL import Image
import cv2
import numpy as np
import tempfile
# 加载预训练的YOLOv8模型
model_path = "runs/detect/train/weights/best.pt"
model = YOLO(model_path)
def predict(image):
"""执行预测并返回结果图像"""
results = model.predict(image, conf=0.5)[0]
result_image = results.plot()
return result_image
st.title("基于YOLOv8的目标检测系统")
uploaded_file = st.file_uploader("上传图片或视频", type=["jpg", "jpeg", "png", "mp4"])
if uploaded_file is not None:
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_filename = temp_file.name
temp_file.write(uploaded_file.read())
if uploaded_file.type.startswith('image'):
image = Image.open(temp_filename).convert("RGB")
img_array = np.array(image)
st.image(img_array, caption="原始输入", use_column_width=True)
detected_img = predict(img_array)
st.image(detected_img, caption="检测结果", use_column_width=True)
elif uploaded_file.type.startswith('video'):
cap = cv2.VideoCapture(temp_filename)
frame_placeholder = st.empty()
while True:
ret, frame = cap.read()
if not ret:
break
# 转换颜色空间以便显示
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 执行推理
results = model(rgb_frame, conf=0.5)[0]
annotated_frame = results.plot()
# 显示帧
frame_placeholder.image(annotated_frame, channels="BGR", use_column_width=True)
cap.release()
```
上述代码实现了以下功能:
- 使用`streamlit`加载页面,并允许用户上传图片或视频文件。
- 对于图片文件,读取后调用YOLOv8模型进行推理,并展示标注后的结果。
- 如果是视频文件,则逐帧处理每一帧数据,并实时更新到界面上。
此方法充分利用了Streamlit的强大能力以及YOLOv8高效的推理速度。
---
### 注意事项
在实际部署过程中需要注意以下几点:
- **模型路径配置**:确保`best.pt`权重文件位于指定目录下(即`runs/detect/train/weights/best.pt`),或者调整脚本中的路径变量以匹配实际情况[^2]。
- **依赖安装**:运行前需确认已正确安装所需库,例如`ultralytics`, `opencv-python-headless` 和 `Pillow`等。
- **硬件支持**:如果可能的话,在GPU上运行可显著提升性能;可以通过设置环境变量启用CUDA加速。
---
阅读全文
相关推荐


















