File size: 1,461 Bytes
90eeca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373fff7
90eeca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from vidgear.gears import CamGear
from flask import Flask
import threading
from utils import start_html_stream
import os
import time
import cv2
import socket

def get_video_file():
    return os.path.join("videos", "classroom.mp4")

video_file = get_video_file()

cap = cv2.VideoCapture(video_file)
framerate = cap.get(cv2.CAP_PROP_FPS)
cap.release()

stream = CamGear(source=video_file).start()
app = Flask(__name__)
output_frame = [None]
lock = threading.Lock()

PORT = 7860

@app.route('/')
def html_stream():
    return start_html_stream(output_frame, lock)

def start_flask():
    app.run(host="0.0.0.0", port=PORT, debug=True, use_reloader=False)

def process_stream():
    global stream
    while True:
        start_time = time.time()
        frame = stream.read()
        if frame is None:
            stream.stop()
            stream = CamGear(source=video_file).start()
            continue
        
        with lock:
            output_frame[0] = frame.copy()
        
        elapsed_time = time.time() - start_time
        sleep_time = max(1.0 / framerate - elapsed_time, 0)
        time.sleep(sleep_time)

def main():
    flask_thread = threading.Thread(target=start_flask)
    flask_thread.daemon = True
    flask_thread.start()
    
    stream_thread = threading.Thread(target=process_stream)
    stream_thread.daemon = True
    stream_thread.start()
    
    flask_thread.join()
    stream_thread.join()

if __name__ == "__main__":
    main()