You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无Django等框架下如何将Caffe模型视频检测结果展示到HTML页面?

嘿,这个需求完全不用Django这类重型框架就能实现,我给你准备了两种实用方案,分别对应静态单张结果展示和实时视频流展示,你按需选就行:

方案1:静态展示单张检测结果(最简单上手)

适合处理单张图片/单帧视频后,把检测结果存成图片再通过网页查看。

步骤1:修改检测代码,保存带框的结果图

先把你原本用cv2.imshow()展示的图像,改成保存到本地文件:

import cv2
import numpy as np

# 假设你已经通过Caffe模型得到了检测结果:boxes(边界框坐标)、labels(类别标签)
# 加载原始图像/视频帧
img = cv2.imread("test_image.jpg")  # 如果是视频流,替换成读取的帧即可

# 遍历检测结果,绘制边界框和标签
for box, label in zip(boxes, labels):
    x1, y1, x2, y2 = box.astype(int)
    # 画绿色边界框(线宽2)
    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
    # 绘制标签(黑字白边,避免被背景遮挡)
    cv2.putText(img, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,0,0), 2)
    cv2.putText(img, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255,255,255), 1)

# 保存处理后的图像到本地
cv2.imwrite("detected_result.jpg", img)

步骤2:写一个极简的HTML页面

在和结果图同目录下创建index.html,内容如下:

<!DOCTYPE html>
<html>
<head>
    <title>Caffe目标检测结果</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .result-img {
            max-width: 90vw;
            max-height: 80vh;
            border: 3px solid #4CAF50;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <h1>目标检测结果展示</h1>
    <img class="result-img" src="detected_result.jpg" alt="带检测框的图像">
</body>
</html>

步骤3:启动本地静态服务器

打开命令行,进入文件所在目录,运行:

# Python 3版本
python -m http.server 8000
# Python 2版本(如果还在使用)
python -m SimpleHTTPServer 8000

然后打开浏览器访问http://localhost:8000/index.html,就能看到你的检测结果了。如果更新了结果图,刷新网页即可。

方案2:实时展示视频流检测结果(适合摄像头/实时视频)

如果需要实时处理摄像头或视频流,并在网页上同步展示检测结果,可以用Python内置HTTP服务器生成MJPEG流,无需任何重型框架。

步骤1:编写实时流服务器脚本

创建stream_server.py,代码如下(记得替换成你的Caffe模型路径和类别标签):

import cv2
import numpy as np
from http.server import BaseHTTPRequestHandler, HTTPServer
import io
from PIL import Image

# 初始化你的Caffe模型(替换成自己的路径)
net = cv2.dnn.readNetFromCaffe("deploy.prototxt", "your_model.caffemodel")
# 替换成你的模型对应的类别标签
CLASSES = ["背景", "人", "汽车", "自行车", "猫", "狗"]

class StreamHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/stream':
            # 设置响应头,支持MJPEG流
            self.send_response(200)
            self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=frame')
            self.end_headers()

            # 打开摄像头(参数0为默认摄像头,可替换成视频文件路径)
            cap = cv2.VideoCapture(0)
            try:
                while True:
                    ret, frame = cap.read()
                    if not ret:
                        break

                    # 预处理帧,适配Caffe模型输入
                    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300, 300), 127.5)
                    net.setInput(blob)
                    detections = net.forward()

                    # 遍历检测结果,过滤低置信度(比如>0.5)的结果
                    for i in range(detections.shape[2]):
                        confidence = detections[0, 0, i, 2]
                        if confidence > 0.5:
                            idx = int(detections[0, 0, i, 1])
                            box = detections[0, 0, i, 3:7] * np.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])
                            startX, startY, endX, endY = box.astype(int)

                            # 绘制边界框和置信度标签
                            label = f"{CLASSES[idx]}: {confidence*100:.1f}%"
                            cv2.rectangle(frame, (startX, startY), (endX, endY), (0,255,0), 2)
                            y = startY - 15 if startY > 15 else startY + 15
                            cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)

                    # 转换图像格式,生成JPEG字节流
                    img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    pil_img = Image.fromarray(img_rgb)
                    buf = io.BytesIO()
                    pil_img.save(buf, format='JPEG')
                    frame_bytes = buf.getvalue()

                    # 发送帧到浏览器
                    self.wfile.write(b'--frame\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame_bytes))
                    self.end_headers()
                    self.wfile.write(frame_bytes)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                print(f"流中断:{e}")
            finally:
                cap.release()
        else:
            # 返回主页HTML
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            html = """
            <!DOCTYPE html>
            <html>
            <head>
                <title>实时目标检测</title>
                <style>
                    body {
                        margin: 0;
                        padding: 20px;
                        background: #f5f5f5;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                    }
                    h1 { color: #333; }
                    .stream-img { border: 3px solid #4CAF50; border-radius: 8px; max-width: 90vw; }
                </style>
            </head>
            <body>
                <h1>Caffe实时目标检测流</h1>
                <img class="stream-img" src="/stream" alt="实时检测画面">
            </body>
            </html>
            """
            self.wfile.write(html.encode('utf-8'))

def run(port=8000):
    server_address = ('', port)
    httpd = HTTPServer(server_address, StreamHandler)
    print(f"服务器已启动,访问 http://localhost:{port}")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
        print("服务器已停止")

if __name__ == '__main__':
    run()

步骤2:安装依赖(如果没装的话)

pip install opencv-python pillow numpy

步骤3:启动服务器并查看

运行脚本:

python stream_server.py

打开浏览器访问http://localhost:8000,就能看到实时的目标检测画面了。

注意事项
  • 记得把代码中的Caffe模型路径、类别标签替换成你自己的配置。
  • 如果处理本地视频文件,把cv2.VideoCapture(0)换成视频文件路径(比如"test_video.mp4")。
  • 实时流的帧率取决于你的模型推理速度和硬件性能,要是帧率太低,可以尝试降低视频分辨率或提高置信度阈值减少检测数量。

内容的提问来源于stack exchange,提问作者arman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:07:43