Flask结合Ajax:如何展示非持续存在的average变量到网页
解决方案
一、修改Python后端代码
- 初始化并维护average变量:在
Tracking函数中添加平均时间的初始值,确保每次生成器返回都包含该字段:
def Tracking(): lower = np.array([35, 192, 65]) upper = np.array([179, 255, 255]) video = cv2.VideoCapture(1, 0) times = [] total = 0 is_round = False average = None # 初始化平均时间变量 while True: success, img = video.read() image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(image, lower, upper) blur = cv2.GaussianBlur(mask, (15, 15), 0) circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, 14, param1=34, param2=10, minRadius=4, maxRadius=10) circles = np.uint16(np.around(circles)) if (len(circles[0, :]) == 7) and not is_round: start_time = time.time() is_round = True curr_count = 0 round_total = 0 elif is_round: if len(circles[0, :]) == 1: end_time = time.time() is_round = False time_taken = end_time - start_time print('time: ', str(datetime.timedelta(seconds=time_taken))[2:7]) times.append(time_taken) average = sum(times) / len(times) # 计算平均时间 print('Avg time: ', str(datetime.timedelta(seconds=average))[2:7]) elif len(circles[0, :]) < 7: curr_count = (7 - round_total) - len(circles[0, :]) total += curr_count round_total += curr_count for i in circles[0, :]: cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2) cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3) # 修改yield内容,返回包含total和average的字典 yield { "total": total, "average": str(datetime.timedelta(seconds=average))[2:7] if average is not None else None }
- 修改/update路由返回JSON格式:用Flask的
jsonify将数据转为标准JSON格式,方便前端解析:
from flask import Flask, render_template, jsonify # 确保导入jsonify # 原有代码保持不变... @app.get("/update") def update(): global gen_total data = next(gen_total) return jsonify(data) # 返回JSON而非纯字符串
二、修改HTML页面
添加用于显示平均时间的元素,和原有总计数元素并列:
<div class="data"> <p>总计数:<span id="output"></span></p> <p>平均耗时:<span id="average-output">暂无数据</span></p> </div>
三、修改JavaScript逻辑
更新Ajax请求处理逻辑,解析JSON数据并分别更新两个页面元素:
function update(){ $.get("/update", function(data){ // 更新总计数 $("#output").text(data.total); // 更新平均时间,处理无数据的情况 if (data.average !== null) { $("#average-output").text(data.average); } else { $("#average-output").text("暂无数据"); } }); } update() var intervalId = setInterval(function() { update() }, 10000);
这样修改后,前端会定时获取包含总计数和平均时间的JSON数据,当平均时间存在时显示格式化后的字符串,不存在时显示"暂无数据",完全适配你的检测逻辑。
内容的提问来源于stack exchange,提问作者Ethan0619
相关产品推荐
相关产品推荐

