-
Notifications
You must be signed in to change notification settings - Fork 11
/
xenics.py
1553 lines (1402 loc) · 64.1 KB
/
xenics.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Hardware control for Xenics camera via the :mod:`Xeneth` interface.
Python wrapper for Xenith C++ SDK 2.7 from Xenics; see xeneth-sdk.chm
there for additional documentation.
"""
import time
from ctypes import *
import numpy as np
from .camera import Camera
CLKFREQ = 80e6
### Imaging Constants from XFilters.h ###
# pylint: disable=C0301
# fmt: off
#ErrorCodes
I_OK = 0 # Success.
I_DIRTY = 1 # Internal.
E_BUG = 10000 # Generic.
E_NOINIT = 10001 # Camera was not successfully initialised.
E_LOGICLOADFAILED = 10002 # Invalid logic file.
E_INTERFACE_ERROR = 10003 # Command interface failure.
E_OUT_OF_RANGE = 10004 # Provided value is incapable of being produced by the hardware.
E_NOT_SUPPORTED = 10005 # Functionality not supported by this camera.
E_NOT_FOUND = 10006 # File/Data not found.
E_FILTER_DONE = 10007 # Filter has finished processing and will be removed.
E_NO_FRAME = 10008 # A frame was requested by calling GetFrame but none was available.
E_SAVE_ERROR = 10009 # Couldn't save to file.
E_MISMATCHED = 10010 # Buffer size mismatch.
E_BUSY = 10011 # The API can not read a temperature because the camera is busy.
E_INVALID_HANDLE = 10012 # An unknown handle was passed to the C API.
E_TIMEOUT = 10013 # Operation timed out.
E_FRAMEGRABBER = 10014 # Frame grabber error.
E_NO_CONVERSION = 10015 # GetFrame could not convert the image data to the requested format.
E_FILTER_SKIP_FRAME = 10016 # Filter indicates the frame should be skipped.
E_WRONG_VERSION = 10017 # Version mismatch.
E_PACKET_ERROR = 10018 # The requested frame cannot be provided because at least one packet has been lost.
E_WRONG_FORMAT = 10019 # The emissivity map you tried to set should be a 16 bit greyscale PNG.
E_WRONG_SIZE = 10020 # The emissivity map you tried to set has the wrong dimensions (width height).
E_CAPSTOP = 10021 # Internal
E_OUT_OF_MEMORY = 10022 # An allocation failed because the system ran out of memory.
#ColourMode
COLOURMODE_8 = 0 # Intensity only
COLOURMODE_16 = 1 # Alias
COLOURMODE_PROFILE = 2 # Uses a colour profile bitmap. See #LoadColourProfile()
COLOURMODE_INVERT = 256 # Set this flag if an inversion of the colour profile is desired. eg: #ColourMode_8 | #ColourMode_Invert
#BlitType
WINDOW = 0 # Blit the contents of the last captured frame directly to a Windows client device context using a Window handle (HWND) */
DEVICECONTEXT = 1 # Blit the contents of the last captured frame to a specified device context.
# This can be any device context (HDC) like a memory DC paint DC or a handle to a DC associated with a Graphics-object (C#) */
#FrameType
FT_UNKNOWN = -1 # Unknown invalid frame type
FT_NATIVE = 0 # The native frame type of this camera (can be FT_8..,FT_16..,FT32.. check GetFrameType())
FT_8_BPP_GRAY = 1 # 8-bit greyscale
FT_16_BPP_GRAY = 2 # 16-bit greyscale (default for most of the Xenics branded cameras)
FT_32_BPP_GRAY = 3 # 32-bit greyscale
FT_32_BPP_RGBA = 4 # 32-bit colour RGBA [B,G,R,A] Available for output conversion.
FT_32_BPP_RGB = 5 # 32-bit colour RGB [B,G,R] Available for output conversion.
FT_32_BPP_BGRA = 6 # 32-bit colour BGRA [R,G,B,A]
FT_32_BPP_BGR = 7 # 32-bit colour BGR [R,G,B]
#XEnumerationFlag
XEF_NETWORK = 0x00000001 # Network
XEF_SERIAL = 0x00000002 # Serial
XEF_CAMERALINK = 0x00000004 # CameraLink
XEF_GIGEVISION = 0x00000008 # GigEVision
XEF_COAXPRESS = 0x00000010 # CoaXPress
XEF_USB = 0x00000020 # USB
XEF_USB3VISION = 0x00000040 # USB3Vision
XEF_GENCP = 0x00000080 # CameraLink GenCP
XEF_ENABLEALL = 0x0000FFFF # Enable all protocols.
XEF_USECACHED = 0x01000000 # Use cached devices on enumeration.
XEF_RELEASECACHE = 0x02000000 # Release internally cached devices.
#XFilterMessage
XMSGINIT = 0 # [API->Filter Event] Called when the filter is being installed ( (!) calling thread context) */
XMSGCLOSE = 1 # [API->Filter Event] Called when the filter is being removed ( (!) calling thread context) */
XMSGFRAME = 2 # [API->Filter Event] Called after every frame grab ( (!) grabbing thread context) */
XMSGGETNAME = 3 # [App->Filter Event] Retrieve filter name: the filter should copy a friendly string to msgparm */
XMSGGETVALUE = 4 # [Obsolete] */
XMSGSAVE = 5 # [Obsolete] */
XMSGGETSTATUS = 6 # [API->Filter Event] Retrieves a general purpose status message from the image filter */
XMSGUPDATEVIEWPORT = 7 # [API->Filter Event] Instructs an image correction filter to update it's view port
# This message is sent to a filter upon changing the window of interest or when
# flipping image horizontally or vertically */
XMSGCANPROCEED = 8 # Used by image filters in in interactive mode to indicate acceptable image conditions */
XMSGGETINFO = 9 # [Internal] Used to query filter 'registers' */
XMSGSELECT = 10 # [Obsolete] */
XMSGPROCESSEDFRAME = 11 # [API->Filter Event] Sent after other filters have done their processing. Do not modify the frame data
# in response to this event. */
XMSGTIMEOUT = 13 # [API->Filter Event] A camera time-out event was generated */
XMSGISBUSY = 16 # [Thermography] Is the temperature filter recalculating - Used to check if the thermal filter is
# still updating it's linearisation tables */
XMSGSETTROI = 17 # [Imaging/Thermo] Set the adu/temperature span in percent (see #XMsgSetTROIParms) */
XMSGLOAD = 18 # [Obsolete] */
XMSGUNLOAD = 19 # [Obsolete] */
XMSGADUTOTEMP = 12 # [Thermography] Convert an ADU value to a temperature (see #XFltADUToTemperature) */
XMSGGETEN = 14 # [Obsolete] Get temperature correction parameters (see #XMsgGetRadiometricParms) */
XMSGSETEN = 15 # [Obsolete] Set temperature correction parameters (see #XMsgGetRadiometricParms) */
XMSGTEMPTOADU = 20 # [Thermography] Convert a temperature to an ADU value (see #XFltTemperatureToADU) */
XMSGGETTVALUE = 21 # [Thermography] Retrieve an emissivity corrected value from a coordinate */
XMSGGETRADIOMETRICPARMS = 22 # [Thermography] Get temperature correction parameters (see #XMsgTempParms) */
XMSGSETRADIOMETRICPARMS = 23 # [Thermography] Set temperature correction parameters (see #XMsgTempParms) */
XMSGSERIALISE = 100 # [App->Filter event] Serialise internal parameter state (write xml structure) see #XFltSetParameter */
XMSGDESERIALISE = 101 # [App->Filter event] Deserialise parameter state (read xml structure) see #XFltSetParameter */
XMSGGETPRIORITY = 102 # [Filter Management] Write the current filter priority to the long * provided in v_pMsgParm */
XMSGSETFILTERSTATE = 104 # [Filter Management] Enable or disable an image filter temporarily by sending 0/1 in v_pMsgParm */
XMSGISSERIALISEDIRTY = 105 # [Internal] */
XMSGSTOREHANDLE = 106 # [Internal] Start tracking the module handle for plugin image filters */
XMSGUPDATETINT = 107 # [API->Filter event] Integration time change notification */
XMSGLINADUTOTEMP = 109 # [Thermography] Convert a Linearized ADU value to a temperature (see #XFltADUToTemperatureLin) */
XMSGLINTEMPTOADU = 110 # [Thermography] Convert a temperature to a Linearized ADU value (see #XFltTemperatureToADULin) */
XMSGUPDATESPAN = 111 # [API->Filter event] Span change notification */
XMSGUPDATEPALETTE = 112 # [API->Filter event] Colour profile change notification */
XMSGFILTERQUEUED = 113 # [API->Filter event] A filter is queued */
XMSGFILTERREMOVED = 114 # [API->Filter event] A filter is removed */
XMSGDRAWOVERLAY = 200 # [API->Filter event] Draw the RGBA frame overlay, v_pMsgParm is the pointer to the RGBA data
# structure */
XMSGLINEARISEOUTPUT = 201 # [Thermography] When specifying a v_pMsgParm that is non zero, starts linearising adu output */
XMSGSETEMIMAP = 202 # [Thermography] Streams the main emissivity map to the thermal filter (16 bit png, 65535 = 1.0) */
XMSGSETEMIMAPUSER = 203 # [Thermography] Stream a user emissivity map to the thermal filter (16 bit png, 65535 = 1.0,
# 0 values are replaced by the emissivity in the main map) */
XMSGGETEMIMAP = 204 # [Thermography] Stream out the combined emissivity map */
XMSGCLREMIMAP = 205 # [Thermography] Clear emissivity map */
XMSGCLREMIMAPUSER = 206 # [Thermography] Clear emissivity map (user) */
XMSGPUSHRANGE = 207 # [Thermography] Push a new linearization range to the thermal filter */
XMSGTHMFILTERSTATE = 208 # [Thermography] Filter event indicating thermal filter queue/removal */
XMSGTHMADJUSTSET = 209 # [Thermography] Set global offset & gain adu adjustment (pre-thermal conversion) */
XMSGTHMADJUSTGET = 210 # [Thermography] (see #XMsgTempAdjustmentParms) */
XMSGLOG = 211 # [Plugin->API] Fire a log event to the end user application\n
# Target filter id: 0xffffffff */
XMSGGETDELTAT = 212 # [Internal] */
XMSGGETTINTRANGE = 213 # [Plugin->API] Request the exposure time range
# Target filter id: 0xffffffff */
XMSGCORRECTIONDIRTY = 214 # [Internal] The onboard thermography parameters have changed */
XMSGHASRADIANCEINFO = 215 # [Thermography] Check if the radiance information is available. This is needed to for emissivity correction */
XMSGCORRECTIONDATACHANGED = 216 # [Internal] New correction data is loaded */
XMSGPOSTPROCESS = 217 # [Internal] A post processing step is introduced in the software correction filter */
XMSGZOOMLENSCONNECT = 300 # [Zoom lens] Connect to the zoom lens on the specified port. */
XMSGZOOMLENSGETSTATE = 301 # [Zoom lens] Get the current zoom/focus state from the zoom lens filter. */
XMSGZOOMLENSSETSTATE = 302 # [Zoom lens] Set the current zoom/focus state in the zoom lens filter. */
XMSGZOOMLENSGETINFO = 303 # [Zoom lens] Get some descriptive information about the connected lens. */
XMSGUSER = 24200 # If you develop your own image filter plugins, please use this constant to offset your messages. */
#XStatusMessage
XSLOADLOGIC = 1 # Passed when loading the camera's main logic file */
XSLOADVIDEOLOGIC = 2 # Passed when loading the camera's video output firmware */
XSDATASTORAGE = 3 # Passed when accessing persistent data on the camera */
XSCORRECTION = 4 # Passed when uploading correction data to the camera */
XSSELFSTART = 5 # Passed when a self starting camera is starting (instead of XSLoadLogic) */
XSMESSAGE = 6 # String event
# This status message is used to relay critical errors and events originating
# from within the API.
# Cam|PropLimit|property=number - A filter notifies you your user interface should limit the value of 'property' to 'number'
# Cam|TemperatureFilter|RangeUpdate - The thermography filter uses this to notify you of a span update.
# Cam|TemperatureFilter|Off - The thermography filter suggests the application to dequeue the filter.
# Cam|InterfaceUpdate - Internal, do not handle, returning E_BUG here causes the API to stop unpacking 'abcd.package'.packages to %appdata%/xenics/interface
XSLOADGRABBER = 7 # Passed when loading the framegrabber */
XSDEVICEINFORMATION = 8 # Device information passed when connecting a device, ulP is the lower part of the address. When using 64-bit the higher part of the address is stored in ulT */
#XGetFrameFlags
XGF_BLOCKING = 1 # In blocking-mode the method does not return immediately with the return codes #E_NO_FRAME / #I_OK.
# Instead the method waits for a frame and only returns until a frame was captured, or a time-out period has elapsed.
XGF_NOCONVERSION= 2 # Prevents internal conversion to 8 bit, specifying this flag reduces computation time, but prevents #SaveData() and the #Blit() method from working.
XGF_FETCHPFF = 4 # Retrieve the per frame footer with frame timing information. Call XCamera::GetFrameFooterLength() to determine the increase in frame size.
XGF_RFU_1 = 8
XGF_RFU_2 = 16
XGF_RFU_3 = 32
#XSaveDataFlags
XSD_FORCE16 = 1 # Forces 16-bit output independent of the current #ColourMode-setting (only possible for PNG's)
XSD_FORCE8 = 2 # Forces 8-bit output independent of the current #ColourMode
XSD_ALIGNLEFT = 4 # Left aligns 16-bit output (#XSD_Force16 | #XSD_AlignLeft)
XSD_SAVETHERMALINFO = 8 # Save thermal conversion structure (only available when saving 16-bit PNGs)
XSD_RFU_0 = 16 # Reserved
XSD_RFU_1 = 32
XSD_RFU_2 = 64
XSD_RFU_3 = 128
#XSaveSettingFlags
XSS_SAVECAMERAPROPS = 1 # Define property sources to save settings from.
XSS_SAVEGRABBERPROPS = 2 #
XSS_SAVEALLPROPS = 4 # Also save properties marked 'No persist'.
XSS_SS_RFU_3 = 8 #
#XLoadSettingsFlags
XSS_IGNORENAIS = 1 # Ignore properties which do not affect the image.
XSS_LS_RFU_1 = 2 #
XSS_LS_RFU_2 = 4 #
XSS_LS_RFU_3 = 8 #
#XLoadCalibrationFlags
XLC_STARTSOFTWARECORRECTION = 1 # Starts the software correction filter after unpacking the calibration data
XLC_RFU_1 = 2
XLC_RFU_2 = 4
XLC_RFU_3 = 8
#XPropType
XTYPE_NONE = 0x00000000
XTYPE_BASE_MASK = 0x000000ff # Type mask
XTYPE_ATTR_MASK = 0xffffff00 # Attribute mask
XTYPE_BASE_NUMBER = 0x00000001 # A number (floating)
XTYPE_BASE_ENUM = 0x00000002 # An enumerated type (a choice)
XTYPE_BASE_BOOL = 0x00000004 # Boolean (true / false / 1 / 0)
XTYPE_BASE_BLOB = 0x00000008 # Binary large object
XTYPE_BASE_STRING = 0x00000010 # String
XTYPE_BASE_ACTION = 0x00000020 # Action (button)
XTYPE_BASE_RFU1 = 0x00000040 # RFU
XTYPE_BASE_RFU2 = 0x00000080 # RFU
XTYPE_BASE_MINMAX = 0x00002000 # The property accepts the strings 'min' and 'max' to set the best achievable extremities.
XTYPE_BASE_READONCE = 0x00001000 # Property needs to be read at start-up only
XTYPE_BASE_NOPERSIST = 0x00000800 # Property shouldn't be persisted (saved & restored)
XTYPE_BASE_NAI = 0x00000400 # Property does not affect image intensity level ('Not Affecting Image')
XTYPE_BASE_RW = 0x00000300 # Write and read back
XTYPE_BASE_WRITEABLE = 0x00000200 # Writeable properties have this set in their high byte
XTYPE_BASE_READABLE = 0x00000100 # Readable properties have this set in their high byte
XTYPE_NUMBER = 0x00000201 # Write only number
XTYPE_ENUM = 0x00000202 # Write only enumeration
XTYPE_BOOL = 0x00000204 # Write only boolean
XTYPE_BLOB = 0x00000208 # Write only binary large object
XTYPE_STRING = 0x00000210 # Write only string
XTYPE_ACTION = 0x00000220 # Action (button)
XTYPE_RO_NUMBER = 0x00000101 # Read only number
XTYPE_RO_ENUM = 0x00000102 # Read only enumeration
XTYPE_RO_BOOL = 0x00000104 # Read only boolean
XTYPE_RO_BLOB = 0x00000108 # Read only binary large object
XTYPE_RO_STRING = 0x00000110 # Read only string
XTYPE_RW_NUMBER = 0x00000301 # R/W number
XTYPE_RW_ENUM = 0x00000302 # R/W enumeration
XTYPE_RW_BOOL = 0x00000304 # R/W boolean
XTYPE_RW_BLOB = 0x00000308 # R/W binary large object
XTYPE_RW_STRING = 0x00000310 # R/W string
#XDirectories
XDIR_FILTERDATA = 0x0000 # Filter data (%APPDATA%/XenICs/Data/<sessionnumber>)
XDIR_SCRIPTROOT = 0x0001 # Script root (%APPDATA%/XenICs/Interface/<PID-number>)
XDIR_CALIBRATIONS = 0x0002 # Calibration folder (%ProgramFiles%/Xeneth/Calibrations)
XDIR_INSTALLDIR = 0x0003 # Installation folder (%CommonProgramFiles%/XenICs/Runtime)
XDIR_PLUGINS = 0x0004 # Plugin folder (%CommonProgramFiles%/XenICs/Runtime/Plugins)
XDIR_CACHEPATH = 0x0005 # Cache folder (%APPDATA%/XenICs/Cache)
XDIR_SDKRESOURCES = 0x0006 # SDK resource folder (%CommonProgramFiles%/XenICs/Runtime/Resources)
XDIR_XENETH = 0x0007 # Xeneth installation directory
XDIR_GRABBERSCRIPTROOT = 0x0008 # Script root (%APPDATA%/XenICs/Interface/<FrameGrabber>)
#XDeviceStates
XDS_AVAILABLE = 0x0 # The device is available to establish a connection.
XDS_BUSY = 0x1 # The device is currently in use.
XDS_UNREACHABLE = 0x2 # The device was detected but is unreachable.
# pylint: enable=C0301
# fmt: on
class _XDeviceInformation(Structure):
"""Structure to be filled with camera data from the dll inteface."""
_fields_ = [
("size", c_int),
("name", (c_char * 64)),
("transport", (c_char * 64)),
("url", (c_char * 256)),
("address", (c_char * 64)),
("serial", c_uint),
("pid", c_uint),
("state", c_uint),
]
class Cheetah640(Camera):
"""
Xeneth's Cheetah640 camera.
Attributes
----------
xeneth : windll
Object to talk with the Xeneth SDK.
cam : ptr
Object to talk with the desired camera.
profile : {'triggered', 'free'}
Current pre-configured operation mode.
``'triggered'`` - Captures on external trigger \n
``'free'`` - Continuous capture
frame_size : int
Size of the frame in bytes for use in grabbing data for the buffer.
frame_buffer : c_ushort array
Buffer used to grab data from the camera and sdk interface.
last_capture : numpy.ndarray
Previous capture by get_image()
last_tag : numpy.uint16
Frame tag of last capture
last_process_time : float
Time to process last frame
filters : dict
Dictionary with enabled filters. See Xeneth documentation for more information.
"""
### Camera Interface ###
def __init__(self, virtual=False, temperature=None, verbose=True, **kwargs):
"""
Initialize camera. Default ``profile`` is ``'free'``.
Parameters
----------
virtual : bool
Whether or not the camera is virtual.
temperature : float or None
Temperature in degrees celcius to set on startup. ``None`` defaults to no cooling.
verbose : bool
Whether or not to print camera initialization information.
kwargs
See :meth:`.Camera.__init__` for permissible options.
Raises
------
RuntimeError
If the camera is not reachable.
"""
# Load the SDK
self.xeneth = windll.LoadLibrary("xeneth64.dll")
# Enumerate devices
dev_count = c_uint()
_ = self.xeneth.XCD_EnumerateDevices(None, byref(dev_count), XEF_CAMERALINK)
device = _XDeviceInformation()
_ = self.xeneth.XCD_EnumerateDevices(
byref(device), byref(dev_count), XEF_USECACHED
)
# Open the first avaliable camera
if virtual:
if verbose:
print("Opening connection to virtual camera")
self.cam = self.xeneth.XC_OpenCamera(b"soft://0", 0, 0)
else:
if device.name.decode():
if verbose:
print("Opening connection to %s" % device.name.decode())
self.cam = self.xeneth.XC_OpenCamera(device.url, 0, 0)
name = device.name.decode()
else:
raise RuntimeError(
"Camera not reachable! Close Xeneth GUI or check connections."
)
# Check that the camera opened properly
if self.xeneth.XC_IsInitialised(self.cam):
if verbose:
print("Camera initialized, loading properties ...")
super().__init__(
self.xeneth.XC_GetWidth(self.cam),
self.xeneth.XC_GetHeight(self.cam),
bitdepth=12,
dx_um=20,
dy_um=20,
name=name,
**kwargs
)
# Initialize a 16-bit buffer for a single frame; initialize to 0
self.frame_size = self.xeneth.XC_Getframe_size(self.cam)
self.frame_buffer = (c_ushort * int(self.frame_size / 2))(0)
self.last_capture = np.empty(self.shape)
self.last_tag = np.uint16(0) # Frame tag of last capture
self.last_process_time = 0 # Time to process last frame
# Make a filter dictionary
self.filters = {}
# Setup base imaging configuration
if not virtual:
# Starts a circular buffer w/ 4k frames (anything larger crashes???)
self.setup_grabber(frames=4000)
# Max out the API buffer to
self.set_buffer_api(frames=64)
# Enable frame tags (frame number in first two pixels)
self.enable_frametags(True)
if temperature is None:
# Disable high fan speed for stability
self.enable_cooling(False)
else:
self.enable_cooling()
# Set Peltier setpoint
self.set_temperature(temperature)
# Flip X, Flip Y readout by default (used in onboard cal)
self.set_readout_orientation(True, True)
# Enable output trigger to readout integration periods
self.setup_output_trigger()
# Set max frame rate to basically unlimited (exposure-limited)
self.set_framerate(0)
# Load visible setup by default
self.setup("free")
else:
print("Initialization failed")
def close(self):
"""See :meth:`.Camera.close`."""
if self.xeneth.XC_IsInitialised(self.cam):
print("Closing connection to camera...")
self.xeneth.XC_CloseCamera(self.cam)
else:
print("Camera not open!")
def reset(self):
"""See :meth:`.Camera.reset`."""
self.close()
self.__init__()
### Property Configuration ###
def get_property_status(self, save_file_path=None, verbose=True):
"""
List and get status of all addressable properties on camera.
Parameters
----------
save_file_path : str or None
If not ``None``, the property status results will be saved to this path.
verbose : True
Prints property results if ``True``.
"""
if self.xeneth.XC_IsInitialised(self.cam):
if verbose:
print("Getting camera properties...")
property_count = self.xeneth.XC_GetPropertyCount(self.cam)
property_name = (c_char * 128)(0)
property_category = (c_char * 128)(0)
property_range = (c_char * 128)(0)
property_unit = (c_char * 128)(0)
property_type = c_int() # XType_None
lvalue = c_long(0)
fvalue = c_double(0)
cvalue = c_char(0)
# Iterate over each property and output details such as name, type, value
for x in range(property_count):
self.xeneth.XC_Getproperty_name(self.cam, x, property_name, 128)
self.xeneth.XC_Getproperty_category(
self.cam, property_name, property_category, 128
)
self.xeneth.XC_Getproperty_type(
self.cam, property_name, byref(property_type)
)
self.xeneth.XC_Getproperty_range(
self.cam, property_name, property_range, 128
)
self.xeneth.XC_Getproperty_unit(
self.cam, property_name, property_unit, 128
)
if verbose:
print(
"Property[%d] Category: %s"
% (x, property_category.value.decode())
)
print(
"Property[%d] Name: %s"
% (x, property_name.value.decode())
)
print(
"Property[%d] Flags: %s"
% (
x,
(
"MinMax | "
if property_type.value & XTYPE_BASE_MINMAX
else ""
)
+ (
"ReadOnce | "
if property_type.value & XTYPE_BASE_READONCE
else ""
)
+ (
"NoPersist | "
if property_type.value & XTYPE_BASE_NOPERSIST
else ""
)
+ ("NAI | " if property_type.value & XTYPE_BASE_NAI else "")
+ (
"Writeable | "
if property_type.value & XTYPE_BASE_WRITEABLE
else ""
)
+ (
"Readable | "
if property_type.value & XTYPE_BASE_READABLE
else ""
),
)
)
# The following output depends on the property type.
type_num = property_type.value & XTYPE_BASE_MASK
# Write-only number
if type_num == XTYPE_BASE_NUMBER:
# Check camera doc for float vs. long
self.xeneth.XC_GetPropertyValueL(
self.cam, property_name, byref(lvalue)
)
self.xeneth.XC_GetPropertyValueF(
self.cam, property_name, byref(fvalue)
)
if verbose:
print("Property[%d] Type: Number" % x)
print(
"Property[%d] Range: %s"
% (x, property_range.value.decode())
)
print(
"Property[%d] Unit: %s"
% (x, property_unit.value.decode())
)
print("Property[%d] Long value: %lu" % (x, lvalue.value))
print("Property[%d] Float value: %f" % (x, fvalue.value))
# Write-only enumeration
elif type_num == XTYPE_BASE_ENUM:
self.xeneth.XC_GetPropertyValueL(
self.cam, property_name, byref(lvalue)
)
if verbose:
print("Property[%d] Type: Enum" % x)
print(
"Property[%d] Range: %s"
% (x, property_range.value.decode())
)
print("Property[%d] Value: %lu" % (x, lvalue.value))
# Boolean TF
elif type_num == XTYPE_BASE_BOOL:
self.xeneth.XC_GetPropertyValueL(
self.cam, property_name, byref(lvalue)
)
if verbose:
print("Property[%d] Type: Bool" % x)
print(
"Property[%d] Value: %s"
% (x, "True" if lvalue.value == 1 else "False")
)
# Binary large object (BLOB)
elif type_num == XTYPE_BASE_BLOB:
if verbose:
print("Skipping BLOB information collection to save time...")
# String
elif type_num == XTYPE_BASE_STRING:
# Get the string.
cvalue = (c_char * 128)(0)
self.xeneth.XC_GetPropertyValue(
self.cam, property_name, cvalue, 128
)
if verbose:
print("Property[%d] Type: String" % x)
print("Property[%d] Value: %s" % (x, cvalue.value))
if verbose:
print("")
# Save current settings to file if desired
if save_file_path is not None:
fname = save_file_path + ".xcf"
print('Saving settings to file "{}"...'.format(fname))
self.xeneth.XC_SaveSettings(self.cam, fname)
else:
print("Camera not open!")
def configure(self, format_file):
"""
Loads pre-stored imaging profile from XC_SaveSettings XCF file
Parameters
----------
format_file : str
Path to XCF file containing format information
"""
if self.xeneth.XC_IsInitialised(self.cam):
print("Loading settings from {}.xcf ....".format(format_file))
self.xeneth.XC_LoadSettings(self.cam, format_file)
else:
print("Camera not open!")
def get_exposure(self):
"""See :meth:`.Camera.get_exposure`."""
exposure_old = c_double(0.0)
err1 = self.xeneth.XC_GetPropertyValueF(
self.cam, b"IntegrationTime", byref(exposure_old)
)
if err1:
print("\nWarning -- error encountered! Error code: %d" % (err1))
return exposure_old.value / 1e6
def set_exposure(self, exposure_s, verbose=True):
"""
See :meth:`.Camera.set_exposure`.
Parameters
----------
verbose : bool
Whether or not to print extra information.
"""
print(
"Setting integration time to %1.3f ms... " % (exposure_s * 1e3),
end="\r",
)
exposure_old = c_double(0.0)
exposure = c_double(exposure_s * 1e6) # us
err1 = self.xeneth.XC_GetPropertyValueF(
self.cam, b"IntegrationTime", byref(exposure_old)
)
err2 = self.xeneth.XC_SetPropertyValueF(
self.cam, b"IntegrationTime", exposure, ""
)
err3 = self.xeneth.XC_GetPropertyValueF(
self.cam, b"IntegrationTime", byref(exposure)
)
if verbose:
print(
"\nPrevious integration time: %ld us\nNew integration time: %ld us"
% (exposure_old.value, exposure.value)
)
if err1 or err2 or err3:
print(
"\nWarning -- error encountered! Error codes: %d, %d, %d"
% (err1, err2, err3)
)
def set_framerate(self, framerate):
"""
Set the camera framerate.
Parameters
----------
frame : int
The framerate in fps.
"""
rate = c_long(int(framerate))
print("Setting frame rate to %d Hz..." % (rate.value))
rate_old = c_long(0)
err1 = False
err1 = self.xeneth.XC_GetPropertyValueL(self.cam, b"FrameRate", byref(rate_old))
err2 = self.xeneth.XC_SetPropertyValueL(self.cam, b"FrameRate", rate, "")
err3 = self.xeneth.XC_GetPropertyValueL(self.cam, b"FrameRate", byref(rate))
print(
"Previous frame rate: %d Hz\nNew frame rate: %d Hz"
% (rate_old.value, rate.value)
)
if err1 or err2 or err3:
print(
"Warning -- error encountered! Error codes: %d, %d, %d"
% (err1, err2, err3)
)
def get_frame_footer_length(self):
"""
Get the length of software frame tags.
Returns
-------
int
"""
return self.xeneth.XC_GetFrameFooterLength(self.cam)
def set_buffer_api(self, frames=64):
"""
Set the number of API-facing buffer frames.
Parameters
----------
frames : int
Number of buffer frames to allocate.
"""
print("Setting API buffer frame count to %d..." % (frames))
frame_current = c_ulong(0)
err1 = self.xeneth.XC_GetPropertyValueL(
self.cam, b"_API_FPC_BFRNUM", byref(frame_current)
)
print("Previous API buffer size: %d frames" % (frame_current.value))
err2 = self.xeneth.XC_SetPropertyValueL(
self.cam, b"_API_FPC_BFRNUM", c_long(frames), ""
)
err3 = self.xeneth.XC_GetPropertyValueL(
self.cam, b"_API_FPC_BFRNUM", byref(frame_current)
)
print(" New API buffer size: %d frames" % (frame_current.value))
if err1 or err2 or err3:
print(
"Warning -- error encountered! Error codes: %d, %d, %d"
% (err1, err2, err3)
)
def set_timeout_api(self, timeout_ms=10000):
"""
Set the get_frame time allowed before issuing E_NOFRAME error.
Warning
~~~~~~~~
Implementation unfinished and untested.
Parameters
----------
timeout_ms : int
Time in ms to wait for blocking frame capture.
"""
print("Setting API timeout to %d ms..." % (timeout_ms))
timeout_current = c_ulong(0)
err1 = self.xeneth.XC_GetPropertyValueL(
self.cam, b"_API_GETFRAME_TIMEOUT", byref(timeout_current)
)
print("Previous API timeout: %d ms" % (timeout_current.value))
err2 = self.xeneth.XC_SetPropertyValueL(
self.cam, b"_API_GETFRAME_TIMEOUT", c_long(timeout_ms), ""
)
err3 = self.xeneth.XC_GetPropertyValueL(
self.cam, b"_API_GETFRAME_TIMEOUT", byref(timeout_current)
)
print(" New API timeout: %d ms" % (timeout_current.value))
if err1 or err2 or err3:
print(
"Warning -- error encountered! Error codes: %d, %d, %d"
% (err1, err2, err3)
)
def set_temperature(self, temp_c):
"""
Set the camera temperature setpoint.
Parameters
----------
temp_c : float
Temperature in degrees celcius to set on startup.
"""
print("Setting settle temperature to %1.2fC..." % (temp_c))
temp_current = c_double(0)
err1 = self.xeneth.XC_GetPropertyValueF(
self.cam, b"SettleTemperature", byref(temp_current)
)
print("Previous set temperature: %1.2f degC" % (temp_current.value - 273.15))
err2 = self.xeneth.XC_SetPropertyValueF(
self.cam, b"SettleTemperature", c_double(temp_c + 273.15), ""
)
err3 = self.xeneth.XC_GetPropertyValueF(
self.cam, b"SettleTemperature", byref(temp_current)
)
print(" New set temperature: %1.2f degC" % (temp_current.value - 273.15))
if err1 or err2 or err3:
print(
"Warning -- error encountered! Error codes: %d, %d, %d"
% (err1, err2, err3)
)
def get_temperature(self):
"""
Get the camera temperature setpoint.
Returns
-------
float
Temperature in degrees celcius to set on startup. -1 if the temperature
could not be read.
"""
temp = -1.0
temp_current = c_double(0)
err = self.xeneth.XC_GetPropertyValueF(
self.cam, b"Temperature", byref(temp_current)
)
if err:
print("Error while reading sensor temperature; code: " + str(err))
else:
temp = temp_current.value - 273.15
return temp
def set_readout_orientation(self, flip_x=True, flip_y=True):
"""
Sets direction of pixel readout from focal plane.
Parameters
----------
flip_x, flip_y : tuple(bool)
Whether a flip will be applied in the X or Y directions.
"""
errs = []
flip_x = c_long(int(flip_x))
flip_y = c_long(int(flip_y))
errs.append(
self.xeneth.XC_SetPropertyValueL(self.cam, b"ReadoutFlipX", flip_x, "")
)
errs.append(
self.xeneth.XC_SetPropertyValueL(self.cam, b"ReadoutFlipY", flip_y, "")
)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"ReadoutFlipX", byref(flip_x))
)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"ReadoutFlipX", byref(flip_x))
)
print(
"Readout orientation set to (flip_x,flip_y) = (%s,%s)"
% (str(bool(flip_x.value)), str(bool(flip_y.value)))
)
if any(errs):
print("Warning! Errors detected in trigger setup. List: ", errs)
def enable_frametags(self, enable=False):
"""
Adds captured frame number to first two pixels of an image.
Disabled by default to prevent issues with autoexposure.
Parameters
----------
enable : bool
Whether to enable or disable.
"""
if enable:
err = self.xeneth.XC_SetPropertyValueE(self.cam, b"FrameMarker", b"Enabled")
else:
err = self.xeneth.XC_SetPropertyValueE(
self.cam, b"FrameMarker", b"Disabled"
)
if err:
print("Error setting frame tags! Code: " + str(err))
else:
print("Frame tags set...")
def setup_input_trigger(
self,
mode=0,
delay=0,
source=0,
skip=0,
fpt=1,
verbose=False,
):
"""
Configure capture control via triggering.
Parameters
----------
mode : int
Trigger properties.\n
0 means free running.\n
1 means level.\n
2 means rising edge.\n
3 means falling edge.
delay : float
Trigger delay in microseconds.
source : int
Source of the input trigger.\n
0 means trigger in.\n
1 means software.\n
2 means CameraLink CC1.
skip : int
Number of frames to skip after trigger.
fpt : int
Frames per trigger.
verbose : bool
Enable debug printout.
"""
trigger_modes = {
0: b"Free running",
1: b"Level",
2: b"Rising edge",
3: b"Falling edge",
}
trigger_sources = {0: b"Trigger in", 1: b"Software", 2: b"CameraLink CC1"}
errs = []
# Get current trigger setup
mode_old = (c_char * 128)(0)
errs.append(
self.xeneth.XC_GetPropertyValueE(
self.cam, b"TriggerMode", byref(mode_old), 128
)
)
delay_old = c_double(0)
errs.append(
self.xeneth.XC_GetPropertyValueF(
self.cam, b"TriggerInputDelay", byref(delay_old)
)
)
source_old = (c_char * 128)(0)
errs.append(
self.xeneth.XC_GetPropertyValueE(
self.cam, b"TriggerSource", byref(source_old), 128
)
)
skip_old = c_long(0)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"TriggerSkip", byref(skip_old))
)
fpt_old = c_long(0)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"NrOfFrames", byref(fpt_old))
)
if verbose:
print(
"Original trigger setup: Mode - %s | Delay - %1.2fus "
"| Source - %s | NSkip - %d | FPT - %d"
% (
mode_old.value.decode(),
delay_old.value,
source_old.value.decode(),
skip_old.value,
fpt_old.value,
)
)
# Set desired trigger setup
errs.append(
self.xeneth.XC_SetPropertyValueL(self.cam, b"NrOfFrames", c_long(fpt), "")
)
errs.append(
self.xeneth.XC_SetPropertyValueE(
self.cam, b"TriggerMode", trigger_modes[mode]
)
)
errs.append(
self.xeneth.XC_SetPropertyValueF(
self.cam, b"TriggerInputDelay", c_double(delay), ""
)
)
errs.append(
self.xeneth.XC_SetPropertyValueE(
self.cam, b"TriggerSource", trigger_sources[source]
)
)
errs.append(
self.xeneth.XC_SetPropertyValueL(self.cam, b"TriggerSkip", c_long(skip), "")
)
# Get final trigger setup
errs.append(
self.xeneth.XC_GetPropertyValueE(
self.cam, b"TriggerMode", byref(mode_old), 128
)
)
errs.append(
self.xeneth.XC_GetPropertyValueF(
self.cam, b"TriggerInputDelay", byref(delay_old)
)
)
errs.append(
self.xeneth.XC_GetPropertyValueE(
self.cam, b"TriggerSource", byref(source_old), 128
)
)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"TriggerSkip", byref(skip_old))
)
errs.append(
self.xeneth.XC_GetPropertyValueL(self.cam, b"NrOfFrames", byref(fpt_old))
)
if verbose:
print(
" New trigger setup: Mode - %s | Delay - %1.2fus "
"| Source - %s | NSkip - %d | FPT - %d"
% (
mode_old.value.decode(),
delay_old.value,
source_old.value.decode(),
skip_old.value,
fpt_old.value,
)
)
if any(errs):
print("Warning! Errors detected in trigger setup. List: ", errs)
def setup_output_trigger(
self,
enable=1,
mode=1,
source=2,
delay=0,
width=10,
verbose=False,