pythonopencvflaskimutils

imutils VideoStream returns NoneType while integrating with flask


So i want to create a video stream using imutils VideoStream and put it on the web. This is the Code:

camera_web.py

from flask import Flask, render_template, Response
from imutils.video import VideoStream
from imutils.video import FPS
import cv2

app = Flask(__name__)
vs = VideoStream(src=0).start()

@app.route('/')
def index():
    """ Video streaming home page """
    return render_template('index.html')

def gen():
        rval, frame = vs.read()
        cv2.imwrite('t.jpg', frame)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n')


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

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug = True, port = 80)

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vehicle Counter Web</title>
</head>
<body>
    <h1>Vehicle Counter Demo</h1>
    <img src="{{ url_for('video_feed') }}">
</body>
</html>

Now when i run it, it returns the Error:

[ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -1072875772 [ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -1072875772 [ WARN:1] videoio(MSMF): can't grab frame. Error: -1072875772

and it doesn't return any of my videostream like on this picture:

enter image description here

Is there an error in my code, or does flask didn't support imutils VideoStream? Thanks in advance.


Solution

  • Alright, so i am the one who just dumb. The code should be like this:

    camera_web.py

    from flask import Flask, render_template, Response
    from imutils.video import WebcamVideoStream
    from imutils.video import FPS
    import imutils
    import time
    import cv2
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        """ Video streaming home page """
        return render_template('index.html')
    
    
    def gen():
        vs = WebcamVideoStream(src=1).start()
        time.sleep(2.0)
        while True:
            frame = vs.read()
            frame = imutils.resize(frame, width=500)
            rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            cv2.imwrite('t.jpg', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n')
    
    
    @app.route('/video_feed')
    def video_feed():
        return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
    
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True, port=80)
    

    And there we go! we should now see the videostream. Link to the image