首页 > 解决方案 > 如何将变量从 python 发送和更新到 html(Flask)?

问题描述

我正在为智能停车场创建一个 Web 应用程序,它将有两个按钮,它们将显示按下它时相机正在查看的图像或框架,另一个将显示一条消息,告诉每个按钮的可用性投币口。

这是负责查找停车场可用性的代码的一部分,在我调用一个使我进行透视转换以保存代码的函数之前,但使用烧瓶我最终在调用该方法时产生了问题。

智能停车.py

    def get_Disponibilidad(self):
        _, frame = self.cap.read()
        frame = cv2.resize(frame,(np.int(frame.shape[1]/2),np.int(frame.shape[0]/2)))
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cv2.circle(frame, (65, 190), 5, (0, 0, 255), -1)
        cv2.circle(frame, (490, 200), 5, (0, 0, 255), -1)
        cv2.circle(frame, (30, 310), 5, (0, 0, 255), -1)
        cv2.circle(frame, (530, 310), 5, (0, 0, 255), -1)

        pts1 = np.float32([[65, 190], [490, 200], [30, 310], [530, 310]])
        pts2 = np.float32([[0, 0], [600, 0], [0, 500], [600, 500]])

        matrix = cv2.getPerspectiveTransform(pts1, pts2)
        result = cv2.warpPerspective(gray, matrix, (600, 500))

        v = np.median(result)    
        lower = int(max(0, (1.0 - 0.33) * v))
        upper = int(min(255, (1.0 + 0.33) * v))
    ##    edged = cv2.Canny(image, 50, 100)
        edges = cv2.Canny(result, lower, upper)

        estado = 0
        blancos = cv2.countNonZero(edges)
        if (blancos >= 6000):
            estado = 1
        #estado = disponibilidadPlaza(edges)
        return estado

    def get_Image(self):
        _, frame = self.cap.read()
        frame = cv2.resize(frame,(np.int(frame.shape[1]/2),np.int(frame.shape[0]/2)))        
        cv2.circle(frame, (65, 190), 1, (0, 0, 255), -1)
        cv2.circle(frame, (490, 200), 1, (0, 0, 255), -1)
        cv2.circle(frame, (30, 310), 1, (0, 0, 255), -1)
        cv2.circle(frame, (530, 310), 1, (0, 0, 255), -1)

        pts1 = np.float32([[65, 190], [490, 200], [30, 310], [530, 310]])
        pts2 = np.float32([[0, 0], [600, 0], [0, 500], [600, 500]])

        matrix = cv2.getPerspectiveTransform(pts1, pts2)
        result = cv2.warpPerspective(frame, matrix, (600, 500))
        _, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()

在下面的代码中,我调用了 smartparking 的函数 get_Availability(),它应该在繁忙的情况下返回 1,否则返回 0,这个值是按下按钮时应该在 html 中显示的值,但如果它应该更新当在停车场发现汽车时,该人按下按钮。

主文件

from flask import Flask, request, redirect, render_template, Response
from SmartParking import VideoCamera

app = Flask(__name__)

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

def disponible(parking):
        while True:                 
                availability = VideoCamera().get_Disponibilidad()
                render_template('index.htm',availability=availability)

def gen(camera):        
        while True:
                frame = camera.get_Image()                
                yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
        app.run(debug=True)

最后是现在实时显示相机所见内容的 html,但其想法是在每次按下按钮时显示一帧视频,以及可用性状态。

<!DOCTYPE html>
<html>
  <head>
    <title>Smart-Parking</title>
  </head>
  <body>
    <h1>Smart Parking</h1> <h1 style="color: red;">LIVE STREAM</h1> 
    <img id="bg" src="{{ url_for('video_feed') }}">

    <h1>Slot 1:  {{availability}}</h1>

    <form method="POST"> 
      <button type="submit" name="Parking">Image</button>
      <button type="submit" name="Slots">Availability</button>
    </form>

    </body>
</html>

变量availability 将其视为null,并且按钮也不起作用,因为我不知道如何在main.py 中调用它们

伊姆古尔

标签: pythonhtmlimage-processingflask

解决方案


def disponible(parking) 函数没有路由装饰器并且永远不会被调用。您正在索引函数中呈现模板,该函数没有可用性变量。

表单提交也没有在任何地方被读取。您应该查看烧瓶的请求上下文。或者至少指向一条新路线。

这将使您无需按钮即可进行刷新:

@app.route('/')
def disponible(parking):
                availability = VideoCamera().get_Disponibilidad()
                render_template('index.htm',availability=availability)

While True there 永远不会工作,因为它会立即返回。

至于让按钮触发回程序,您需要提交表单,并在表单操作指向的路径中解决该问题。即提交到新路由(/image)或使用请求获取提交的参数

@app.route('/image/)
# Do some action that you want as a result of the image button

使用模板中的表单代码:

<form name="image" action="/image"><button type=submit>image</button></form>

http://flask.pocoo.org/docs/1.0/reqcontext/


推荐阅读