-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcamera.py
93 lines (73 loc) · 2.33 KB
/
camera.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import time
from flask import Response, Flask
from flask_cors import CORS
from threading import Thread, Lock
import cv2
global video_frame
video_frame = None
global thread_lock
thread_lock = Lock()
class Webcam:
'''
Camera class to handle video capture with a laptop webcam using OpenCV
'''
def __init__(self, image_w=640, image_h=480, framerate=30):
self.w = image_w
self.h = image_h
self.framerate = framerate
self.running = True
self.frame = None
def init_camera(self):
# initialize the camera
self.camera = cv2.VideoCapture(0)
# Set resolution
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, self.w)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, self.h)
print('Webcam loaded.. .warming camera')
time.sleep(2)
def update(self):
self.init_camera()
while self.running:
self.poll_camera()
def poll_camera(self):
global video_frame, thread_lock
self.ret, frame = self.camera.read()
if frame is not None:
with thread_lock:
video_frame = frame.copy()
self.frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
def run(self):
self.poll_camera()
return self.frame
def run_threaded(self):
return self.frame
def shutdown(self):
self.running = False
print('stopping Webcam')
time.sleep(.5)
self.camera.release()
def encodeFrame():
global thread_lock
while True:
with thread_lock:
global video_frame
if video_frame is None:
continue
return_key, encoded_image = cv2.imencode(".jpg", video_frame)
if not return_key:
continue
yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encoded_image) + b'\r\n')
# Create the Flask object for the application
app = Flask(__name__)
CORS(app)
@app.route("/")
def streamFrames():
return Response(encodeFrame(), mimetype="multipart/x-mixed-replace; boundary=frame")
if __name__ == '__main__':
cam = Webcam(image_w=640, image_h=480)
# Create a thread for processing image frames
process_thread = Thread(target=cam.update)
process_thread.daemon = True
process_thread.start()
app.run("0.0.0.0", port="8000")