etho-python 0.22.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- etho/__init__.py +9 -0
- etho/app.py +569 -0
- etho/assets/etho_icon1_pipeline_dark.svg +23 -0
- etho/assets/etho_icon1_pipeline_light.svg +30 -0
- etho/cli.py +215 -0
- etho/client.py +384 -0
- etho/services/ANAZeroService.py +123 -0
- etho/services/BLTZeroService.py +108 -0
- etho/services/DAQZeroService.py +326 -0
- etho/services/DLPZeroService.py +240 -0
- etho/services/GCMZeroService.py +271 -0
- etho/services/GOVZeroService.py +231 -0
- etho/services/NICounterZeroService.py +92 -0
- etho/services/NITriggerZeroService.py +120 -0
- etho/services/TemplateZeroService.py +98 -0
- etho/services/ZeroService.py +272 -0
- etho/services/__init__.py +0 -0
- etho/services/callbacks/__init__.py +19 -0
- etho/services/callbacks/_base.py +92 -0
- etho/services/callbacks/_image.py +798 -0
- etho/services/callbacks/_trace.py +456 -0
- etho/services/camera/__init__.py +13 -0
- etho/services/camera/base.py +164 -0
- etho/services/camera/basler.py +201 -0
- etho/services/camera/dummy.py +139 -0
- etho/services/camera/hamamatsu.py +133 -0
- etho/services/camera/spinnaker.py +317 -0
- etho/services/camera/ximea.py +167 -0
- etho/services/daq/IOTask.py +311 -0
- etho/services/daq/ai.py +174 -0
- etho/services/dlp/dlp_make_warpfiles.py +131 -0
- etho/services/dlp/dlp_runners.py +238 -0
- etho/services/utils/__init__.py +0 -0
- etho/services/utils/concurrent_task.py +236 -0
- etho/services/utils/log_exceptions.py +39 -0
- etho/utils/__init__.py +0 -0
- etho/utils/calibration.py +88 -0
- etho/utils/config.py +41 -0
- etho/utils/runner.py +121 -0
- etho/utils/shuffled_cycle.py +45 -0
- etho/utils/sound.py +336 -0
- etho/utils/tui.py +105 -0
- etho/utils/zeroclient.py +95 -0
- etho_python-0.22.0.dist-info/METADATA +49 -0
- etho_python-0.22.0.dist-info/RECORD +47 -0
- etho_python-0.22.0.dist-info/WHEEL +4 -0
- etho_python-0.22.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
"""Callbacks for processing images."""
|
|
2
|
+
import logging
|
|
3
|
+
from xml.dom import NotFoundErr
|
|
4
|
+
import numpy as np
|
|
5
|
+
from . import register_callback
|
|
6
|
+
from ._base import BaseCallback
|
|
7
|
+
from ..utils.concurrent_task import ConcurrentTask
|
|
8
|
+
from ..utils.log_exceptions import for_all_methods, log_exceptions
|
|
9
|
+
from typing import Optional, Dict, Any
|
|
10
|
+
import tables
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
import cv2
|
|
15
|
+
cv2_import_error = None
|
|
16
|
+
except ImportError as cv2_import_error:
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import ffmpegcv
|
|
21
|
+
ffmpegcv_import_error = None
|
|
22
|
+
except ImportError as ffmpegcv_import_error:
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
from vidgear.gears import WriteGear
|
|
27
|
+
vidgear_import_error = None
|
|
28
|
+
except ImportError as vidgear_import_error:
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
from qtpy import QtWidgets
|
|
33
|
+
import pyqtgraph as pg
|
|
34
|
+
from pyqtgraph.widgets.RawImageWidget import RawImageWidget
|
|
35
|
+
pyqtgraph_import_error = None
|
|
36
|
+
except Exception as pyqtgraph_import_error: # catch generic Exception to cover missing Qt error from pyqtgraph
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
import zarr
|
|
41
|
+
from numcodecs import Blosc
|
|
42
|
+
|
|
43
|
+
zarr_import_error = None
|
|
44
|
+
except Exception as zarr_import_error: # catch generic Exception to cover missing Qt error from pyqtgraph
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger(__name__)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@for_all_methods(log_exceptions(logger))
|
|
53
|
+
class ImageCallback(BaseCallback):
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
data_source,
|
|
57
|
+
poll_timeout: float = None,
|
|
58
|
+
rate: float = 0,
|
|
59
|
+
file_name: str = None,
|
|
60
|
+
frame_rate: float = None,
|
|
61
|
+
frame_width: float = None,
|
|
62
|
+
frame_height: float = None,
|
|
63
|
+
**kwargs,
|
|
64
|
+
):
|
|
65
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, rate=rate, **kwargs)
|
|
66
|
+
|
|
67
|
+
self.frame_rate = frame_rate
|
|
68
|
+
self.frame_width = frame_width
|
|
69
|
+
self.frame_height = frame_height
|
|
70
|
+
self.file_name = file_name
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@for_all_methods(log_exceptions(logger))
|
|
74
|
+
@register_callback
|
|
75
|
+
class ImageDisplayCV2(ImageCallback):
|
|
76
|
+
|
|
77
|
+
FRIENDLY_NAME = "disp"
|
|
78
|
+
TIMESTAMPS_ONLY = False
|
|
79
|
+
|
|
80
|
+
def __init__(self, data_source, poll_timeout=0.01, **kwargs):
|
|
81
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
82
|
+
|
|
83
|
+
if cv2_import_error is not None:
|
|
84
|
+
logger.exception('Could not import cv2. Aborting!', exc_info=cv2_import_error)
|
|
85
|
+
raise cv2_import_error
|
|
86
|
+
|
|
87
|
+
logger.info("setting up disp")
|
|
88
|
+
cv2.namedWindow("display")
|
|
89
|
+
cv2.resizeWindow("display", self.frame_width, self.frame_height)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def make_concurrent(cls, comms="pipe", **kwargs):
|
|
93
|
+
return ConcurrentTask(task=cls.make_run, comms=comms, **kwargs)
|
|
94
|
+
|
|
95
|
+
def _loop(self, data):
|
|
96
|
+
if self.data_source.WHOAMI == "array":
|
|
97
|
+
image = data
|
|
98
|
+
else:
|
|
99
|
+
image, timestamp = data
|
|
100
|
+
|
|
101
|
+
cv2.imshow("display", image)
|
|
102
|
+
cv2.waitKey(1)
|
|
103
|
+
|
|
104
|
+
def _cleanup(self):
|
|
105
|
+
logger.info("closing display")
|
|
106
|
+
cv2.destroyWindow("display")
|
|
107
|
+
super()._cleanup()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@for_all_methods(log_exceptions(logger))
|
|
111
|
+
@register_callback
|
|
112
|
+
class ImageDisplayPQG(ImageCallback):
|
|
113
|
+
|
|
114
|
+
FRIENDLY_NAME = "disp_fast"
|
|
115
|
+
TIMESTAMPS_ONLY = False
|
|
116
|
+
|
|
117
|
+
def __init__(self, data_source, *, poll_timeout=0.01, **kwargs):
|
|
118
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
119
|
+
|
|
120
|
+
if pyqtgraph_import_error is not None:
|
|
121
|
+
logger.exception('Could not import pyqtgraph. Aborting!', exc_info=pyqtgraph_import_error)
|
|
122
|
+
raise pyqtgraph_import_error
|
|
123
|
+
|
|
124
|
+
logger.info("setting up ImageDisplayPQG")
|
|
125
|
+
|
|
126
|
+
pg.setConfigOption("background", "w")
|
|
127
|
+
pg.setConfigOption("leftButtonPan", False)
|
|
128
|
+
|
|
129
|
+
# set up window and subplots
|
|
130
|
+
self.app = QtWidgets.QApplication([])
|
|
131
|
+
self.win = RawImageWidget(scaled=True)
|
|
132
|
+
self.win.resize(self.frame_width, self.frame_height)
|
|
133
|
+
self.win.show()
|
|
134
|
+
self.app.processEvents()
|
|
135
|
+
|
|
136
|
+
@classmethod
|
|
137
|
+
def make_concurrent(cls, comms="pipe", **kwargs):
|
|
138
|
+
return ConcurrentTask(task=cls.make_run, comms=comms, **kwargs)
|
|
139
|
+
|
|
140
|
+
def _loop(self, data):
|
|
141
|
+
if self.data_source.WHOAMI == "array":
|
|
142
|
+
image = data
|
|
143
|
+
else:
|
|
144
|
+
image, timestamp = data
|
|
145
|
+
|
|
146
|
+
self.win.setImage(image)
|
|
147
|
+
self.app.processEvents()
|
|
148
|
+
|
|
149
|
+
def _cleanup(self):
|
|
150
|
+
logger.info("closing display")
|
|
151
|
+
# close app and windows here
|
|
152
|
+
self.app.closeAllWindows()
|
|
153
|
+
super()._cleanup()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@for_all_methods(log_exceptions(logger))
|
|
157
|
+
@register_callback
|
|
158
|
+
class ImageWriterCV2(ImageCallback):
|
|
159
|
+
"""Save images to video using opencv's VideoWriter.
|
|
160
|
+
|
|
161
|
+
Fast but little control over video compression quality.
|
|
162
|
+
|
|
163
|
+
Requirements:
|
|
164
|
+
- ffmpeg (?): `mamba install ffmpeg -c conda-forge
|
|
165
|
+
- openh264 (?) form the cisco github page
|
|
166
|
+
- opencv: `mamba install opencv -c conda-forge`
|
|
167
|
+
|
|
168
|
+
Raises:
|
|
169
|
+
cv2_import_error: If cv2 (opencv) could not be imported.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
ImageCallback (_type_): _description_
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
SUFFIX: str = ".avi"
|
|
176
|
+
FRIENDLY_NAME = "save_avi"
|
|
177
|
+
TIMESTAMPS_ONLY = False
|
|
178
|
+
|
|
179
|
+
def __init__(self, data_source, *, poll_timeout=0.01, **kwargs):
|
|
180
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
181
|
+
|
|
182
|
+
if cv2_import_error is not None:
|
|
183
|
+
logger.exception('Could not import cv2. Aborting!', exc_info=cv2_import_error)
|
|
184
|
+
raise cv2_import_error
|
|
185
|
+
|
|
186
|
+
self.vw = cv2.VideoWriter()
|
|
187
|
+
self.vw.open(
|
|
188
|
+
self.file_name + self.SUFFIX,
|
|
189
|
+
cv2.VideoWriter_fourcc(*"x264"),
|
|
190
|
+
self.frame_rate,
|
|
191
|
+
(self.frame_height, self.frame_width),
|
|
192
|
+
True,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def _loop(self, data):
|
|
196
|
+
if hasattr(self.data_source, "WHOAMI") and self.data_source.WHOAMI == "array":
|
|
197
|
+
image = data
|
|
198
|
+
else:
|
|
199
|
+
image, timestamp = data
|
|
200
|
+
|
|
201
|
+
self.vw.write(image)
|
|
202
|
+
|
|
203
|
+
def _cleanup(self):
|
|
204
|
+
self.vw.release()
|
|
205
|
+
del self.vw
|
|
206
|
+
super()._cleanup()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@for_all_methods(log_exceptions(logger))
|
|
211
|
+
@register_callback
|
|
212
|
+
class ImageWriterFCV(ImageCallback):
|
|
213
|
+
"""Save images to video using ffmpegcv.
|
|
214
|
+
|
|
215
|
+
Supports hardware accelerated encoding
|
|
216
|
+
Requirements:
|
|
217
|
+
- ffmpeg>=6 (?): `mamba install ffmpeg>=6 -c conda-forge
|
|
218
|
+
- ffmpegcv: `pip install ffmpegcv`
|
|
219
|
+
|
|
220
|
+
Raises:
|
|
221
|
+
ffmpegcv_import_error: If ffmpegcv could not be imported.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
ImageCallback (_type_): _description_
|
|
225
|
+
"""
|
|
226
|
+
|
|
227
|
+
SUFFIX: str = ".mp4"
|
|
228
|
+
FRIENDLY_NAME = "save_ffmpegcv"
|
|
229
|
+
TIMESTAMPS_ONLY = False
|
|
230
|
+
|
|
231
|
+
def __init__(self, data_source, *, poll_timeout=0.01, **kwargs):
|
|
232
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
233
|
+
|
|
234
|
+
if ffmpegcv_import_error is not None:
|
|
235
|
+
logger.exception('Could not import ffmpegcv. Aborting!', exc_info=ffmpegcv_import_error)
|
|
236
|
+
raise ffmpegcv_import_error
|
|
237
|
+
|
|
238
|
+
# self.vw = ffmpegcv.VideoWriter()
|
|
239
|
+
self.vw = ffmpegcv.VideoWriter(
|
|
240
|
+
self.file_name + self.SUFFIX,
|
|
241
|
+
# 'hevc',
|
|
242
|
+
# self.frame_rate,
|
|
243
|
+
# (self.frame_height, self.frame_width),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
def _loop(self, data):
|
|
247
|
+
if hasattr(self.data_source, "WHOAMI") and self.data_source.WHOAMI == "array":
|
|
248
|
+
image = data
|
|
249
|
+
else:
|
|
250
|
+
image, timestamp = data
|
|
251
|
+
|
|
252
|
+
self.vw.write(image)
|
|
253
|
+
|
|
254
|
+
def _cleanup(self):
|
|
255
|
+
self.vw.release()
|
|
256
|
+
del self.vw
|
|
257
|
+
super()._cleanup()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@for_all_methods(log_exceptions(logger))
|
|
261
|
+
@register_callback
|
|
262
|
+
class ImageWriterCVR(ImageCallback):
|
|
263
|
+
"""Round robin videowriter - see ImageWriterVidGear for details.
|
|
264
|
+
|
|
265
|
+
Will switch after a specified to a new file.
|
|
266
|
+
Naming patter `f"{file_name}_{video_count:06d}.avi"`, for instance "testvideo_000012.avi"
|
|
267
|
+
|
|
268
|
+
Special protocol parameters:
|
|
269
|
+
```yaml
|
|
270
|
+
callbacks:
|
|
271
|
+
save_vidgear:
|
|
272
|
+
ffmpeg_params: # dict with parameters to pass to ffmpeg
|
|
273
|
+
-crf: 16
|
|
274
|
+
max_frames_per_video: 100_000 # number of frames after which to switch to new video file
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
SUFFIX: str = ".avi"
|
|
280
|
+
FRIENDLY_NAME = "save_vidgear_round"
|
|
281
|
+
TIMESTAMPS_ONLY = False
|
|
282
|
+
|
|
283
|
+
def __init__(
|
|
284
|
+
self,
|
|
285
|
+
data_source,
|
|
286
|
+
*,
|
|
287
|
+
poll_timeout=0.01,
|
|
288
|
+
max_frames_per_video=100_000,
|
|
289
|
+
ffmpeg_params: Optional[Dict[str, Any]] = None,
|
|
290
|
+
**kwargs,
|
|
291
|
+
):
|
|
292
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
293
|
+
|
|
294
|
+
if vidgear_import_error is not None:
|
|
295
|
+
logger.exception('No!', exc_info=vidgear_import_error)
|
|
296
|
+
self._cleanup()
|
|
297
|
+
raise vidgear_import_error
|
|
298
|
+
|
|
299
|
+
self.video_count = 0
|
|
300
|
+
self.frame_count = 0
|
|
301
|
+
self.max_frames_per_video = max_frames_per_video
|
|
302
|
+
|
|
303
|
+
self.output_params = {"-input_framerate": self.frame_rate, "-r": self.frame_rate}
|
|
304
|
+
if ffmpeg_params is not None:
|
|
305
|
+
self.output_params.update(ffmpeg_params)
|
|
306
|
+
try:
|
|
307
|
+
self.vw = WriteGear(output_filename=self.file_name + f"_{self.video_count:06d}" + self.SUFFIX, **self.output_params)
|
|
308
|
+
except:
|
|
309
|
+
self.vw = WriteGear(output=self.file_name + f"_{self.video_count:06d}" + self.SUFFIX, **self.output_params)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _loop(self, data):
|
|
313
|
+
if hasattr(self.data_source, "WHOAMI") and self.data_source.WHOAMI == "array":
|
|
314
|
+
image = data
|
|
315
|
+
else:
|
|
316
|
+
image, timestamp = data
|
|
317
|
+
|
|
318
|
+
self.vw.write(image)
|
|
319
|
+
self.frame_count += 1
|
|
320
|
+
if self.frame_count > self.max_frames_per_video:
|
|
321
|
+
self.vw.close()
|
|
322
|
+
del self.vw
|
|
323
|
+
self.frame_count = 0
|
|
324
|
+
self.video_count += 1
|
|
325
|
+
try:
|
|
326
|
+
self.vw = WriteGear(output_filename=self.file_name + f"_{self.video_count:06d}" + self.SUFFIX, **self.output_params)
|
|
327
|
+
except:
|
|
328
|
+
self.vw = WriteGear(output=self.file_name + f"_{self.video_count:06d}" + self.SUFFIX, **self.output_params)
|
|
329
|
+
|
|
330
|
+
def _cleanup(self):
|
|
331
|
+
try:
|
|
332
|
+
self.vw.close()
|
|
333
|
+
del self.vw
|
|
334
|
+
except:
|
|
335
|
+
pass
|
|
336
|
+
super()._cleanup()
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@for_all_methods(log_exceptions(logger))
|
|
340
|
+
@register_callback
|
|
341
|
+
class ImageWriterVidGear(ImageCallback):
|
|
342
|
+
"""Write video files using vidgear [](https://abhitronix.github.io/vidgear/latest/).
|
|
343
|
+
Directly calls ffmpeg for video encoding, works with 100+ fps.
|
|
344
|
+
Gives more control over compression quality, via args to ffmpeg.
|
|
345
|
+
|
|
346
|
+
Requirements:
|
|
347
|
+
- ffmpeg: `mamba install ffmpeg -c conda-forge
|
|
348
|
+
- vidgear: `python -m pip install vidgear[core]`
|
|
349
|
+
|
|
350
|
+
Special protocol parameters:
|
|
351
|
+
- ffmpeg_params: dict with parameters to pass to ffmpeg
|
|
352
|
+
|
|
353
|
+
```yaml
|
|
354
|
+
callbacks:
|
|
355
|
+
save_vidgear:
|
|
356
|
+
ffmpeg_params: # dict with parameters to pass to ffmpeg
|
|
357
|
+
-crf: 16
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
Raises:
|
|
361
|
+
vidgear_import_error: If VidGear could not be imported.
|
|
362
|
+
"""
|
|
363
|
+
|
|
364
|
+
SUFFIX: str = ".avi"
|
|
365
|
+
FRIENDLY_NAME = "save_vidgear"
|
|
366
|
+
TIMESTAMPS_ONLY = False
|
|
367
|
+
|
|
368
|
+
def __init__(self, data_source, *, poll_timeout=0.01, ffmpeg_params: Optional[Dict[str, Any]] = None, **kwargs):
|
|
369
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
370
|
+
|
|
371
|
+
if vidgear_import_error is not None:
|
|
372
|
+
logger.exception('Failed to import VidGear. Closing!', exc_info=vidgear_import_error)
|
|
373
|
+
self._cleanup()
|
|
374
|
+
# raise vidgear_import_error
|
|
375
|
+
|
|
376
|
+
self.output_params = {"-input_framerate": self.frame_rate, "-r": self.frame_rate}
|
|
377
|
+
if ffmpeg_params is not None:
|
|
378
|
+
self.output_params.update(ffmpeg_params)
|
|
379
|
+
try:
|
|
380
|
+
self.vw = WriteGear(output_filename=self.file_name + self.SUFFIX, **self.output_params)
|
|
381
|
+
except:
|
|
382
|
+
self.vw = WriteGear(output=self.file_name + self.SUFFIX, **self.output_params)
|
|
383
|
+
|
|
384
|
+
def _loop(self, data):
|
|
385
|
+
if hasattr(self.data_source, "WHOAMI") and self.data_source.WHOAMI == "array":
|
|
386
|
+
image = data
|
|
387
|
+
else:
|
|
388
|
+
image, timestamp = data
|
|
389
|
+
|
|
390
|
+
self.vw.write(image)
|
|
391
|
+
|
|
392
|
+
def _cleanup(self):
|
|
393
|
+
try:
|
|
394
|
+
self.vw.close()
|
|
395
|
+
del self.vw
|
|
396
|
+
except:
|
|
397
|
+
pass
|
|
398
|
+
super()._cleanup()
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@for_all_methods(log_exceptions(logger))
|
|
403
|
+
@register_callback
|
|
404
|
+
class ImageWriterVPF(ImageCallback):
|
|
405
|
+
"""CUDA-accelerated video encoding using Nvidia's VideoProcessingFramework.
|
|
406
|
+
Very fast (1000fps) and high quality but produce large videos.
|
|
407
|
+
|
|
408
|
+
Requirements:
|
|
409
|
+
- VideoProcessingFramework: https://github.com/NVIDIA/VideoProcessingFramework
|
|
410
|
+
"""
|
|
411
|
+
|
|
412
|
+
SUFFIX: str = ".avi"
|
|
413
|
+
FRIENDLY_NAME = "save_avi_fast"
|
|
414
|
+
TIMESTAMPS_ONLY = False
|
|
415
|
+
|
|
416
|
+
def __init__(self, data_source, *, poll_timeout=0.01, VPF_bin_path=None, **kwargs):
|
|
417
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
418
|
+
|
|
419
|
+
try:
|
|
420
|
+
import sys
|
|
421
|
+
sys.path.append(VPF_bin_path)
|
|
422
|
+
import PyNvCodec as nvc
|
|
423
|
+
except Exception as e:
|
|
424
|
+
logging.exception('Could not import PyNvCodec. Quitting.', exc_info=e)
|
|
425
|
+
self._cleanup()
|
|
426
|
+
|
|
427
|
+
gpuID = 0
|
|
428
|
+
self.encFile = open(self.file_name + self.SUFFIX, "wb")
|
|
429
|
+
# self.nvEnc = nvc.PyNvEncoder({'rc':'vbr_hq','profile': 'high', 'cq': '10', 'codec': 'h264', 'bf':'3',
|
|
430
|
+
# 'fps': str(self.frame_rate), 'temporalaq': '', 'lookahead':'20',
|
|
431
|
+
# 's': f'{self.frame_width}x{self.frame_height}'}, gpuID)
|
|
432
|
+
self.nvEnc = nvc.PyNvEncoder(
|
|
433
|
+
{
|
|
434
|
+
"rc": "vbr_hq",
|
|
435
|
+
"profile": "high",
|
|
436
|
+
"cq": "10",
|
|
437
|
+
"codec": "h264",
|
|
438
|
+
"bf": "3",
|
|
439
|
+
"fps": str(self.frame_rate),
|
|
440
|
+
"temporalaq": "",
|
|
441
|
+
"lookahead": "20",
|
|
442
|
+
"s": f"{self.frame_height}x{self.frame_width}",
|
|
443
|
+
},
|
|
444
|
+
gpuID,
|
|
445
|
+
)
|
|
446
|
+
self.nvUpl = nvc.PyFrameUploader(self.nvEnc.Width(), self.nvEnc.Height(), nvc.PixelFormat.YUV420, gpuID)
|
|
447
|
+
self.nvCvt = nvc.PySurfaceConverter(
|
|
448
|
+
self.nvEnc.Width(), self.nvEnc.Height(), nvc.PixelFormat.YUV420, nvc.PixelFormat.NV12, gpuID
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
def _loop(self, data):
|
|
452
|
+
image, timestamp = data
|
|
453
|
+
rawFrameYUV420 = cv2.cvtColor(image, cv2.COLOR_RGB2YUV_I420) # convert to YUV420 - nvenc can't handle RGB inputs
|
|
454
|
+
rawSurfaceYUV420 = self.nvUpl.UploadSingleFrame(rawFrameYUV420) # upload YUV420 frame to GPU
|
|
455
|
+
if rawSurfaceYUV420.Empty():
|
|
456
|
+
return # break
|
|
457
|
+
rawSurfaceNV12 = self.nvCvt.Execute(rawSurfaceYUV420) # convert YUV420 to NV12
|
|
458
|
+
if rawSurfaceNV12.Empty():
|
|
459
|
+
return # break
|
|
460
|
+
encFrame = self.nvEnc.EncodeSingleSurface(rawSurfaceNV12) # compres NV12 and download
|
|
461
|
+
self._write_frame(encFrame)
|
|
462
|
+
|
|
463
|
+
def _write_frame(self, encFrame):
|
|
464
|
+
# save compressd byte stream to file
|
|
465
|
+
if encFrame.size:
|
|
466
|
+
encByteArray = bytearray(encFrame) # save compressd byte stream to file
|
|
467
|
+
self.encFile.write(encByteArray)
|
|
468
|
+
|
|
469
|
+
def _cleanup(self):
|
|
470
|
+
# Encoder is asyncronous, so we need to flush it
|
|
471
|
+
encFrames = self.nvEnc.Flush()
|
|
472
|
+
for encFrame in encFrames:
|
|
473
|
+
self._write_frame(encFrame)
|
|
474
|
+
self.encFile.close()
|
|
475
|
+
super()._cleanup()
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
@for_all_methods(log_exceptions(logging.getLogger(__name__)))
|
|
479
|
+
@register_callback
|
|
480
|
+
class ImageWriterH5(BaseCallback):
|
|
481
|
+
|
|
482
|
+
FRIENDLY_NAME = "saveimg_h5"
|
|
483
|
+
SUFFIX = "_images.h5"
|
|
484
|
+
|
|
485
|
+
def __init__(self, data_source, *, file_name, attrs=None, poll_timeout=0.01, **kwargs):
|
|
486
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
487
|
+
self.file_name = file_name
|
|
488
|
+
self.f = tables.open_file(self.file_name + self.SUFFIX, mode="w")
|
|
489
|
+
self.vanilla: bool = True
|
|
490
|
+
self.arrays = dict()
|
|
491
|
+
self.attrs = attrs
|
|
492
|
+
|
|
493
|
+
@classmethod
|
|
494
|
+
def make_concurrent(cls, task_kwargs, comms="queue"):
|
|
495
|
+
return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
|
|
496
|
+
|
|
497
|
+
def _init_data(self, data, timestamp):
|
|
498
|
+
filters = tables.Filters(complevel=4, complib="zlib", fletcher32=True)
|
|
499
|
+
|
|
500
|
+
self.arrays["images"] = self.f.create_earray(
|
|
501
|
+
self.f.root,
|
|
502
|
+
"images",
|
|
503
|
+
tables.Atom.from_dtype(data.dtype),
|
|
504
|
+
shape=[0, *data.shape[1:]],
|
|
505
|
+
chunkshape=[10, *data.shape[1:]],
|
|
506
|
+
filters=filters,
|
|
507
|
+
)
|
|
508
|
+
if self.attrs is not None:
|
|
509
|
+
for key, val in self.attrs.items():
|
|
510
|
+
self.arrays["images"].attrs[key] = val
|
|
511
|
+
|
|
512
|
+
self.arrays["timestamp"] = self.f.create_earray(
|
|
513
|
+
self.f.root,
|
|
514
|
+
"timestamp",
|
|
515
|
+
tables.Atom.from_dtype(np.array(timestamp).dtype),
|
|
516
|
+
shape=[0, *timestamp.shape[1:]],
|
|
517
|
+
chunkshape=[10, *timestamp.shape[1:]],
|
|
518
|
+
filters=filters,
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
def _append_data(self, data, timestamp):
|
|
522
|
+
self.arrays["images"].append(data)
|
|
523
|
+
self.arrays["timestamp"].append(timestamp)
|
|
524
|
+
|
|
525
|
+
def _loop(self, data):
|
|
526
|
+
data_to_save, timestamp = data # unpack
|
|
527
|
+
data_to_save = data_to_save[np.newaxis,...]
|
|
528
|
+
timestamp = np.array([timestamp])[:, np.newaxis]
|
|
529
|
+
if self.vanilla:
|
|
530
|
+
self._init_data(data_to_save, timestamp)
|
|
531
|
+
self.vanilla = False
|
|
532
|
+
self._append_data(data_to_save, timestamp)
|
|
533
|
+
|
|
534
|
+
def _cleanup(self):
|
|
535
|
+
if self.f.isopen:
|
|
536
|
+
self.f.flush()
|
|
537
|
+
self.f.close()
|
|
538
|
+
else:
|
|
539
|
+
logging.debug(f"{self.file_name} already closed.")
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@for_all_methods(log_exceptions(logging.getLogger(__name__)))
|
|
543
|
+
@register_callback
|
|
544
|
+
class ImageWriterZarr(BaseCallback):
|
|
545
|
+
|
|
546
|
+
FRIENDLY_NAME = "saveimg_zarr"
|
|
547
|
+
SUFFIX = "_images.zarr"
|
|
548
|
+
|
|
549
|
+
def __init__(self, data_source, *, file_name, attrs=None, poll_timeout=0.01, **kwargs):
|
|
550
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
551
|
+
|
|
552
|
+
if zarr_import_error is not None:
|
|
553
|
+
logger.exception("Could not import zarr. Aborting!", exc_info=tables_import_error)
|
|
554
|
+
raise zarr_import_error
|
|
555
|
+
|
|
556
|
+
self.file_name = file_name
|
|
557
|
+
self.f = zarr.DirectoryStore(self.file_name + self.SUFFIX) # ONLY FOR ZARR2 - otherwise zarr.storage.LocalStore
|
|
558
|
+
self.vanilla: bool = True
|
|
559
|
+
self.arrays = zarr.group(self.f, overwrite=True)
|
|
560
|
+
self.attrs = attrs
|
|
561
|
+
|
|
562
|
+
@classmethod
|
|
563
|
+
def make_concurrent(cls, task_kwargs, comms="queue"):
|
|
564
|
+
return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
|
|
565
|
+
|
|
566
|
+
def _init_data(self, data, timestamp):
|
|
567
|
+
compressor = Blosc(cname="zstd", clevel=3, shuffle=Blosc.BITSHUFFLE)
|
|
568
|
+
|
|
569
|
+
self.arrays.create_dataset("images", shape=(0, *data.shape[1:]), chunks=(30, *data.shape[1:]), dtype=data.dtype, compressor=compressor)
|
|
570
|
+
|
|
571
|
+
if self.attrs is not None:
|
|
572
|
+
for key, val in self.attrs.items():
|
|
573
|
+
self.arrays["images"].attrs[key] = val
|
|
574
|
+
|
|
575
|
+
self.arrays.create_dataset("timestamp", shape=(0, *timestamp.shape[1:]), chunks=(100, *timestamp.shape[1:]), dtype=timestamp.dtype, compressor=None)
|
|
576
|
+
|
|
577
|
+
def _append_data(self, data, timestamp):
|
|
578
|
+
self.arrays["images"].append(data, axis=0)
|
|
579
|
+
self.arrays["timestamp"].append(timestamp, axis=0)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _loop(self, data):
|
|
583
|
+
data_to_save, timestamp = data # unpack
|
|
584
|
+
data_to_save = data_to_save[np.newaxis,...]
|
|
585
|
+
timestamp = np.array([timestamp])[:, np.newaxis]
|
|
586
|
+
if self.vanilla:
|
|
587
|
+
self._init_data(data_to_save, timestamp)
|
|
588
|
+
self.vanilla = False
|
|
589
|
+
self._append_data(data_to_save, timestamp)
|
|
590
|
+
|
|
591
|
+
def _cleanup(self):
|
|
592
|
+
logger.warning("cleaning")
|
|
593
|
+
try:
|
|
594
|
+
self.f.close()
|
|
595
|
+
except:
|
|
596
|
+
logger.debug(f"{self.file_name} already closed.")
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
@for_all_methods(log_exceptions(logger))
|
|
600
|
+
@register_callback
|
|
601
|
+
class TimestampWriterHDF(ImageCallback):
|
|
602
|
+
"""[summary]
|
|
603
|
+
|
|
604
|
+
required params to set in prot:
|
|
605
|
+
increment: int = 1000, data_dim=2,
|
|
606
|
+
|
|
607
|
+
Args:
|
|
608
|
+
BaseCallback ([type]): [description]
|
|
609
|
+
"""
|
|
610
|
+
|
|
611
|
+
SUFFIX: str = "_timestamps.h5"
|
|
612
|
+
FRIENDLY_NAME: str = "save_timestamps"
|
|
613
|
+
TIMESTAMPS_ONLY = True
|
|
614
|
+
|
|
615
|
+
def __init__(self, data_source, *, poll_timeout=0.01, increment: int = 1000, data_dim=2, **kwargs):
|
|
616
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
617
|
+
|
|
618
|
+
import h5py
|
|
619
|
+
|
|
620
|
+
self.increment = increment
|
|
621
|
+
self.f = h5py.File(self.file_name + self.SUFFIX, "w")
|
|
622
|
+
self.ts = self.f.create_dataset(
|
|
623
|
+
name="timeStamps", shape=[self.increment, data_dim], maxshape=[None, data_dim], dtype=np.float64, compression="gzip"
|
|
624
|
+
)
|
|
625
|
+
self.frame_count = 0
|
|
626
|
+
|
|
627
|
+
def _loop(self, data):
|
|
628
|
+
image, timestamp = data
|
|
629
|
+
|
|
630
|
+
if self.frame_count % self.increment == self.increment - 1:
|
|
631
|
+
self.f.flush()
|
|
632
|
+
self.ts.resize(self.ts.shape[0] + self.increment, axis=0)
|
|
633
|
+
|
|
634
|
+
self.ts[self.frame_count] = timestamp
|
|
635
|
+
self.frame_count += 1
|
|
636
|
+
|
|
637
|
+
def _cleanup(self):
|
|
638
|
+
self.ts.resize(self.frame_count, axis=0) # self.ts[:self.frame_count]
|
|
639
|
+
self.f.flush()
|
|
640
|
+
self.f.close()
|
|
641
|
+
super()._cleanup()
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
@for_all_methods(log_exceptions(logger))
|
|
645
|
+
@register_callback
|
|
646
|
+
class ImageDisplayCenterBackCV2(ImageCallback):
|
|
647
|
+
|
|
648
|
+
FRIENDLY_NAME = "disp_back"
|
|
649
|
+
TIMESTAMPS_ONLY = False
|
|
650
|
+
|
|
651
|
+
def __init__(self, data_source, poll_timeout=0.01, center_x=0, center_y=0, **kwargs):
|
|
652
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
653
|
+
|
|
654
|
+
logger.info("setting up disp")
|
|
655
|
+
cv2.namedWindow("display")
|
|
656
|
+
cv2.resizeWindow("display", self.frame_width, self.frame_height)
|
|
657
|
+
|
|
658
|
+
if center_x != 0:
|
|
659
|
+
self.center_x = center_x
|
|
660
|
+
else:
|
|
661
|
+
self.center_x = self.frame_height // 2
|
|
662
|
+
if center_y != 0:
|
|
663
|
+
self.center_y = center_y
|
|
664
|
+
else:
|
|
665
|
+
self.center_y = self.frame_width // 2
|
|
666
|
+
self.color = [0, 0, 250]
|
|
667
|
+
self.thickness = 1
|
|
668
|
+
|
|
669
|
+
@classmethod
|
|
670
|
+
def make_concurrent(cls, comms="pipe", **kwargs):
|
|
671
|
+
return ConcurrentTask(task=cls.make_run, comms=comms, **kwargs)
|
|
672
|
+
|
|
673
|
+
def _loop(self, data):
|
|
674
|
+
if self.data_source.WHOAMI == "array":
|
|
675
|
+
image = data
|
|
676
|
+
else:
|
|
677
|
+
image, timestamp = data
|
|
678
|
+
|
|
679
|
+
image = cv2.rectangle(
|
|
680
|
+
image,
|
|
681
|
+
(self.frame_height - 95, self.frame_width),
|
|
682
|
+
(95, self.frame_width - 45),
|
|
683
|
+
color=self.color,
|
|
684
|
+
thickness=self.thickness,
|
|
685
|
+
) # ball region
|
|
686
|
+
image = cv2.line(
|
|
687
|
+
image, (60, self.center_y), (self.frame_height - 60, self.center_y), self.color, self.thickness
|
|
688
|
+
) # y-axis cross
|
|
689
|
+
image = cv2.line(
|
|
690
|
+
image, (self.center_x, 60), (self.center_x, self.frame_width - 60), self.color, self.thickness
|
|
691
|
+
) # x-axis cross
|
|
692
|
+
# image = cv2.rectangle(image, (self.center_x-40,self.center_y-35), (self.center_x+20,self.center_y+35), color=self.color, thickness=self.thickness) # fly
|
|
693
|
+
cv2.imshow("display", image)
|
|
694
|
+
cv2.waitKey(1)
|
|
695
|
+
|
|
696
|
+
def _cleanup(self):
|
|
697
|
+
logger.info("closing display")
|
|
698
|
+
cv2.destroyWindow("display")
|
|
699
|
+
super()._cleanup()
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
@for_all_methods(log_exceptions(logger))
|
|
703
|
+
@register_callback
|
|
704
|
+
class ImageDisplayCenterTopCV2(ImageCallback):
|
|
705
|
+
|
|
706
|
+
FRIENDLY_NAME = "disp_top"
|
|
707
|
+
TIMESTAMPS_ONLY = False
|
|
708
|
+
|
|
709
|
+
def __init__(self, data_source, poll_timeout=0.01, circ_center_x=0, circ_center_y=0, circ_r=0, **kwargs):
|
|
710
|
+
super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
|
|
711
|
+
|
|
712
|
+
logger.info("setting up disp")
|
|
713
|
+
cv2.namedWindow("display")
|
|
714
|
+
cv2.resizeWindow("display", self.frame_width, self.frame_height)
|
|
715
|
+
|
|
716
|
+
# properties of drawn circle
|
|
717
|
+
if circ_center_x != 0:
|
|
718
|
+
self.circ_center_x = circ_center_x
|
|
719
|
+
else:
|
|
720
|
+
self.circ_center_x = self.frame_height // 2
|
|
721
|
+
if circ_center_y != 0:
|
|
722
|
+
self.circ_center_y = circ_center_y
|
|
723
|
+
else:
|
|
724
|
+
self.circ_center_y = self.frame_width // 2
|
|
725
|
+
if circ_r != 0:
|
|
726
|
+
self.circ_r = circ_r
|
|
727
|
+
else:
|
|
728
|
+
self.circ_r = 10
|
|
729
|
+
self.circ_color = [0, 0, 250]
|
|
730
|
+
self.needle_color = [250, 0, 0]
|
|
731
|
+
self.circ_thickness = 2
|
|
732
|
+
|
|
733
|
+
self.flyhead_topleft, self.flyhead_bottomright = (self.circ_center_x - 45, self.circ_center_y - 50), (
|
|
734
|
+
self.circ_center_x + 5,
|
|
735
|
+
self.circ_center_y + 50,
|
|
736
|
+
)
|
|
737
|
+
self.flybody_topleft, self.flybody_bottomright = (self.circ_center_x, self.circ_center_y - 45), (
|
|
738
|
+
self.circ_center_x + 200,
|
|
739
|
+
self.circ_center_y + 45,
|
|
740
|
+
)
|
|
741
|
+
self.needle_topleft, self.needle_bottomright = (self.circ_center_x + 195, self.circ_center_y - 40), (
|
|
742
|
+
self.frame_width,
|
|
743
|
+
self.circ_center_y + 40,
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
@classmethod
|
|
747
|
+
def make_concurrent(cls, comms="pipe", **kwargs):
|
|
748
|
+
return ConcurrentTask(task=cls.make_run, comms=comms, **kwargs)
|
|
749
|
+
|
|
750
|
+
def _loop(self, data):
|
|
751
|
+
if self.data_source.WHOAMI == "array":
|
|
752
|
+
image = data
|
|
753
|
+
else:
|
|
754
|
+
image, timestamp = data
|
|
755
|
+
|
|
756
|
+
image = cv2.circle(image, (self.circ_center_x, self.circ_center_y), self.circ_r, self.circ_color, self.circ_thickness)
|
|
757
|
+
image = cv2.line(
|
|
758
|
+
image, (self.circ_center_x, 0), (self.circ_center_x, self.frame_width), self.circ_color, self.circ_thickness
|
|
759
|
+
)
|
|
760
|
+
image = cv2.line(
|
|
761
|
+
image, (0, self.circ_center_y), (self.frame_height, self.circ_center_y), self.circ_color, self.circ_thickness
|
|
762
|
+
)
|
|
763
|
+
image = cv2.rectangle(
|
|
764
|
+
image, self.flyhead_topleft, self.flyhead_bottomright, color=self.circ_color, thickness=self.circ_thickness
|
|
765
|
+
)
|
|
766
|
+
image = cv2.rectangle(
|
|
767
|
+
image, self.flybody_topleft, self.flybody_bottomright, color=self.circ_color, thickness=self.circ_thickness
|
|
768
|
+
)
|
|
769
|
+
image = cv2.rectangle(
|
|
770
|
+
image, self.needle_topleft, self.needle_bottomright, color=self.needle_color, thickness=self.circ_thickness
|
|
771
|
+
)
|
|
772
|
+
cv2.imshow("display", image)
|
|
773
|
+
cv2.waitKey(1)
|
|
774
|
+
|
|
775
|
+
def _cleanup(self):
|
|
776
|
+
logger.info("closing display")
|
|
777
|
+
cv2.destroyWindow("display")
|
|
778
|
+
super()._cleanup()
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
if __name__ == "__main__":
|
|
782
|
+
import time
|
|
783
|
+
import ctypes
|
|
784
|
+
|
|
785
|
+
ct = ImageDisplayPQG.make_concurrent(
|
|
786
|
+
task_kwargs={"frame_width": 1000, "frame_height": 1000, "rate": .1},
|
|
787
|
+
comms="array",
|
|
788
|
+
comms_kwargs={"shape": (1000, 1000, 3), "ctype": ctypes.c_uint8},
|
|
789
|
+
)
|
|
790
|
+
ct.start()
|
|
791
|
+
for _ in range(100000000):
|
|
792
|
+
if ct._sender.WHOAMI == "array":
|
|
793
|
+
ct.send((np.random.randint(0, 255, (1000, 1000, 3)).astype(np.uint8), 1))
|
|
794
|
+
else:
|
|
795
|
+
ct.send(((np.zeros((1000, 1000)) + np.random.randint(0, 255)).astype(np.uint8), 1))
|
|
796
|
+
time.sleep(0.001)
|
|
797
|
+
ct.finish()
|
|
798
|
+
ct.close()
|