Flask Web应用中如何在摄像头视频流下动态打印帧数值
实现方案
你可以通过「后端存储实时像素值+前端定时拉取追加显示」的方式实现需求,全程不需要改动原有视频流的传输逻辑,改动量极小:
1. 后端代码修改(App.py)
核心改动点:
- 新增全局变量存储每帧最新的
frame[0][0][0]数值 - 在帧编码为JPG之前读取像素值(注意要在
frame变量被覆盖为字节流之前取值) - 新增轻量接口返回最新的像素值供前端拉取
修改后的完整代码:
from flask import Flask, render_template, Response, jsonify import cv2 app = Flask(__name__) camera = cv2.VideoCapture(0) latest_pixel_val = 0 # 存储左上角像素的最新通道值 def gen_frames(): global latest_pixel_val while True: success, frame = camera.read() if not success: break else: # 读取目标像素值,转成普通int类型避免JSON序列化报错 latest_pixel_val = int(frame[0][0][0]) ret, buffer = cv2.imencode('.jpg', frame) frame_bytes = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n') @app.route('/') def index(): return render_template('index.html') @app.route('/video_feed') def video_feed(): return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') # 新增接口:返回最新像素值 @app.route('/get_latest_pixel') def get_latest_pixel(): return jsonify({"val": latest_pixel_val}) if __name__ == "__main__": app.run(debug=True)
2. 前端代码修改(templates/index.html)
核心改动点:
- 新增数值显示区域
- 加定时器定时拉取最新像素值,追加到序列后用逗号拼接显示
- 做长度限制避免页面内容过多卡顿
修改后的完整代码:
<body> <div> <img src="{{ url_for('video_feed') }}" width="50%"> </div> <!-- 像素值显示区域 --> <div style="margin-top: 12px; padding: 8px; word-break: break-all; width: 50%;"> <strong>像素值序列:</strong> <span id="pixel-sequence"></span> </div> <script> const seqContainer = document.getElementById('pixel-sequence'); const valueList = []; // 定时拉取像素值,间隔可根据摄像头帧率调整 setInterval(async () => { try { const resp = await fetch('/get_latest_pixel'); const { val } = await resp.json(); valueList.push(val); // 最多保留最近500个值,可根据需求调整上限 if (valueList.length > 500) valueList.shift(); seqContainer.textContent = valueList.join(', '); } catch (err) { console.error('像素值拉取失败:', err); } }, 100); </script> </body>
可调参数说明
- 拉取间隔:默认100ms(对应10次/秒),如果你的摄像头帧率更高,可以改成40ms(25次/秒)匹配帧率
- 数值保留长度:默认最多存500个值,避免页面DOM过长卡顿,可自行调整阈值
- 通道选择:OpenCV默认读取的彩色帧是BGR顺序,
frame[0][0][0]是蓝色通道值,要取绿/红通道对应改成frame[0][0][1]/frame[0][0][2]即可
内容的提问来源于stack exchange,提问作者Chulendra Wibavashakthi
相关产品推荐
相关产品推荐

