-
Notifications
You must be signed in to change notification settings - Fork 253
/
CameraLoader.py
204 lines (167 loc) · 6.02 KB
/
CameraLoader.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
import cv2
import time
import torch
import numpy as np
from queue import Queue
from threading import Thread, Lock
class CamLoader:
"""Use threading to capture a frame from camera for faster frame load.
Recommend for camera or webcam.
Args:
camera: (int, str) Source of camera or video.,
preprocess: (Callable function) to process the frame before return.
"""
def __init__(self, camera, preprocess=None, ori_return=False):
self.stream = cv2.VideoCapture(camera)
assert self.stream.isOpened(), 'Cannot read camera source!'
self.fps = self.stream.get(cv2.CAP_PROP_FPS)
self.frame_size = (int(self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)))
self.stopped = False
self.ret = False
self.frame = None
self.ori_frame = None
self.read_lock = Lock()
self.ori = ori_return
self.preprocess_fn = preprocess
def start(self):
self.t = Thread(target=self.update, args=()) # , daemon=True)
self.t.start()
c = 0
while not self.ret:
time.sleep(0.1)
c += 1
if c > 20:
self.stop()
raise TimeoutError('Can not get a frame from camera!!!')
return self
def update(self):
while not self.stopped:
ret, frame = self.stream.read()
self.read_lock.acquire()
self.ori_frame = frame.copy()
if ret and self.preprocess_fn is not None:
frame = self.preprocess_fn(frame)
self.ret, self.frame = ret, frame
self.read_lock.release()
def grabbed(self):
"""Return `True` if can read a frame."""
return self.ret
def getitem(self):
self.read_lock.acquire()
frame = self.frame.copy()
ori_frame = self.ori_frame.copy()
self.read_lock.release()
if self.ori:
return frame, ori_frame
else:
return frame
def stop(self):
if self.stopped:
return
self.stopped = True
if self.t.is_alive():
self.t.join()
self.stream.release()
def __del__(self):
if self.stream.isOpened():
self.stream.release()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.stream.isOpened():
self.stream.release()
class CamLoader_Q:
"""Use threading and queue to capture a frame and store to queue for pickup in sequence.
Recommend for video file.
Args:
camera: (int, str) Source of camera or video.,
batch_size: (int) Number of batch frame to store in queue. Default: 1,
queue_size: (int) Maximum queue size. Default: 256,
preprocess: (Callable function) to process the frame before return.
"""
def __init__(self, camera, batch_size=1, queue_size=256, preprocess=None):
self.stream = cv2.VideoCapture(camera)
assert self.stream.isOpened(), 'Cannot read camera source!'
self.fps = self.stream.get(cv2.CAP_PROP_FPS)
self.frame_size = (int(self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# Queue for storing each frames.
self.stopped = False
self.batch_size = batch_size
self.Q = Queue(maxsize=queue_size)
self.preprocess_fn = preprocess
def start(self):
t = Thread(target=self.update, args=(), daemon=True).start()
c = 0
while not self.grabbed():
time.sleep(0.1)
c += 1
if c > 20:
self.stop()
raise TimeoutError('Can not get a frame from camera!!!')
return self
def update(self):
while not self.stopped:
if not self.Q.full():
frames = []
for k in range(self.batch_size):
ret, frame = self.stream.read()
if not ret:
self.stop()
return
if self.preprocess_fn is not None:
frame = self.preprocess_fn(frame)
frames.append(frame)
frames = np.stack(frames)
self.Q.put(frames)
else:
with self.Q.mutex:
self.Q.queue.clear()
# time.sleep(0.05)
def grabbed(self):
"""Return `True` if can read a frame."""
return self.Q.qsize() > 0
def getitem(self):
return self.Q.get().squeeze()
def stop(self):
if self.stopped:
return
self.stopped = True
self.stream.release()
def __len__(self):
return self.Q.qsize()
def __del__(self):
if self.stream.isOpened():
self.stream.release()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.stream.isOpened():
self.stream.release()
if __name__ == '__main__':
fps_time = 0
# Using threading.
cam = CamLoader(0).start()
while cam.grabbed():
frames = cam.getitem()
frames = cv2.putText(frames, 'FPS: %f' % (1.0 / (time.time() - fps_time)),
(10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
fps_time = time.time()
cv2.imshow('frame', frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cam.stop()
cv2.destroyAllWindows()
# Normal video capture.
"""cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
if ret:
#time.sleep(0.05)
#frame = (cv2.flip(frame, 1) / 255.).astype(np.float)
frame = cv2.putText(frame, 'FPS: %f' % (1.0 / (time.time() - fps_time)),
(10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
fps_time = time.time()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cam.release()
cv2.destroyAllWindows()"""