-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgspy.py
1182 lines (1028 loc) · 42.5 KB
/
gspy.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
# coding=utf-8
#TODO: Impliment adjusting camera resolution
import os
import PySpin
import sys
import cv2
from time import perf_counter_ns
def capture_image(cam, timeout=1000, save_path=None, return_array=True):
"""
Once the camera engine has been activated, this function is used to Extract
one image from the buffering memory and save it into a numpy array.
Note that the camera mode must be set, e.g., "Continuous", and the
cam.BeginAcquisition() must be called before calling this function.
Parameters
----------
cam:camera object from PySpin
camera object to be used
timeout:int
timeout for capturing a frame in milliseconds
save_path:str
save_path for saving jpeg file
return_array:bool
whether numpy array is saved
Returns
-------
result:bool
True--success
False--failed
image_averaged:uint8
output image (numpy ndarray).
"""
image_result = cam.GetNextImage(timeout)
# Ensure image completion
if image_result.IsIncomplete():
print('Image incomplete with image status %d ...' % image_result.GetImageStatus(), end="\r")
return False, None
else:
if save_path is not None:
image_result.Save(save_path)
if return_array:
image_array = image_result.GetNDArray()
else:
image_array = None
# Release image
image_result.Release()
return True, image_array
def cam_configuration(nodemap,
s_node_map,
frameRate=30,
pgrExposureCompensation=0,
exposureTime=27084,
gain=0,
blackLevel=0,
bufferCount=15,
verbose=True):
"""
Configurate the camera. Note that the camera must be initialized before calling
this function, i.e., cam.Init() must be called before calling this function.
Parameters
----------
nodemap:INodemap
camera nodemap
s_node_map:INodemap
camera stream nodemap
frameRate:float
Framerate, if given None, it will not be configured.
pgrExposureCompensation:float
Exposure compensation, if given None, it will not be configured.
exposureTime:float
Exposure time in microseconds, if given None, it will not be configured.
gain:float
Gain, if given None, it will not be configured.
blackLevel:float
black level, if given None, it will not be configured.
bufferCount:int
Buffer count, if given None, it will not be configured.
verbose:bool
If information should be printed out
Returns
-------
result:bool
result
"""
print('\n=================== Config camera ==============================================\n')
result = True
AcquisitionMode = get_IEnumeration_node_current_entry_name(nodemap, 'AcquisitionMode', verbose=False)
if not (AcquisitionMode == 'Continuous'):
result &= setAcquisitionMode(nodemap, AcquisitionModeName='Continuous')
OnBoardColorProcessEnabled = get_IBoolean_node_current_val(nodemap, 'OnBoardColorProcessEnabled', verbose=False)
if OnBoardColorProcessEnabled:
result &= disableOnBoardColorProcess(nodemap)
if frameRate is not None:
result &= setFrameRate(nodemap, frameRate=frameRate)
ExposureCompensationAuto = get_IEnumeration_node_current_entry_name(nodemap, 'pgrExposureCompensationAuto', verbose=False)
if not (ExposureCompensationAuto == 'Off'):
result &= disableExposureCompensationAuto(nodemap)
if pgrExposureCompensation is not None:
result &= setExposureCompensation(nodemap, pgrExposureCompensation=pgrExposureCompensation)
if exposureTime is not None:
result &= setExposureTime(nodemap, exposureTime=exposureTime)
if gain is not None:
result &= setGain(nodemap, gain=gain)
if blackLevel is not None:
result &= setBlackLevel(nodemap, blackLevel=blackLevel)
if bufferCount is not None:
result &= setBufferCount(s_node_map, bufferCount=bufferCount)
if verbose:
print('\n=================== Camera status after configuration ==========================\n')
print_camera_config(nodemap, s_node_map)
return result
def acquire_images(cam,
acquisition_index,
num_images,
savedir,
triggerType,
frameRate=30,
pgrExposureCompensation=0,
exposureTime=27084,
gain=0,
blackLevel=0,
bufferCount=15,
timeout=10,
verbose=True):
"""
This function acquires and saves images from a device. Note that camera
must be initialized and configured before calling this function, i.e.,
cam.Init() and cam_configuration(cam,triggerType, ...,) must be called
before calling this function.
:param cam: Camera to acquire images from.
:param acquisition_index: the index number of the current acquisition.
:param num_images: the total number of images to be taken.
:param savedir: directory to save images.
:param triggerType: Must be one of {"software", "hardware", "off"}.
If triggerType is "off", camera is configured for live view.
:param frameRate: frame rate.
:param pgrExposureCompensation: Exposure compensation
:param exposureTime: exposure time in microseconds.
:param gain: gain
:param blackLevel: black level
:param bufferCount: buffer count in RAM
:param timeout: the maximum waiting time in seconds before termination.
:param verbose: verbose print camera config status
:type cam: CameraPtr
:type acquisition_index: int
:type num_images: int
:type savedir: str
:type triggerType: str
:type frameRate: float
:type pgrExposureCompensation: float
:type exposureTime: int
:type gain: float
:type blackLevel: float
:type bufferCount: int
:type timeout: float
:type verbose: bool
:return: True if successful, False otherwise.
:rtype: bool
"""
nodemap = cam.GetNodeMap()
nodemap_tldevice = cam.GetTLDeviceNodeMap()
s_node_map = cam.GetTLStreamNodeMap()
if verbose:
print_device_info(nodemap_tldevice)
print_camera_config(nodemap, s_node_map)
print_trigger_config(nodemap, s_node_map)
result = True
# live view
# config camera
result &= cam_configuration(nodemap=nodemap,
s_node_map=s_node_map,
frameRate=frameRate,
pgrExposureCompensation=pgrExposureCompensation,
exposureTime=exposureTime,
gain=gain,
blackLevel=blackLevel,
bufferCount=bufferCount,
verbose=verbose)
print('*** IMAGE ACQUISITION ***\n')
# config trigger for preview
result &= trigger_configuration(nodemap=nodemap,
s_node_map=s_node_map,
triggerType="off",
verbose=verbose) # 'off' for preview
cam.BeginAcquisition()
while True:
ret, frame = capture_image(cam)
img_show = cv2.resize(frame, None, fx=0.5, fy=0.5)
cv2.imshow("press q to quit", img_show)
key = cv2.waitKey(1)
if key == ord("q"):
break
cam.EndAcquisition()
cv2.destroyAllWindows()
# Retrieve, convert, and save image
# config trigger for image acquisition
result &= trigger_configuration(nodemap=nodemap,
s_node_map=s_node_map,
triggerType=triggerType,
verbose=verbose)
activate_trigger(nodemap)
cam.BeginAcquisition()
if triggerType == "software":
start = perf_counter_ns()
cam.TriggerSoftware.Execute()
ret, image_array = capture_image(cam)
end = perf_counter_ns()
t = (end - start) / 1e9
print('time spent: %2.3f s' % t)
if ret:
filename = 'Acquisition-%02d.jpg' % acquisition_index
save_path = os.path.join(savedir, filename)
cv2.imwrite(save_path, image_array)
print('Image saved at %s' % save_path)
else:
print('Capture failed')
result = False
if triggerType == "hardware":
count = 0
start = perf_counter_ns()
while count < num_images:
try:
ret, image_array = capture_image(cam)
except PySpin.SpinnakerException as ex:
print('Error: %s' % ex)
ret = False
image_array = None
pass
if ret:
print("extract successfully")
filename = 'Acquisition-%02d-%02d.jpg' % (acquisition_index, count)
save_path = os.path.join(savedir, filename)
cv2.imwrite(save_path, image_array)
print('Image saved at %s' % save_path)
count += 1
start = perf_counter_ns()
print('waiting clock is reset')
else:
end = perf_counter_ns()
waiting_time = (end - start) / 1e9
print('Capture failed. Time spent %2.3f s before %2.3f s timeout' % (waiting_time, timeout))
if waiting_time > timeout:
print('timeout is reached, stop capturing image ...')
break
if count == 0:
result = False
cam.EndAcquisition()
deactivate_trigger(nodemap)
return result
def print_device_info(nodemap_tldevice):
"""
This function prints the device information of the camera from the transport
layer.
:param nodemap_tldevice: Transport layer device nodemap.
:returns: True if successful, False otherwise.
:rtype: bool
"""
print('\n*** DEVICE INFORMATION ***\n')
try:
result = True
node_device_information = PySpin.CCategoryPtr(nodemap_tldevice.GetNode('DeviceInformation'))
display_name_node_device_information = node_device_information.GetDisplayName()
print(display_name_node_device_information)
if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(node_device_information):
features = node_device_information.GetFeatures()
for feature in features:
node_feature = PySpin.CValuePtr(feature)
print('%s: %s' % (node_feature.GetName(),
node_feature.ToString() if PySpin.IsReadable(node_feature) else 'Node not readable'))
print('\n')
else:
print('Device control information not available.')
except PySpin.SpinnakerException as ex:
print('Error: %s' % ex)
return False
return result
def run_single_camera(cam,
savedir,
acquisition_index,
num_images,
triggerType,
frameRate=30,
exposureTime=27084,
gain=0,
bufferCount=15,
timeout=10):
"""
Initialize and configurate a camera and take images. This is a wrapper
function.
:param cam: Camera to acquire images from.
:param savedir: directory to save images.
:param acquisition_index: the index number of the current acquisition.
:param num_images: the total number of images to be taken.
:param triggerType: trigger type, must be one of {"software", "hardware"}
:param frameRate: framerate.
:param exposureTime: exposure time in microseconds.
:param gain: gain
:param bufferCount: buffer count number on RAM
:param timeout: the waiting time in seconds before termination
:type cam: CameraPtr
:type savedir: str
:type acquisition_index: int
:type num_images: int
:type triggerType: str
:type frameRate: float
:type exposureTime: int
:type gain: float
:type bufferCount: int
:type timeout: float
:return: True if successful, False otherwise.
:rtype: bool
"""
try:
result = True
# Initialize camera
cam.Init()
# Acquire images
result &= acquire_images(cam=cam,
acquisition_index=acquisition_index,
num_images=num_images,
savedir=savedir,
triggerType=triggerType,
frameRate=frameRate,
exposureTime=exposureTime,
gain=gain,
bufferCount=bufferCount,
timeout=timeout)
# Deinitialize camera
cam.DeInit()
except PySpin.SpinnakerException as ex:
print('Error: %s' % ex)
result = False
return result
def sysScan():
"""
Scan the system and find all available cameras
Returns
-------
result : bool
Operation result, True or False.
system : system object
Camera system object
cam_list : list
Camera list.
num_cameras : int
Number of cameras.
"""
result = True
# Retrieve singleton reference to system object
system = PySpin.System.GetInstance()
# Get current library version
version = system.GetLibraryVersion()
print('Library version: %d.%d.%d.%d' % (version.major, version.minor, version.type, version.build))
# Retrieve list of cameras from the system
cam_list = system.GetCameras()
# Get the total number of cameras
num_cameras = cam_list.GetSize()
if not cam_list:
result = False
print('No camera is detected...')
else:
print('Number of cameras detected: %d' % num_cameras)
return result, system, cam_list, num_cameras
def clearDir(targetDir):
"""
Clear the directory
Parameters
----------
targetDir:str
targetDir to be cleared.
Returns
-------
None.
"""
if len(os.listdir(targetDir)) != 0:
for f in os.listdir(targetDir):
os.remove(os.path.join(targetDir, f))
print('Directory is cleared!')
else:
print('The target directory is empty! No image file needs to be removed')
def get_IEnumeration_node_current_entry_name(nodemap, nodename, verbose=True):
node = PySpin.CEnumerationPtr(nodemap.GetNode(nodename))
node_int_val = node.GetIntValue()
node_entry = node.GetEntry(node_int_val)
node_entry_name = node_entry.GetSymbolic()
if verbose:
node_description = node.GetDescription()
node_entries = node.GetEntries() # node_entries is a list of INode instances
print('%s: %s' % (nodename, node_entry_name))
print(node_description)
print('All entries are listed below:')
for i, entry in enumerate(node_entries):
entry_name = PySpin.CEnumEntryPtr(entry).GetSymbolic()
print('%d: %s' % (i, entry_name))
print('\n')
return node_entry_name
def get_IInteger_node_current_val(nodemap, nodename, verbose=True):
node = PySpin.CIntegerPtr(nodemap.GetNode(nodename))
node_val = node.GetValue()
if verbose:
node_val_max = node.GetMax()
node_val_min = node.GetMin()
node_description = node.GetDescription()
print('%s: %d' % (nodename, node_val))
print(node_description)
print('Max = %d' % node_val_max)
print('Min = %d' % node_val_min)
print('\n')
return node_val
def get_IFloat_node_current_val(nodemap, nodename, verbose=True):
node = PySpin.CFloatPtr(nodemap.GetNode(nodename))
node_val = node.GetValue()
if verbose:
node_val_max = node.GetMax()
node_val_min = node.GetMin()
node_unit = node.GetUnit()
print('%s: %f' % (nodename, node_val))
print('Max = %f' % node_val_max)
print('Min = %f' % node_val_min)
print('Unit: ', node_unit)
print('\n')
return node_val
def get_IString_node_current_str(nodemap, nodename, verbose=True):
node = PySpin.CStringPtr(nodemap.GetNode(nodename))
node_str = node.GetValue()
if verbose:
node_description = node.GetDescription()
print('%s: %s' % (nodename, node_str))
print(node_description, '\n')
return node_str
def get_IBoolean_node_current_val(nodemap, nodename, verbose=True):
node = PySpin.CBooleanPtr(nodemap.GetNode(nodename))
node_val = node.GetValue()
if verbose:
node_description = node.GetDescription()
print('%s: %s' % (nodename, node_val))
print(node_description, '\n')
return node_val
def disableOnBoardColorProcess(nodemap):
ptrOnBoardColorProcessEnabled = PySpin.CBooleanPtr(nodemap.GetNode("OnBoardColorProcessEnabled"))
if (not PySpin.IsAvailable(ptrOnBoardColorProcessEnabled)) or (not PySpin.IsWritable(ptrOnBoardColorProcessEnabled)):
print('Unable to retrieve OnBoardColorProcessEnabled. Aborting...')
return False
ptrOnBoardColorProcessEnabled.SetValue(False)
print('Set OnBoardColorProcessEnabled to False')
return True
def enableFrameRateSetting(nodemap):
# Turn off "AcquisitionFrameRateAuto"
acqFrameRateAuto = PySpin.CEnumerationPtr(nodemap.GetNode("AcquisitionFrameRateAuto"))
if (not PySpin.IsAvailable(acqFrameRateAuto)) or (not PySpin.IsWritable(acqFrameRateAuto)):
print('Unable to retrieve AcquisitionFrameRateAuto. Aborting...')
return False
acqFrameRateAutoOff = acqFrameRateAuto.GetEntryByName('Off')
if (not PySpin.IsAvailable(acqFrameRateAutoOff)) or (not PySpin.IsReadable(acqFrameRateAutoOff)):
print('Unable to set Buffer Handling mode (Value retrieval). Aborting...')
return False
acqFrameRateAuto.SetIntValue(acqFrameRateAutoOff.GetValue()) # setting to Off
print('Set AcquisitionFrameRateAuto to off')
# Turn on "AcquisitionFrameRateEnabled"
acqFrameRateEnabled = PySpin.CBooleanPtr(nodemap.GetNode("AcquisitionFrameRateEnabled"))
if (not PySpin.IsAvailable(acqFrameRateEnabled)) or (not PySpin.IsWritable(acqFrameRateEnabled)):
print('Unable to retrieve AcquisitionFrameRateEnabled. Aborting...')
return False
acqFrameRateEnabled.SetValue(True)
print('Set AcquisitionFrameRateEnabled to True')
return True
def setFrameRate(nodemap, frameRate):
"""
Set frame rate
Parameters
----------
nodemap:INodemap
camera nodemap
frameRate:float
frame rate
Returns
-------
result:bool
result
"""
# First enable framerate setting
if not enableFrameRateSetting(nodemap):
return False
# frame rate should be a float number. Get the node and check availability
ptrAcquisitionFramerate = PySpin.CFloatPtr(nodemap.GetNode("AcquisitionFrameRate"))
if (not PySpin.IsAvailable(ptrAcquisitionFramerate)) or (not PySpin.IsWritable(ptrAcquisitionFramerate)):
print('Unable to retrieve AcquisitionFrameRate. Aborting...')
return False
# Set framerate value
ptrAcquisitionFramerate.SetValue(frameRate)
print('AcquisitionFrameRate set to %3.3f Hz' % frameRate)
return True
def enableExposureAuto(nodemap):
# Get the node "ExposureAuto" and convert it to Enumeration class
ptrExposureAuto = PySpin.CEnumerationPtr(nodemap.GetNode("ExposureAuto"))
if (not PySpin.IsAvailable(ptrExposureAuto)) or (not PySpin.IsWritable(ptrExposureAuto)):
print('Unable to retrieve ExposureAuto. Aborting...')
return False
# Get the "Continuous" entry
ExposureAuto_on = ptrExposureAuto.GetEntryByName("Continuous")
if (not PySpin.IsAvailable(ExposureAuto_on)) or (not PySpin.IsReadable(ExposureAuto_on)):
print('Unable to set ExposureAuto mode to Continuous. Aborting...')
return False
# set the "Continuous" entry to ExposureAuto
ptrExposureAuto.SetIntValue(ExposureAuto_on.GetValue())
print('ExposureAuto mode is set to "Continuous"')
return True
def disableExposureAuto(nodemap):
# Get the node "ExposureAuto" and convert it to Enumeration class
ptrExposureAuto = PySpin.CEnumerationPtr(nodemap.GetNode("ExposureAuto"))
if (not PySpin.IsAvailable(ptrExposureAuto)) or (not PySpin.IsWritable(ptrExposureAuto)):
print('Unable to retrieve ExposureAuto. Aborting...')
return False
# Get the "Off" entry
ExposureAuto_off = ptrExposureAuto.GetEntryByName("Off")
if (not PySpin.IsAvailable(ExposureAuto_off)) or (not PySpin.IsReadable(ExposureAuto_off)):
print('Unable to set ExposureAuto mode to Off. Aborting...')
return False
# set the "Off" entry to ExposureAuto
ptrExposureAuto.SetIntValue(ExposureAuto_off.GetValue())
print('ExposureAuto mode is set to "off"')
return True
def disableExposureCompensationAuto(nodemap):
# Get the node "ExposureCompensationAuto" and convert it to Enumeration class
ptrExposureCompensationAuto = PySpin.CEnumerationPtr(nodemap.GetNode("pgrExposureCompensationAuto"))
if (not PySpin.IsAvailable(ptrExposureCompensationAuto)) or (not PySpin.IsWritable(ptrExposureCompensationAuto)):
print('Unable to retrieve ExposureCompensationAuto. Aborting...')
return False
# Get the "Off" entry
ExposureCompensationAuto_off = ptrExposureCompensationAuto.GetEntryByName("Off")
if (not PySpin.IsAvailable(ExposureCompensationAuto_off)) or (not PySpin.IsReadable(ExposureCompensationAuto_off)):
print('Unable to set ExposureCompensationAuto mode to Off. Aborting...')
return False
# set the "Off" entry to ExposureAuto
ptrExposureCompensationAuto.SetIntValue(ExposureCompensationAuto_off.GetValue())
print('ExposureCompensationAuto mode is set to "off"')
return True
def setExposureMode(nodemap, exposureModeToSet):
"""
Sets the operation mode of the exposure (shutter). Toggles the Trigger
Selector. Timed = Exposure Start; Trigger Width = Exposure Active
Parameters
----------
nodemap:INodeMap
Camara nodemap.
exposureModeToSet:str
ExposureModeEnums, must be one of {"Timed", "TriggerWidth"}
Returns
-------
result:bool
result
"""
# Get the node "ExposureMode" and check if it is available and writable
ptrExposureMode = PySpin.CEnumerationPtr(nodemap.GetNode("ExposureMode"))
if (not PySpin.IsAvailable(ptrExposureMode)) or (not PySpin.IsWritable(ptrExposureMode)):
print('Unable to retrieve ExposureMode. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
ExposureMode_selected = ptrExposureMode.GetEntryByName(exposureModeToSet)
if (not PySpin.IsAvailable(ExposureMode_selected)) or (not PySpin.IsReadable(ExposureMode_selected)):
print('Unable to set ExposureMode to %s. Aborting...' % exposureModeToSet)
return False
# Set the entry to the node
ptrExposureMode.SetIntValue(ExposureMode_selected.GetValue())
print('ExposureMode is set to %s' % exposureModeToSet)
return True
def setTriggerMode(nodemap, TriggerModeToSet):
"""
Controls whether the selected trigger is active
Parameters
----------
nodemap:INodeMap
Camara nodemap.
TriggerModeToSet:str
TriggerModeEnums, must be one of {"Off", "On"}
Returns
-------
result:bool
result
"""
# Get the node "TriggerMode" and check if it is available and writable
ptrTriggerMode = PySpin.CEnumerationPtr(nodemap.GetNode("TriggerMode"))
if (not PySpin.IsAvailable(ptrTriggerMode)) or (not PySpin.IsWritable(ptrTriggerMode)):
print('Unable to retrieve TriggerMode. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
TriggerMode_selected = ptrTriggerMode.GetEntryByName(TriggerModeToSet)
if (not PySpin.IsAvailable(TriggerMode_selected)) or (not PySpin.IsReadable(TriggerMode_selected)):
print('Unable to set TriggerMode to %s. Aborting...' % TriggerModeToSet)
return False
ptrTriggerMode.SetIntValue(TriggerMode_selected.GetValue())
print('TriggerMode is set to %s...' % TriggerModeToSet)
return True
def setTriggerActivation(nodemap, TriggerActivationToSet):
"""
Specifies the activation mode of the trigger
Parameters
----------
nodemap:INodeMap
Camara nodemap.
TriggerActivationToSet:str
TriggerActivationEnums, must be one of {"FallingEdge", "RisingEdge"}
Returns
-------
result:bool
result.
"""
# Get the node "TriggerActivation" and check if it is available and writable
ptrTriggerActivation = PySpin.CEnumerationPtr(nodemap.GetNode("TriggerActivation"))
if (not PySpin.IsAvailable(ptrTriggerActivation)) or (not PySpin.IsWritable(ptrTriggerActivation)):
print('Unable to retrieve TriggerActivation. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
TriggerActivation_selected = ptrTriggerActivation.GetEntryByName(TriggerActivationToSet)
if (not PySpin.IsAvailable(TriggerActivation_selected)) or (not PySpin.IsReadable(TriggerActivation_selected)):
print('Unable to set TriggerActivation to %s. Aborting...' % TriggerActivationToSet)
return False
ptrTriggerActivation.SetIntValue(TriggerActivation_selected.GetValue())
print('TriggerActivation is set to %s...' % TriggerActivationToSet)
return True
def setTriggerOverlap(nodemap, TriggerOverlapToSet):
"""
Overlapped Exposure Readout Trigger
Parameters
----------
nodemap:INodeMap
Camara nodemap.
TriggerOverlapToSet:str
TriggerOverlapEnums, must be one of {"Off", "ReadOut"}
Returns
-------
result:bool
result.
"""
# Get the node "TriggerOverlap" and check if it is available and writable
ptrTriggerOverlap = PySpin.CEnumerationPtr(nodemap.GetNode("TriggerOverlap"))
if (not PySpin.IsAvailable(ptrTriggerOverlap)) or (not PySpin.IsWritable(ptrTriggerOverlap)):
print('Unable to retrieve TriggerOverlap. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
TriggerOverlap_selected = ptrTriggerOverlap.GetEntryByName(TriggerOverlapToSet)
if (not PySpin.IsAvailable(TriggerOverlap_selected)) or (not PySpin.IsReadable(TriggerOverlap_selected)):
print('Unable to set TriggerOverlap to %s. Aborting...' % TriggerOverlapToSet)
return False
ptrTriggerOverlap.SetIntValue(TriggerOverlap_selected.GetValue())
print('TriggerOverlap is set to %s..' % TriggerOverlapToSet)
return True
def setTriggerSelector(nodemap, TriggerSelectorToSet):
"""
Selects the type of trigger to configure. Derived from Exposure Mode.
Parameters
----------
nodemap:INodeMap
Camara nodemap.
TriggerSelectorToSet:str
TriggerSelectorEnums, must be one of {"FrameStart", "ExposureActive"}.
Returns
-------
result:bool
result
"""
# Get the node "TriggerOverlap" and check if it is available and writable
ptrTriggerSelector = PySpin.CEnumerationPtr(nodemap.GetNode("TriggerSelector"))
if (not PySpin.IsAvailable(ptrTriggerSelector)) or (not PySpin.IsWritable(ptrTriggerSelector)):
print('Unable to retrieve TriggerSelector. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
TriggerSelector_selected = ptrTriggerSelector.GetEntryByName(TriggerSelectorToSet)
if (not PySpin.IsAvailable(TriggerSelector_selected)) or (not PySpin.IsReadable(TriggerSelector_selected)):
print('Unable to set TriggerSelector to %s. Aborting...' % TriggerSelectorToSet)
return False
ptrTriggerSelector.SetIntValue(TriggerSelector_selected.GetValue())
print('TriggerSelector is set to %s...' % TriggerSelectorToSet)
return True
def setTriggerSource(nodemap, TriggerSourceToSet):
"""
Specifies the internal signal or physical input line to use as the trigger source.
Parameters
----------
nodemap:INodeMap
Camara nodemap.
TriggerSourceToSet:str
TriggerSourceEnums, must be one of {"Software", "Line0", "Line1", "Line2", "Line3"}.
Returns
-------
result:bool
result
"""
# Get the node "TriggerSource" and check if it is available and writable
ptrTriggerSource = PySpin.CEnumerationPtr(nodemap.GetNode("TriggerSource"))
if (not PySpin.IsAvailable(ptrTriggerSource)) or (not PySpin.IsWritable(ptrTriggerSource)):
print('Unable to retrieve TriggerSource. Aborting...')
return False
# Get the Entry to be set and check if it is available and writable
TriggerSource_selected = ptrTriggerSource.GetEntryByName(TriggerSourceToSet)
if (not PySpin.IsAvailable(TriggerSource_selected)) or (not PySpin.IsReadable(TriggerSource_selected)):
print('Unable to set TriggerSource to %s. Aborting...' % TriggerSourceToSet)
return False
ptrTriggerSource.SetIntValue(TriggerSource_selected.GetValue())
print('TriggerSource is set to %s...' % TriggerSourceToSet)
return True
def setExposureTime(nodemap, exposureTime=None):
"""
Set exposure time in microseconds.
Parameters
----------
nodemap:INodemap
camera nodemap
exposureTime:float
exposure time in microseconds, if None is given, the maximum possible exposure time is used.
Returns
-------
result:bool
result
"""
# First set the exposure mode to "timed"
if not setExposureMode(nodemap, "Timed"):
return False
# Second disable the ExposureAuto
if not disableExposureAuto(nodemap):
return False
# Get the node "ExposureTime" and check if it is available and writable
ptrExposureTime = PySpin.CFloatPtr(nodemap.GetNode("ExposureTime"))
if (not PySpin.IsAvailable(ptrExposureTime)) or (not PySpin.IsWritable(ptrExposureTime)):
print('Unable to retrieve Exposure Time. Aborting...')
return False
# Ensure desired exposure time does not exceed the maximum
exposureTimeMax = ptrExposureTime.GetMax()
if exposureTime is None:
exposureTime = exposureTimeMax
else:
if exposureTime > exposureTimeMax:
exposureTime = exposureTimeMax
# Set the exposure time
ptrExposureTime.SetValue(exposureTime)
print('Exposure Time set to %5.2f us' % exposureTime)
return True
def setAcquisitionMode(nodemap, AcquisitionModeName):
"""
Explicitly set AcquisitionMode
Parameters
----------
nodemap:INodemap
camera nodemap.
AcquisitionModeName:str
must be one from the three: Continuous, SingleFrame, MultiFrame.
Returns
-------
result:bool
result
"""
# Retrieve enumeration node from nodemap
# # In order to access the node entries, they have to be cast to a pointer type (CEnumerationPtr here)
node_acquisition_mode = PySpin.CEnumerationPtr(nodemap.GetNode('AcquisitionMode'))
if (not PySpin.IsAvailable(node_acquisition_mode)) or (not PySpin.IsWritable(node_acquisition_mode)):
print('Unable to set acquisition mode to continuous (enum retrieval). Aborting...')
return False
# Retrieve entry node from enumeration node
node_acquisition_mode_selected = node_acquisition_mode.GetEntryByName(AcquisitionModeName)
if (not PySpin.IsAvailable(node_acquisition_mode_selected)) or (not PySpin.IsReadable(node_acquisition_mode_selected)):
print('Unable to set acquisition mode to %s. Aborting...' % node_acquisition_mode_selected)
return False
# Set integer value from entry node as new value of enumeration node
node_acquisition_mode.SetIntValue(node_acquisition_mode_selected.GetValue())
print('Acquisition mode set to %s' % AcquisitionModeName)
return True
def setStreamBufferHandlingMode(s_node_map, StreamBufferHandlingModeName):
"""
Explicitly set StreamBufferHandlingModeName
Parameters
----------
s_node_map:INodemap
steam nodemap.
StreamBufferHandlingModeName:str
must be one from the four: OldestFirst, OldestFirstOverwrite, NewestOnly, NewestFirst.
Returns
-------
result:bool
result
"""
handlingMode = PySpin.CEnumerationPtr(s_node_map.GetNode('StreamBufferHandlingMode'))
if (not PySpin.IsAvailable(handlingMode)) or (not PySpin.IsWritable(handlingMode)):
print('Unable to set Buffer Handling mode (node retrieval). Aborting...')
return False
handlingModeSelected = handlingMode.GetEntryByName(StreamBufferHandlingModeName)
if (not PySpin.IsAvailable(handlingModeSelected)) or (not PySpin.IsReadable(handlingModeSelected)):
print('Unable to set Buffer Handling mode (Value retrieval). Aborting...')
return False
handlingMode.SetIntValue(handlingModeSelected.GetValue())
print('Buffer Handling Mode set to %s...' % StreamBufferHandlingModeName)
return True
def setBufferCount(s_node_map, bufferCount):
"""
Set manual buffer count
Parameters
----------
s_node_map:INodemap
stream nodemap
bufferCount:int
buffer count number
Returns
-------
result:bool
result
"""
# Retrieve and modify Stream Buffer Count
buffer_count = PySpin.CIntegerPtr(s_node_map.GetNode('StreamBufferCountManual'))
if (not PySpin.IsAvailable(buffer_count)) or (not PySpin.IsWritable(buffer_count)):
print('Unable to set Buffer Count (Integer node retrieval). Aborting...')
return False
buffer_count.SetValue(bufferCount)
print('Buffer count now set to: %d' % buffer_count.GetValue())
return True
def disableGainAuto(nodemap):
"""
Disable Gain Auto
Parameters
----------
nodemap:INodemap
camera nodemap
Returns
-------
result:bool
result
"""
gainAuto = PySpin.CEnumerationPtr(nodemap.GetNode("GainAuto"))
if (not PySpin.IsAvailable(gainAuto)) or (not PySpin.IsWritable(gainAuto)):
print('Unable to retrieve GainAuto. Aborting...')
return False
gainAutoOff = gainAuto.GetEntryByName('Off')
if (not PySpin.IsAvailable(gainAutoOff)) or (not PySpin.IsReadable(gainAutoOff)):
print('Unable to set GainAuto to off (Value retrieval). Aborting...')
return False
# setting "Off" for the Gain auto
gainAuto.SetIntValue(gainAutoOff.GetValue()) # setting to Off
print('Set GainAuto to off')
return True
def setGain(nodemap, gain):
"""
Set camera gain value.
Parameters
----------
nodemap:INodemap
camera nodemap
gain:float
gain
Returns
-------
result:bool
result
"""
# First disable gainAuto
if not disableGainAuto(nodemap):
return False
# Get the node "Gain" and check the availability
gainValue = PySpin.CFloatPtr(nodemap.GetNode("Gain"))
if (not PySpin.IsAvailable(gainValue)) or (not PySpin.IsWritable(gainValue)):
print('Unable to retrieve Gain. Aborting...')
return False
# Set the gain value
gainValue.SetValue(gain)
print('Set Gain to %2.3f' % gain)
return True
def setBlackLevel(nodemap, blackLevel):
"""
Set the camera black level.
Parameters
----------
nodemap:INodemap
Camera nodemap
blackLevel:float
black level
Returns
-------
result:bool
result
"""