forked from pupil-labs/pupil-picoflexx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.py
396 lines (318 loc) · 11.9 KB
/
backend.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2019 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)
"""
import itertools
import logging
import queue
from time import sleep, time
import numpy as np
from pyglui import ui
import cv2
import cython_methods
from camera_models import load_intrinsics, Radial_Dist_Camera
from video_capture import manager_classes
from video_capture.base_backend import Base_Manager, Base_Source, Playback_Source
logger = logging.getLogger(__name__)
try:
import picoflexx.roypy as roypy
from picoflexx.roypy_platform_utils import PlatformHelper
except ImportError:
import traceback
logger.debug(traceback.format_exc())
logger.info("Pico Flexx backend requirements (roypy) not installed properly")
raise
try:
from . import roypycy
except ImportError:
import traceback
logger.debug(traceback.format_exc())
logger.warning("Pico Flexx backend requirements (roypycy) not installed properly")
raise
class Frame(object):
"""docstring of Frame"""
current_index = 0
def __init__(self, depth_data):
# self.timestamp = depth_data.timeStamp # Not memory safe!
self.timestamp = None
self._data = roypycy.get_backend_data(depth_data)
self.height = depth_data.height
self.width = depth_data.width
self.shape = depth_data.height, depth_data.width, 3
self.index = self.current_index
self.current_index += 1
# indicate that the frame does not have a native yuv or jpeg buffer
self.yuv_buffer = None
self.jpeg_buffer = None
self._img = None
self._gray = None
@property
def img(self):
if self._img is None:
depth_values = self._data.z.reshape(self.height, self.width)
depth_values = (2 ** 16) * depth_values / depth_values.max()
depth_values = depth_values.astype(np.uint16)
self._img = cython_methods.cumhist_color_map16(depth_values)
return self._img
@property
def gray(self):
if self._gray is None:
self._gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
return self._gray
@property
def bgr(self):
return self.img
@property
def confidence(self):
return self._data.depthConfidence.reshape(self.height, self.width)
@property
def noise(self):
return self._data.noise.reshape(self.height, self.width)
@property
def dense_pointcloud(self):
return self._data[["x", "y", "z"]]
class DepthDataListener(roypy.IDepthDataListener):
def __init__(self, queue):
super().__init__()
self.queue = queue
def onNewData(self, data):
try:
self.queue.put(Frame(data), block=False)
except queue.Full:
pass # dropping frame
except Exception:
import traceback
traceback.print_exc()
class Picoflexx_Source(Playback_Source, Base_Source):
name = "Picoflexx"
def __init__(self, g_pool, color_z_min=0.4, color_z_max=1.0, *args, **kwargs):
super().__init__(g_pool, *args, **kwargs)
self.color_z_min = color_z_min
self.color_z_max = color_z_max
self.camera = None
self.queue = queue.Queue(maxsize=1)
self.data_listener = DepthDataListener(self.queue)
self.init_device()
self.fps = 30
self.frame_count = 0
self._ui_exposure = None
self._current_exposure = (
0
) # TODO obtain current exposure from most recent DepthData event
self._current_exposure_mode = False
def init_device(self):
cam_manager = roypy.CameraManager()
try:
cam_id = cam_manager.getConnectedCameraList()[0]
except IndexError:
logger.error("No Pico Flexx camera connected")
return
self.camera_id = cam_id
self.camera = cam_manager.createCamera(cam_id)
self.camera.initialize()
self.camera.registerDataListener(self.data_listener)
self.camera.startCapture()
roypycy.set_exposure_mode(self.camera, 1)
self._current_exposure_mode = self.get_exposure_mode()
self._online = True
def init_ui(self): # was gui
self.add_menu()
self.menu.label = "Pico Flexx"
self.update_ui()
def update_ui(self):
del self.menu[:]
text = ui.Info_Text("Pico Flexx Options")
self.menu.append(text)
if self.online:
use_cases = self.camera.getUseCases()
use_cases = [
use_cases[uc]
for uc in range(use_cases.size())
if "MIXED" not in use_cases[uc]
]
default = "Select to activate"
use_cases.insert(0, default)
self.menu.append(
ui.Selector(
"selected_usecase",
selection=use_cases,
getter=lambda: default,
setter=self.set_usecase,
label="Activate usecase",
)
)
exposure_limits = self.camera.getExposureLimits()
self.menu.append(
ui.Slider(
"selected_exposure",
min=exposure_limits.first,
max=exposure_limits.second,
getter=lambda: self._current_exposure,
setter=self.set_exposure_delayed,
label="Exposure",
)
)
self._ui_exposure = self.menu[-1]
self.menu.append(
ui.Switch(
"selected_exposure_mode",
getter=lambda: self._current_exposure_mode,
setter=self.set_exposure_mode,
label="Auto Exposure",
)
)
else:
text = ui.Info_Text("Pico Flexx needs to be reactivated")
self.menu.append(text)
def deinit_ui(self):
self.remove_menu()
def cleanup(self):
if self.camera:
if self.camera.isConnected() and self.camera.isCapturing():
self.camera.stopCapture()
self.camera.unregisterDataListener()
self.camera = None
def on_notify(self, notification):
if notification["subject"] == "picoflexx.set_exposure":
self.set_exposure(notification["exposure"])
def set_usecase(self, usecase):
if self.camera.isCapturing():
self.camera.stopCapture()
self.camera.setUseCase(usecase)
# Update UI with expsoure limits of this use case
exposure_limits = self.camera.getExposureLimits()
self._ui_exposure.minimum = exposure_limits.first
self._ui_exposure.maximum = exposure_limits.second
if self._current_exposure > exposure_limits.second:
# Exposure is implicitly clamped to new max
self._current_exposure = exposure_limits.second
self.camera.startCapture()
def set_exposure_delayed(self, exposure):
self.notify_all(
{"subject": "picoflexx.set_exposure", "delay": 0.3, "exposure": exposure}
)
def set_exposure(self, exposure):
status = self.camera.setExposureTime(exposure)
if status != 0:
logger.warning(
"setExposureTime: Non-zero return: {} - {}".format(
status, roypy.getStatusString(status)
)
)
self._current_exposure = exposure
def get_exposure_mode(self):
return roypycy.get_exposure_mode(self.camera) == 1
def set_exposure_mode(self, exposure_mode):
roypycy.set_exposure_mode(self.camera, 1 if exposure_mode else 0)
self._current_exposure_mode = exposure_mode
def recent_events(self, events):
frame = self.get_frame()
if frame:
events["frame"] = frame
self._recent_frame = frame
def get_frame(self):
try:
frame = self.queue.get(True, 0.02)
except queue.Empty:
return
# Given: timestamp in microseconds precision (time since epoch 1970)
# Overwrite with Capture timestamp
frame.timestamp = self.g_pool.get_timestamp()
return frame
@property
def frame_size(self):
return (
(self._recent_frame.width, self._recent_frame.height)
if self._recent_frame
else (1280, 720)
)
# @frame_size.setter
# def frame_size(self, new_size):
# # closest match for size
# sizes = [abs(r[0] - new_size[0]) for r in self.frame_sizes]
# best_size_idx = sizes.index(min(sizes))
# size = self.frame_sizes[best_size_idx]
# if size != new_size:
# logger.warning(
# "%s resolution capture mode not available. Selected %s."
# % (new_size, size)
# )
# self.make_img(size)
@property
def frame_rates(self):
return (30, 30)
@property
def frame_sizes(self):
return ((640, 480), (1280, 720), (1920, 1080))
@property
def frame_rate(self):
return self.fps
@frame_rate.setter
def frame_rate(self, new_rate):
rates = [abs(r - new_rate) for r in self.frame_rates]
best_rate_idx = rates.index(min(rates))
rate = self.frame_rates[best_rate_idx]
if rate != new_rate:
logger.warning(
"%sfps capture mode not available at (%s) on 'Fake Source'. Selected %sfps. "
% (new_rate, self.frame_size, rate)
)
self.fps = rate
@property
def jpeg_support(self):
return False
@property
def online(self):
return self.camera and self.camera.isConnected() and self.camera.isCapturing()
@property
def intrinsics(self):
if self._intrinsics is None or self._intrinsics.resolution != self.frame_size:
lens_params = roypycy.get_lens_parameters(self.camera)
c_x, c_y = lens_params["principalPoint"]
f_x, f_y = lens_params["focalLength"]
p_1, p_2 = lens_params["distortionTangential"]
k_1, k_2, *k_other = lens_params["distortionRadial"]
K = [[f_x, 0.0, c_x], [0.0, f_y, c_y], [0.0, 0.0, 1.0]]
D = k_1, k_2, p_1, p_2, *k_other
self._intrinsics = Radial_Dist_Camera(K, D, self.frame_size, self.name)
return self._intrinsics
@intrinsics.setter
def intrinsics(self, model):
logger.error("Picoflexx backend does not support setting intrinsics manually")
class Picoflexx_Manager(Base_Manager):
"""Simple manager to explicitly activate a fake source"""
gui_name = "Pico Flexx"
def __init__(self, g_pool):
super().__init__(g_pool)
# Initiates the UI for starting the webcam.
def init_ui(self):
self.add_menu()
from pyglui import ui
self.menu.append(ui.Info_Text("Backend for https://pmdtec.com/picofamily/"))
self.menu.append(ui.Button("Activate Pico Flexx", self.activate_source))
def activate_source(self):
settings = {}
settings["name"] = "Picoflexx_Source"
# if the user set fake capture, we dont want it to auto jump back to the old capture.
if self.g_pool.process == "world":
self.notify_all(
{
"subject": "start_plugin",
"name": "Picoflexx_Source",
"args": settings,
}
)
else:
logger.warning("Pico Flexx backend is not supported in the eye process.")
def deinit_ui(self):
self.remove_menu()
def recent_events(self, events):
pass
def get_init_dict(self):
return {}
manager_classes.append(Picoflexx_Manager)