-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcamera.py
659 lines (471 loc) · 22.4 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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# -*- coding: utf-8 -*-
"""
@author: ziegler
"""
import numpy as np
import time
from hardware.pco.sdk import sdk
from hardware.pco.recorder import recorder
class exception(Exception):
def __str__(self):
return ('pco.exception Exception:', self.args)
class Camera(object):
# -------------------------------------------------------------------------
def __init__(self, debuglevel='off', timestamp='off', name='', interface=None, camera_number=0):
self.__debuglevel = debuglevel
self.__timestamp = timestamp
self.flim_config = None
self.sdk = sdk(debuglevel=self.__debuglevel,
timestamp=self.__timestamp,
name=name)
self.__camera_number = camera_number
# self.sdk.open_camera()
def __scanner(sdk, interfaces):
for interface in interfaces:
c = sdk.open_camera_ex(interface=interface, camera_number=camera_number)
if c['error'] == 0:
return 0
if c['error'] == 0x80002006:
break
elif c['error'] == 0x80002001:
continue
raise ValueError
try:
# self.sdk.open_camera()
if interface is not None:
if __scanner(self.sdk, [interface]) != 0:
raise ValueError
else:
if __scanner(self.sdk, ['Camera Link Silicon Software']) != 0:
raise ValueError
except Exception:
print('No camera found. Please check the connection and close '
'other processes which use the camera.')
raise
self.rec = recorder(self.sdk,
self.sdk.get_camera_handle(),
debuglevel=self.__debuglevel,
timestamp=self.__timestamp,
name=name)
self.default_configuration()
# -------------------------------------------------------------------------
def default_configuration(self):
"""
Sets default configuration for the camera.
:rtype: None
>>> default_configuration()
"""
if self.sdk.get_recording_state()['recording state'] == 'on':
self.sdk.set_recording_state('off')
self.sdk.reset_settings_to_default()
self.sdk.set_bit_alignment('LSB')
if self.sdk.get_camera_description()['dwGeneralCapsDESC1'] & 0x00004000 == 0x00004000:
self.sdk.set_metadata_mode('on')
self.__serial = self.sdk.get_camera_type()['serial number']
self.__camera_name = self.sdk.get_camera_name()['camera name']
self.sdk.arm_camera()
# -------------------------------------------------------------------------
def __str__(self):
return '{}, serial: {}'.format(self.__camera_name,
self.__serial)
# -------------------------------------------------------------------------
def __repr__(self):
return 'camera'
# -------------------------------------------------------------------------
@property
def configuration(self):
conf = {}
exp = self.sdk.get_delay_exposure_time()
timebase = {'ms': 1e-3, 'us': 1e-6, 'ns': 1e-9}
time = exp['exposure'] * timebase[exp['exposure timebase']]
conf.update({'exposure time': time})
roi = self.sdk.get_roi()
x0, y0, x1, y1 = roi['x0'], roi['y0'], roi['x1'], roi['y1']
conf.update({'roi': (x0, y0, x1, y1)})
conf.update({'timestamp': self.sdk.get_timestamp_mode()['timestamp mode']})
conf.update({'pixel rate': self.sdk.get_pixel_rate()['pixel rate']})
conf.update({'trigger': self.sdk.get_trigger_mode()['trigger mode']})
conf.update({'acquire': self.sdk.get_acquire_mode()['acquire mode']})
conf.update({'metadata': self.sdk.get_metadata_mode()['metadata mode']})
conf.update({'output format': self.sdk.get_interface_output_format()['output format']})
conf.update({'exposure lines': self.sdk.get_cmos_line_exposure_delay()['exposure lines']})
conf.update({'line timw': self.sdk.get_cmos_line_timing()['line time']})
bin = self.sdk.get_binning()
conf.update({'binning': (bin['binning x'], bin['binning y'])})
return conf
# -------------------------------------------------------------------------
@configuration.setter
def configuration(self, arg):
"""
Configures the camera with the given values from a dictionary.
:param arg: Arguments to configurate the camera.
:type arg: dict
:rtype: None
>>> configuration = {'exposure time': 10e-3,
'roi': (1, 1, 512, 512),
'timestamp': 'ascii'}
"""
if type(arg) is not dict:
print('Argument is not a dictionary')
raise TypeError
if self.sdk.get_recording_state()['recording state'] == 'on':
self.sdk.set_recording_state('off')
if 'exposure time' in arg:
self.set_exposure_time(arg['exposure time'])
if 'roi' in arg:
self.sdk.set_roi(*arg['roi'])
if 'timestamp' in arg:
self.sdk.set_timestamp_mode(arg['timestamp'])
if 'pixel rate' in arg:
self.sdk.set_pixel_rate(arg['pixel rate'])
if 'trigger' in arg:
self.sdk.set_trigger_mode(arg['trigger'])
if 'acquire' in arg:
self.sdk.set_acquire_mode(arg['acquire'])
if 'metadata' in arg:
self.sdk.set_metadata_mode(arg['metadata'])
if 'binning' in arg:
self.sdk.set_binning(*arg['binning'])
if 'line timing' in arg:
print(self.sdk.get_cmos_line_timing())
self.sdk.set_cmos_line_timing('on', 'us', arg['line timing']) # assumes us unit and turns ON line timing
print(self.sdk.get_cmos_line_timing())
if 'exposure lines' in arg:
print(self.sdk.get_cmos_line_exposure_delay())
self.sdk.set_cmos_line_exposure_delay(arg['exposure lines'], 0) # assumes 0 lines of delay
print(self.sdk.get_cmos_line_exposure_delay())
if 'output format' in arg:
print(self.sdk.get_interface_output_format('edge'))
self.sdk.set_interface_output_format('edge', arg['output format'])
print(self.sdk.get_interface_output_format('edge'))
self.sdk.arm_camera()
# -------------------------------------------------------------------------
def record(self, number_of_images=1, mode='sequence'):
"""
Generates and configures a new Recorder instance.
:param number_of_images: Number of images allocated in the driver. The
RAM of the PC is limiting the maximum value.
:type number_of_images: int
:paran mode: Mode of the Recorder
* 'sequence' - function is blocking while the number of images are
recorded. Recorder stops the recording when the
maximum number of images is reached.
* 'sequence non blocking' - function is non blocking. Status must
be checked before reading the image.
* 'ring buffer' - function is non blocking. Status must be checked
before reading the image. Recorder did not stop
the recording when the maximum number of images
is reached. The first image is overwritten from
the next image.
* 'fifo' - function is non blocking. Status must be checked before
reading the image.
:type mode: string
>>> record()
>>> record(10)
>>> record(number_of_images=10, mode='sequence')
>>> record(10, 'ring buffer')
>>> record(20, 'fifo')
"""
if (self.sdk.get_camera_health_status()['status'] & 2) != 2:
self.sdk.arm_camera()
self.__roi = self.sdk.get_roi()
try:
if self.sdk.get_camera_description()['wDoubleImageDESC'] == 1:
if self.sdk.get_double_image_mode()['double image'] == 'on':
self.__roi['y1'] = self.__roi['y1'] * 2
except Exception:
pass
if self.rec.recorder_handle.value is not None:
self.rec.stop_record()
self.rec.delete()
m = self.rec.create('memory')['maximum available images']
if m >= number_of_images:
self.__number_of_images = number_of_images
else:
print('maximum available images:', m)
return
self.rec.init(self.__number_of_images, mode)
self.rec.set_compression_parameter()
# -------------------------------------------------------------------------
def start(self, blocking):
"""
Starts the current recording. Blocking 'on' should only be used with sequence mode
>>> start()
"""
self.rec.start_record()
if blocking == 'on':
while True:
running = self.rec.get_status()['is running']
if running is False:
break
time.sleep(0.001)
#else:
# self.wait_for_image()
# -------------------------------------------------------------------------
def stop(self):
"""
Stops the current recording. Is used in "ring buffer" mode or "fifo"
mode.
>>> stop()
"""
if self.rec.recorder_handle.value is not None:
self.rec.stop_record()
# -------------------------------------------------------------------------
def close(self):
"""
Closes the current active camera and releases the blocked ressources.
This function must be called before the application is terminated.
Otherwise the resources remain occupied.
This function is called automatically, if the camera object is
created by the 'with' statement. An explicit call of 'close()' is no
longer necessary.
>>> close()
>>> with pco.camera() as cam:
...: # do some stuff
"""
if self.rec.recorder_handle.value is not None:
try:
self.rec.stop_record()
except self.rec.exception as exc:
pass
if self.rec.recorder_handle.value is not None:
try:
self.rec.delete()
except self.rec.exception as exc:
pass
if self.sdk.lens_control.value is not None:
try:
self.sdk.close_lens_control()
except self.sdk.exception as exc:
pass
try:
self.sdk.close_camera()
except self.sdk.exception as exc:
pass
# -------------------------------------------------------------------------
def __enter__(self):
return self
# -------------------------------------------------------------------------
def __exit__(self, type, value, traceback):
self.close()
# -------------------------------------------------------------------------
def image(self, image_number=0, roi=None):
"""
Returns an image from the recorder.
:param image_number: Number of recorder index to read. In "sequence"
mode or "sequence non blocking" mode the recorder
index matches the image number.
:type image_number: int
:param roi: Region of interrest. Only this region is returned.
:type roi: tuple(int, int, int, int)
:return: image
:rtype: numpy array
>>> image(image_number=0, roi=(1, 1, 512, 512))
image, metadata
>>> image(0xFFFFFFFF)
image, metadata
"""
if roi is None:
image = self.rec.copy_image(image_number, 1, 1,
(self.__roi['x1'] - self.__roi['x0'] + 1),
(self.__roi['y1'] - self.__roi['y0'] + 1))
np_image = np.asarray(image['image']).reshape((self.__roi['y1']-self.__roi['y0']+1),
(self.__roi['x1']-self.__roi['x0']+1))
else:
image = self.rec.copy_image(image_number, roi[0], roi[1], roi[2], roi[3])
np_image = np.asarray(image['image']).reshape((roi[3] - roi[1] + 1), (roi[2] - roi[0] + 1))
meta = {}
meta.update({'serial number': image['serial number']})
meta.update({'camera image number': image['camera image number']})
meta.update({'recorder image number': image['recorder image number']})
meta.update({'size x': image['wIMAGE_SIZE_X']})
meta.update({'size y': image['wIMAGE_SIZE_Y']})
meta.update({'binning x': image['bBINNING_X']})
meta.update({'binning y': image['bBINNING_Y']})
meta.update({'conversion factor': image['conversion factor']})
meta.update({'pixel clock': image['pixel clock']})
meta.update({'sensor temperature': image['sensor temperature']})
time.sleep(0.001)
return np_image, meta
# -------------------------------------------------------------------------
def images(self, roi=None, blocksize=None,):
"""
Returns all recorded images from the recorder.
:param roi: Region of interrest. Only this region is returned.
:type roi: tuple(int, int, int, int)
:param blocksize: The blocksize defines the maximum number of images
which are returned. This parameter is only useful in
'fifo' mode and special conditions.
:type blocksize: int
:return: images
:rtype: list(numpy arrays)
>>> images()
image_list, metadata_list
>>> images(blocksize=8)
image_list[:8], metadata_list[:8]
"""
image_list = []
meta_list = []
if blocksize is None:
for index in range(self.__number_of_images):
if roi is None:
image = self.rec.copy_image(index, 1, 1,
(self.__roi['x1'] - self.__roi['x0'] + 1),
(self.__roi['y1'] - self.__roi['y0'] + 1))
np_image = np.asarray(image['image']).reshape((self.__roi['y1']-self.__roi['y0']+1),
(self.__roi['x1']-self.__roi['x0']+1))
else:
image = self.rec.copy_image(index, roi[0], roi[1], roi[2], roi[3])
np_image = np.asarray(image['image']).reshape((roi[3] - roi[1] + 1), (roi[2] - roi[0] + 1))
meta = {}
meta.update({'serial number': image['serial number']})
meta.update({'camera image number': image['camera image number']})
meta_list.append(meta)
image_list.append(np_image)
else:
while True:
level = self.rec.get_status()['dwProcImgCount']
if level >= blocksize:
break
for index in range(blocksize):
if roi is None:
image = self.rec.copy_image(index, 1, 1,
(self.__roi['x1'] - self.__roi['x0'] + 1),
(self.__roi['y1'] - self.__roi['y0'] + 1))
np_image = np.asarray(image['image']).reshape((self.__roi['y1']-self.__roi['y0']+1),
(self.__roi['x1']-self.__roi['x0']+1))
else:
image = self.rec.copy_image(index, roi[0], roi[1], roi[2], roi[3])
np_image = np.asarray(image['image']).reshape((roi[3] - roi[1] + 1), (roi[2] - roi[0] + 1))
meta = {}
meta.update({'serial number': image['serial number']})
meta.update({'camera image number': image['camera image number']})
meta_list.append(meta)
image_list.append(np_image)
time.sleep(0.001)
return image_list, meta_list
# -------------------------------------------------------------------------
def set_exposure_time(self, exposure_time):
"""
Sets the exposure time of the camera. The underlying values for the
sdk.set_delay_exposure_time(0, 'ms', time, timebase) function will be
calculated automatically. The delay time is set to 0.
>>> set_exposure_time(0.001)
>>> set_exposure_time(1e-3)
"""
if exposure_time <= 4e-3:
time = int(exposure_time * 1e9)
timebase = 'ns'
elif exposure_time <= 4:
time = int(exposure_time * 1e6)
timebase = 'us'
elif exposure_time > 4:
time = int(exposure_time * 1e3)
timebase = 'ms'
else:
raise
self.sdk.set_delay_exposure_time(0, 'ms', time, timebase)
# -------------------------------------------------------------------------
def image_average(self, roi=None):
"""
Returns the averaged image. This image is calculated from all created
image buffers.
>>> average_image()
image
"""
start = 0
stop = self.__number_of_images - 1
if roi is None:
image = self.rec.copy_average_image(start, stop,
1, 1,
(self.__roi['x1'] - self.__roi['x0'] + 1),
(self.__roi['y1'] - self.__roi['y0'] + 1))
np_image = np.asarray(image['average image']).reshape((self.__roi['y1']-self.__roi['y0']+1),
(self.__roi['x1']-self.__roi['x0']+1))
else:
image = self.rec.copy_average_image(start, stop,
roi[0], roi[1],
roi[2], roi[3])
np_image = np.asarray(image['average image']).reshape((roi[3] - roi[1] + 1), (roi[2] - roi[0] + 1))
return np_image
# -------------------------------------------------------------------------
def average_image(self, roi=None):
print()
print('WARNING: This function will be removed / renamed. Use image_average() instead.')
print()
return self.image_average(roi)
# -------------------------------------------------------------------------
def wait_for_image(self):
"""
This function waits for the first available image. In recorder mode
'sequence non blocking', 'ring buffer' and 'fifo' the record() function
returns immediately. The user is responsible to wait for images from
the camera before image() / images() is called.
>>> wait_for_image()
"""
print()
print('WARNING: This function will be removed / renamed. Use wait_for_first_image() instead.')
print()
self.wait_for_first_image()
# -------------------------------------------------------------------------
def wait_for_first_image(self):
"""
This function waits for the first available image. In recorder mode
'sequence non blocking', 'ring buffer' and 'fifo' the record() function
returns immediately. The user is responsible to wait for images from
the camera before image() / images() is called.
>>> wait_for_first_image()
"""
while True:
if self.rec.get_status()['dwProcImgCount'] >= 1:
break
time.sleep(0.0001)
def wait_for_next_image(self, index):
"""
This function waits for the next available image.
>>> wait_for_next_image()
"""
while True:
if self.rec.get_status()['dwProcImgCount'] >= index+1:
break
time.sleep(0.0001)
# -------------------------------------------------------------------------
def image_compressed(self, image_number=0, roi=None):
"""
Returns an image from the recorder.
:param image_number: Number of recorder index to read. In "sequence"
mode or "sequence non blocking" mode the recorder
index matches the image number.
:type image_number: int
:param roi: Region of interrest. Only this region is returned.
:type roi: tuple(int, int, int, int)
:return: image
:rtype: numpy array
>>> image(image_number=0, roi=(1, 1, 512, 512))
image, metadata
>>> image(0xFFFFFFFF)
image, metadata
"""
if roi is None:
image = self.rec.copy_image_compressed(image_number, 1, 1,
(self.__roi['x1'] - self.__roi['x0'] + 1),
(self.__roi['y1'] - self.__roi['y0'] + 1))
np_image = np.asarray(image['image']).reshape((self.__roi['y1']-self.__roi['y0']+1),
(self.__roi['x1']-self.__roi['x0']+1))
else:
image = self.rec.copy_image_compressed(image_number, roi[0], roi[1], roi[2], roi[3])
np_image = np.asarray(image['image']).reshape((roi[3] - roi[1] + 1), (roi[2] - roi[0] + 1))
meta = {}
meta.update({'serial number': image['serial number']})
meta.update({'camera image number': image['camera image number']})
meta.update({'recorder image number': image['recorder image number']})
meta.update({'size x': image['wIMAGE_SIZE_X']})
meta.update({'size y': image['wIMAGE_SIZE_Y']})
meta.update({'binning x': image['bBINNING_X']})
meta.update({'binning y': image['bBINNING_Y']})
return np_image, meta
# -----------------------------------------------------------------------------
class camera(Camera):
def __init__(self, debuglevel='off', timestamp='off', name='', interface=None, camera_number=0):
print("Class 'camera' has been renamed to 'Camera', please use the new name.")
super().__init__(debuglevel=debuglevel, timestamp=timestamp, name=name, interface=interface, camera_number=camera_number)