如何将变量传递给python中的类

时间:2019-01-17 05:42:38

标签: python forms flask

尝试根据html表单提供的值执行条件语句。

代码流如下。 Index.html使用视频流进行渲染,并具有一个复选框,使用户可以决定是否要运行面部检测。

按下检查瓶后,将值保存到一个名为status的变量,并尝试在opencv_camera对象期间传递它。我所有的尝试都会产生未定义的自我/状态。

真的迷路了,请帮助。

camera_opencv.py

from base_camera import BaseCamera
**# THE CLASS IN QUESTION**
class Camera(BaseCamera):
    status = 0
    def __init__(self, state=None):
        if state:
                status = state
        else:
            status = 0
        super().__init__()
    video_source = 0
    @staticmethod
    def set_video_source(source):
        Camera.video_source = source

    @staticmethod
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        while True:
            # read current frame
            _, frame = camera.read()
            # frame = cv2.resize(frame, (704, 396))
            if status: # CONDITIONAL STATEMENT
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                faces = face_cascade.detectMultiScale(gray, 1.3, 5)
                if len(faces) > 0:
                    print("SUPS")
                for (x,y,w,h) in faces:
                    cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)



            # encode as a jpeg image and return it
            yield cv2.imencode('.jpg', frame)[1].tobytes()

app.py

   from camera_opencv import Camera
    app = Flask(__name__)
    state = 0 # STATE VARIABLE 
    @app.route('/', methods = ['GET','POST'])
    def index():
        state = request.form.get('check')
        # print(state)
        # import pdb; pdb.set_trace()
        return render_template("index.html")

    def gen(camera):
        """Video streaming generator function."""
        while True:
            frame = camera.get_frame()
            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():
        """Video streaming route. Put this in the src attribute of an img tag."""
        return Response(gen(Camera(state=state)),
                        mimetype='multipart/x-mixed-replace; boundary=frame')#STATE VARIABLE BEING PASSED

1 个答案:

答案 0 :(得分:3)

从本质上讲,Web服务器是无状态的:它们不知道两个请求是否来自同一用户,因此每个响应都在自己的上下文中执行。这意味着,如果您在索引视图中将状态从0设置为1,然后转到/video_feed视图,则状态将再次为0。

要在启动相机时获得适当的状态值,请将状态作为参数添加到/video_feed视图中。因此,如果要使用面部检测,请导航至URL /video_feed?state=1,然后从URL中获取state参数。如果您不想激活面部检测,请导航至/video_feed?state=0或仅导航至/video_feed并使用默认状态。