サンプルプログラム¶
サンプル一覧¶
ファイル名 |
機能 |
画像取得 |
コールバック |
サードパーティー |
---|---|---|---|---|
AWB, AGC, AE |
Yes |
StApi(クラス) |
numpy, opencv-python |
|
カメラ側ROI |
Yes |
|||
デバイスロスト検出 |
Yes |
GenApi(関数) |
||
ノードマップのアクセス |
||||
トリガー |
Yes |
StApi(関数) |
||
GigEVision ActionCommand |
Yes |
StApi(関数), GenApi(クラス) |
||
GigEVision設定 |
Yes |
|||
GigEVision Multicast |
Yes |
|||
コールバックで取得 |
Yes |
StApi(クラス) |
||
コールバックで取得、表示 |
Yes |
StApi(クラス) |
numpy, opencv-python |
|
コールバックで取得 |
Yes |
StApi(関数) |
||
カメライベント |
Yes |
GenApi(関数) |
||
チャンク |
Yes |
|||
シンプル取得、StApi画像処理で画像変換、OpenCVで表示 |
Yes |
numpy, opencv-python |
||
シンプル取得、OpenCVで画像変換と表示 |
Yes |
numpy, opencv-python |
||
シンプル取得 |
Yes |
|||
Host側ROI |
Yes |
numpy, opencv-python |
||
マルチカメラ |
Yes |
|||
マルチシステム |
Yes |
|||
画像ファイルの保存と読み取り |
Yes |
|||
設定ファイル |
No |
|||
動画の保存 |
Yes |
|||
StApi IPで画像変換 |
Yes |
numpy, opencv-python |
||
StApi IPで画像フィルター |
Yes |
numpy, opencv-python |
||
ユーザーデータを保存できるメモリーを操作 |
No |
|||
User set, feature bag |
No |
ソースコード¶
auto_functions_opencv.py¶
1"""
2 This sample demostrates how to set AWB, AGC, and AE function.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Register and use callback function with StApi
7 - Acquire image via callback function
8 - Set AWB, AGC, AE
9 - Copy image data for OpenCV
10 - Convert Bayer image format to RGB using OpenCV
11 - Preview image using OpenCV
12 Note: opencv-python and numpy packages are required:
13 pip install numpy
14 pip install opencv-python
15"""
16
17import cv2
18import threading
19import numpy as np
20import stapipy as st
21
22# Image scale when displaying using OpenCV.
23DISPLAY_RESIZE_FACTOR = 0.3
24
25# Feature names
26EXPOSURE_AUTO = "ExposureAuto"
27GAIN_AUTO = "GainAuto"
28BALANCE_WHITE_AUTO = "BalanceWhiteAuto"
29
30AUTO_LIGHT_TARGET = "AutoLightTarget"
31GAIN = "Gain"
32GAIN_RAW = "GainRaw"
33
34EXPOSURE_MODE = "ExposureMode"
35EXPOSURE_TIME = "ExposureTime"
36EXPOSURE_TIME_RAW = "ExposureTimeRaw" # Custom
37
38BALANCE_RATIO_SELECTOR = "BalanceRatioSelector"
39BALANCE_RATIO = "BalanceRatio"
40
41
42class CMyCallback:
43 """
44 Class that contains a callback function.
45 """
46
47 def __init__(self):
48 self._image = None
49 self._lock = threading.Lock()
50
51 @property
52 def image(self):
53 """Property: return PyIStImage of the grabbed image."""
54 duplicate = None
55 self._lock.acquire()
56 if self._image is not None:
57 duplicate = self._image.copy()
58 self._lock.release()
59 return duplicate
60
61 def datastream_callback(self, handle=None, context=None):
62 """
63 Callback to handle events from DataStream.
64
65 :param handle: handle that trigger the callback.
66 :param context: user data passed on during callback registration.
67 """
68 st_datastream = handle.module
69 if st_datastream:
70 with st_datastream.retrieve_buffer() as st_buffer:
71 # Check if the acquired data contains image data.
72 if st_buffer.info.is_image_present:
73 # Create an image object.
74 st_image = st_buffer.get_image()
75
76 # Check the pixelformat of the input image.
77 pixel_format = st_image.pixel_format
78 pixel_format_info = st.get_pixel_format_info(pixel_format)
79
80 # Only mono or bayer is processed.
81 if not(pixel_format_info.is_mono or pixel_format_info.is_bayer):
82 return
83
84 # Get raw image data.
85 data = st_image.get_image_data()
86
87 # Perform pixel value scaling if each pixel component is
88 # larger than 8bit. Example: 10bit Bayer/Mono, 12bit, etc.
89 if pixel_format_info.each_component_total_bit_count > 8:
90 nparr = np.frombuffer(data, np.uint16)
91 division = pow(2, pixel_format_info
92 .each_component_valid_bit_count - 8)
93 nparr = (nparr / division).astype('uint8')
94 else:
95 nparr = np.frombuffer(data, np.uint8)
96
97 # Process image for display.
98 nparr = nparr.reshape(st_image.height, st_image.width, 1)
99
100 # Perform color conversion for Bayer.
101 if pixel_format_info.is_bayer:
102 bayer_type = pixel_format_info.get_pixel_color_filter()
103 if bayer_type == st.EStPixelColorFilter.BayerRG:
104 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_RG2RGB)
105 elif bayer_type == st.EStPixelColorFilter.BayerGR:
106 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GR2RGB)
107 elif bayer_type == st.EStPixelColorFilter.BayerGB:
108 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GB2RGB)
109 elif bayer_type == st.EStPixelColorFilter.BayerBG:
110 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_BG2RGB)
111
112 # Resize image and store to self._image.
113 nparr = cv2.resize(nparr, None,
114 fx=DISPLAY_RESIZE_FACTOR,
115 fy=DISPLAY_RESIZE_FACTOR)
116 self._lock.acquire()
117 self._image = nparr
118 self._lock.release()
119
120
121def edit_enumeration(nodemap, enum_name):
122 """
123 Display and allow user to modify the enumeration value.
124
125 :param nodemap: node map.
126 :param enum_name: name of the enumeration node.
127 """
128 node = nodemap.get_node(enum_name)
129 if not node.is_writable:
130 return
131
132 # Cast to PyIEnumeration from PyNode
133 enum_node = st.PyIEnumeration(node)
134
135 while True:
136 print(enum_name)
137 enum_entries = enum_node.entries
138 for index in range(len(enum_entries)):
139 enum_entry = enum_entries[index]
140 if enum_entry.is_available:
141 print("{0} : {1} {2}".format(index,
142 st.PyIEnumEntry(enum_entry).symbolic_value,
143 "(Current)" if enum_node.value == enum_entry.value
144 else ""))
145 selection = int(input("Select : "))
146 if selection < len(enum_entries):
147 enum_entry = enum_entries[selection]
148 enum_node.set_int_value(enum_entry.value)
149 break
150
151
152def edit_setting(nodemap, node_name):
153 """
154 Edit setting which has numeric type.
155
156 :param nodemap: Node map.
157 :param node_name: Node name.
158 """
159 node = nodemap.get_node(node_name)
160 if not node.is_writable:
161 return
162 if node.principal_interface_type == st.EGCInterfaceType.IFloat:
163 node_value = st.PyIFloat(node)
164 elif node.principal_interface_type == st.EGCInterfaceType.IInteger:
165 node_value = st.PyIInteger(node)
166 while True:
167 print(node_name)
168 print(" Min={0} Max={1} Current={2}{3}".format(
169 node_value.min, node_value.max, node_value.value,
170 " Inc={0}".format(node_value.inc) if\
171 node_value.inc_mode == st.EGCIncMode.FixedIncrement\
172 else ""))
173 new_value = input("New value : ")
174 print()
175 if node.principal_interface_type == st.EGCInterfaceType.IFloat:
176 new_numeric_value = float(new_value)
177 else:
178 new_numeric_value = int(new_value)
179 if node_value.min <= new_numeric_value <= node_value.max:
180 node_value.value = new_numeric_value
181 return
182
183
184def edit_enum_setting(nodemap, enum_name, numeric_name):
185 """
186 Display the contents of the current enumeration node and edit settings.
187
188 :param nodemap: Node map.
189 :param enum_name: Enumeration name.
190 :param numeric_name: Numeric name.
191 """
192 node = nodemap.get_node(enum_name)
193 if not node.is_writable:
194 return
195
196 enum_node = st.PyIEnumeration(node)
197 enum_entries = enum_node.entries
198 for index in range(len(enum_entries)):
199 enum_entry = enum_entries[index]
200 if enum_entry.is_available:
201 enum_node.value = enum_entry.value
202 print("{0} = {1}".format(enum_name,
203 st.PyIEnumEntry(enum_entry).symbolic_value))
204 edit_setting(nodemap, numeric_name)
205
206
207def exposure_auto(nodemap):
208 """Configure exposure using the given nodemap."""
209 # Configure the ExposureMode
210 edit_enumeration(nodemap, EXPOSURE_MODE)
211
212 # Configure the ExposureAuto
213 edit_enumeration(nodemap, EXPOSURE_AUTO)
214
215 # Configure the AutoLightTarget
216 edit_setting(nodemap, AUTO_LIGHT_TARGET)
217
218 if nodemap.get_node(EXPOSURE_TIME):
219 edit_setting(nodemap, EXPOSURE_TIME)
220 else:
221 edit_setting(nodemap, EXPOSURE_TIME_RAW)
222
223
224def gain_auto(nodemap):
225 """Configure gain using the given nodemap."""
226 # Configure the GainAuto
227 edit_enumeration(nodemap, GAIN_AUTO)
228
229 # Configure the AutoLightTarget
230 edit_setting(nodemap, AUTO_LIGHT_TARGET)
231
232 if nodemap.get_node(GAIN):
233 edit_setting(nodemap, GAIN)
234 else:
235 edit_setting(nodemap, GAIN_RAW)
236
237
238def balance_white_auto(nodemap):
239 """Configure balance ratio/white using the given nodemap."""
240 # Configure the BalanceWhiteAuto
241 edit_enumeration(nodemap, BALANCE_WHITE_AUTO)
242
243 # While switching the BalanceRatioSelector, configure the BalanceRatio
244 edit_enum_setting(nodemap, BALANCE_RATIO_SELECTOR, BALANCE_RATIO)
245
246
247def do_auto_functions(nodemap):
248 """Function running in a separate thread for auto function configuration."""
249 # Check if features available.
250 feature_list = [EXPOSURE_AUTO, GAIN_AUTO, BALANCE_WHITE_AUTO]
251 is_writable_list = [False, False, False]
252 for index, feature in enumerate(feature_list):
253 with nodemap.get_node(feature) as node:
254 is_writable_list[index]=True if node.is_writable else False
255
256 while True:
257 print()
258 print("Auto Functions")
259 for index, feature in enumerate(feature_list):
260 if is_writable_list[index]:
261 print("{0} : {1}".format(index, feature))
262 print("Else : Exit")
263 selection = int(input("Select : "))
264 if selection == 0 and is_writable_list[selection] == True:
265 exposure_auto(nodemap)
266 elif selection == 1 and is_writable_list[selection] == True:
267 gain_auto(nodemap)
268 elif selection == 2 and is_writable_list[selection] == True:
269 balance_white_auto(nodemap)
270 else:
271 print("Focus on the OpenCV window and press any key to terminate.")
272 break
273
274
275if __name__ == "__main__":
276 my_callback = CMyCallback()
277 cb_func = my_callback.datastream_callback
278 try:
279 # Initialize StApi before using.
280 st.initialize()
281
282 # Create a system object for device scan and connection.
283 st_system = st.create_system()
284
285 # Connect to first detected device.
286 st_device = st_system.create_first_device()
287
288 # Display DisplayName of the device.
289 print('Device=', st_device.info.display_name)
290
291 # Create a datastream object for handling image stream data.
292 st_datastream = st_device.create_datastream()
293
294 # Register callback for datastream
295 callback = st_datastream.register_callback(cb_func)
296
297 # Start the image acquisition of the host (local machine) side.
298 st_datastream.start_acquisition()
299
300 # Start the image acquisition of the camera side.
301 st_device.acquisition_start()
302
303 # Get device nodemap to access the device settings.
304 remote_nodemap = st_device.remote_port.nodemap
305
306 # Create and start a thread for auto function configuration.
307 autofunc_thread = threading.Thread(target=do_auto_functions,
308 args=(remote_nodemap,))
309 autofunc_thread.start()
310
311 # Display image using OpenCV.
312 while True:
313 output_image = my_callback.image
314 if output_image is not None:
315 cv2.imshow('image', output_image)
316 key_input = cv2.waitKey(1)
317 if key_input != -1:
318 break
319
320 autofunc_thread.join()
321
322 # Stop the image acquisition of the camera side
323 st_device.acquisition_stop()
324
325 # Stop the image acquisition of the host side
326 st_datastream.stop_acquisition()
327
328 except Exception as exception:
329 print(exception)
camera_side_roi.py¶
1"""
2 This sample shows how to set ROI in camera side and handle the image data.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Set image ROI parameter
7 - Acquire image data
8 - Process the acquired ROI images
9"""
10
11import stapipy as st
12
13# Number of images to grab
14number_of_images_to_grab = 100
15
16# Feature names
17PIXEL_FORMAT = "PixelFormat"
18REGION_SELECTOR = "RegionSelector"
19REGION_MODE = "RegionMode"
20OFFSET_X = "OffsetX"
21OFFSET_Y = "OffsetY"
22WIDTH = "Width"
23HEIGHT = "Height"
24
25
26def edit_enumeration(nodemap, enum_name) -> bool:
27 """
28 Display and edit enumeration value.
29
30 :param nodemap: Node map.
31 :param enum_name: Enumeration name.
32 :return: True if enumeration value is updated. False otherwise.
33 """
34 node = nodemap.get_node(enum_name)
35 if not node.is_writable:
36 return False
37 enum_node = st.PyIEnumeration(node)
38 enum_entries = enum_node.entries
39 print(enum_name)
40 for index in range(len(enum_entries)):
41 enum_entry = enum_entries[index]
42 if enum_entry.is_available:
43 print("{0} : {1} {2}".format(index,
44 st.PyIEnumEntry(enum_entry).symbolic_value,
45 "(Current)" if enum_node.value == enum_entry.value
46 else ""))
47 print("Else : Exit")
48 selection = int(input("Select : "))
49 if selection < len(enum_entries) and enum_entries[selection].is_available:
50 enum_entry = enum_entries[selection]
51 enum_node.set_int_value(enum_entry.value)
52 return True
53
54
55def edit_setting(nodemap, node_name):
56 """
57 Edit setting which has numeric type.
58
59 :param nodemap: Node map.
60 :param node_name: Node name.
61 """
62 node = nodemap.get_node(node_name)
63 if not node.is_writable:
64 return
65 if node.principal_interface_type == st.EGCInterfaceType.IFloat:
66 node_value = st.PyIFloat(node)
67 elif node.principal_interface_type == st.EGCInterfaceType.IInteger:
68 node_value = st.PyIInteger(node)
69 while True:
70 print(node_name)
71 print(" Min={0} Max={1} Current={2}{3}".format(
72 node_value.min, node_value.max, node_value.value,
73 " Inc={0}".format(node_value.inc) if\
74 node_value.inc_mode == st.EGCIncMode.FixedIncrement\
75 else ""))
76 new_value = int(input("New value : "))
77 print()
78 if node_value.min <= new_value <= node_value.max:
79 node_value.value = new_value
80 return
81
82
83def set_camera_side_roi(nodemap):
84 """
85 Set camera side ROI.
86
87 :param nodemap: Node map.
88 """
89 region_selector = nodemap.get_node(REGION_SELECTOR)
90 if not region_selector.is_writable:
91 # Single ROI:
92 edit_setting(nodemap, OFFSET_X)
93 edit_setting(nodemap, WIDTH)
94 edit_setting(nodemap, OFFSET_Y)
95 edit_setting(nodemap, HEIGHT)
96 else:
97 while True:
98 if not edit_enumeration(nodemap, REGION_SELECTOR):
99 return
100
101 edit_enumeration(nodemap, REGION_MODE)
102 region_mode = st.PyIEnumeration(nodemap.get_node(REGION_MODE))
103 if region_mode.current_entry.value != region_mode["Off"].value:
104 edit_setting(nodemap, OFFSET_X)
105 edit_setting(nodemap, WIDTH)
106 edit_setting(nodemap, OFFSET_Y)
107 edit_setting(nodemap, HEIGHT)
108
109
110if __name__ == "__main__":
111 try:
112 # Initialize StApi before using.
113 st.initialize()
114
115 # Create a system object for device scan and connection.
116 st_system = st.create_system()
117
118 # Connect to first detected device.
119 st_device = st_system.create_first_device()
120
121 # Display DisplayName of the device.
122 print('Device=', st_device.info.display_name)
123
124 # Create a datastream object for handling image stream data.
125 st_datastream = st_device.create_datastream()
126
127 # Get INodeMap object to access the setting of the device.
128 remote_nodemap = st_device.remote_port.nodemap
129
130 # Check and set PixelFormat
131 edit_enumeration(remote_nodemap, PIXEL_FORMAT)
132
133 # Check and set CameraSideROI
134 set_camera_side_roi(remote_nodemap)
135
136 # Start the image acquisition of the host (local machine) side.
137 st_datastream.start_acquisition(number_of_images_to_grab)
138
139 # Start the image acquisition of the camera side.
140 st_device.acquisition_start()
141
142 # A while loop for acquiring data and checking status
143 while st_datastream.is_grabbing:
144 # Create a localized variable st_buffer using 'with'
145 # Warning: if st_buffer is in a global scope, st_buffer must be
146 # assign to None to allow Garbage Collector release the buffer
147 # properly.
148 with st_datastream.retrieve_buffer() as st_buffer:
149 # Check if the acquired data contains image data.
150 if st_buffer.info.is_image_present:
151 # Create an image object.
152 st_image = st_buffer.get_image()
153 # Display the information of the acquired image data.
154 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
155 st_buffer.info.frame_id,
156 st_image.width, st_image.height,
157 st_image.get_image_data()[0]))
158 else:
159 # If the acquired data contains no image data.
160 print("Image data does not exist.")
161
162 # Stop the image acquisition of the camera side
163 st_device.acquisition_stop()
164
165 # Stop the image acquisition of the host side
166 st_datastream.stop_acquisition()
167
168 except Exception as exception:
169 print(exception)
event_device_lost.py¶
1"""
2 This sample shows how to setup and detect device connection lost.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Detect the disconnection of camera
7 """
8
9# Import stapipy package
10import stapipy as st
11
12EVENT_SELECTOR = "EventSelector"
13EVENT_NOTIFICATION = "EventNotification"
14EVENT_NOTIFICATION_ON = "On"
15TARGET_EVENT_NAME = "DeviceLost"
16CALLBACK_NODE_NAME = "EventDeviceLost"
17
18def node_callback(node=None, st_device=None):
19 """
20 Callback to handle events from GenICam node.
21
22 :param node: node that triggered the callback.
23 :param st_device: PyStDevice object passed on at callback registration.
24 """
25 if node.is_available:
26 if st_device.is_device_lost:
27 print("OnNodeEvent: {0}: DeviceLost".format(node.display_name))
28 else:
29 print("OnNodeEvent: {0}: Invalidated".format(node.display_name))
30
31
32def do_grabbing(st_device):
33 """Perform grabbing using the given st_device. """
34
35 # Display DisplayName of the device.
36 print('Device=', st_device.info.display_name)
37
38 # Get host side device setting (nodemap)
39 st_nodemap = st_device.local_port.nodemap
40
41 # Get EventDeviceLost node
42 st_event_node = st_nodemap.get_node(CALLBACK_NODE_NAME)
43
44 # Register callback for EventDeviceLost
45 # To ensure the device lost flag is already updated when fired, here we
46 # use OutsideLock flag (executed on leaving outside the lock-guarded
47 # GenApi node.
48 st_event_node.register_callback(node_callback, st_device,
49 st.EGCCallbackType.OutsideLock)
50
51 # Enable the transmission of the target event
52 st_event_selector = st.PyIEnumeration(st_nodemap.get_node(EVENT_SELECTOR))
53 st_event_selector.set_symbolic_value(TARGET_EVENT_NAME)
54
55 st_event_notification = \
56 st.PyIEnumeration(st_nodemap.get_node(EVENT_NOTIFICATION))
57 st_event_notification.set_symbolic_value(EVENT_NOTIFICATION_ON)
58
59 # Start event handling thread
60 st_device.start_event_acquisition()
61
62 # Create a datastream object for handling image stream data.
63 st_datastream = st_device.create_datastream()
64
65 # Start the image acquisition of the host (local machine) side.
66 st_datastream.start_acquisition()
67
68 # Start the image acquisition of the camera side.
69 st_device.acquisition_start()
70
71 # A while loop for acquiring data and checking status
72 while st_datastream.is_grabbing:
73 # Create a localized variable st_buffer using 'with'
74 # Warning: if st_buffer is in a global scope, st_buffer must be
75 # cleared to None to allow Garbage Collector release the buffer
76 # properly.
77 with st_datastream.retrieve_buffer(5000) as st_buffer:
78 # Check if the acquired data contains image data.
79 if st_buffer.info.is_image_present:
80 # Create an image object.
81 st_image = st_buffer.get_image()
82 # Display the information of the acquired image data.
83 print("BlockID={0} Size={1} x {2} First Byte={3} "
84 "(Unplug the camera to trigger device lost).".format(
85 st_buffer.info.frame_id,
86 st_image.width, st_image.height,
87 st_image.get_image_data()[0]))
88 else:
89 # If the acquired data contains no image data.
90 print("Image data does not exist.")
91
92 # Stop the image acquisition of the camera side
93 st_device.acquisition_stop()
94
95 # Stop the image acquisition of the host side
96 st_datastream.stop_acquisition()
97
98 # Stop event acquisition thread
99 st_device.stop_event_acquisition()
100
101
102try:
103 # Initialize StApi before using.
104 st.initialize()
105
106 # Create a system object for device scan and connection.
107 # If StApi has not been initialized, StApi will automatically initialize
108 # itself.
109 st_system = st.create_system()
110
111 device_id = ''
112
113 repeat = True
114 while repeat:
115 st_device = None
116 if device_id == '':
117 # Connect to first detected device.
118 st_device = st_system.create_first_device()
119
120 # Hold the device ID for re-open
121 device_id = st_device.info.device_id
122 else:
123 # Get the number of interfaces
124 interface_count = st_system.interface_count
125 for interface_index in range(interface_count):
126 st_interface = st_system.get_interface(interface_index)
127 try:
128 st_device = st_interface.create_device_by_id(device_id)
129 except:
130 pass
131
132 if st_device:
133 try:
134 do_grabbing(st_device)
135 except:
136 if not st_device.is_device_lost:
137 raise
138
139 print("0 : Reopen the same device")
140 print(" Warning: for GigEVision device, you may need to set the "
141 "camera IP to persistent before running this example")
142 print("Else : Exit")
143 selection = input("Selection :")
144 if str(selection) != "0":
145 break
146
147except Exception as exception:
148 print(exception)
featurelist.py¶
1"""
2 This sample will list all support functions of connected camera.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Access Nodes of NodeMap for displaying camera's features
7"""
8
9import stapipy as st
10
11
12def display_nodes(node):
13 """
14 Function to display node
15
16 :param node: node to display
17 """
18 if not node.is_implemented:
19 return
20 # Display the interface type and name
21 print("{0} : {1}".format(node.principal_interface_type.name, node.name))
22 if node.principal_interface_type == st.EGCInterfaceType.ICategory:
23 # Display all the features that belong to the category
24 feature_list = st.PyICategory(node).feature_list
25 for feature in feature_list:
26 display_nodes(feature)
27 elif node.principal_interface_type == st.EGCInterfaceType.IEnumeration:
28 # Display all entries if the type is Enumeration
29 entry_list = st.PyIEnumeration(node).entries
30 for entry in entry_list:
31 display_nodes(entry)
32
33try:
34 # Initialize StApi before using.
35 st.initialize()
36
37 # Create a system object for device scan and connection.
38 st_system = st.create_system()
39
40 # Connect to first detected device.
41 st_device = st_system.create_first_device()
42
43 # Display DisplayName of the device.
44 print('Device=', st_device.info.display_name)
45
46 # Display nodes
47 display_nodes(st_device.remote_port.nodemap.get_node("Root"))
48
49except Exception as exception:
50 print(exception)
framestart_trigger.py¶
1"""
2 This sample shows how to use trigger mode of the camera
3 The The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Set trigger mode and send trigger
7"""
8
9import stapipy as st
10
11TRIGGER_SELECTOR = "TriggerSelector"
12TRIGGER_SELECTOR_FRAME_START = "FrameStart"
13TRIGGER_SELECTOR_EXPOSURE_START = "ExposureStart"
14TRIGGER_MODE = "TriggerMode"
15TRIGGER_MODE_ON = "On"
16TRIGGER_MODE_OFF = "Off"
17TRIGGER_SOURCE = "TriggerSource"
18TRIGGER_SOURCE_SOFTWARE = "Software"
19TRIGGER_SOFTWARE = "TriggerSoftware"
20
21def datastream_callback(handle=None, context=None):
22 """
23 Callback to handle events from DataStream.
24
25 :param handle: handle that trigger the callback.
26 :param context: user data passed on during callback registration.
27 """
28 if handle.callback_type == st.EStCallbackType.GenTLDataStreamNewBuffer:
29 try:
30 st_datastream = handle.module
31 with st_datastream.retrieve_buffer(0) as st_buffer:
32 # Check if the acquired data contains image data.
33 if st_buffer.info.is_image_present:
34 # Create an image object.
35 st_image = st_buffer.get_image()
36 # Display the information of the acquired image data.
37 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
38 st_buffer.info.frame_id,
39 st_image.width, st_image.height,
40 st_image.get_image_data()[0]))
41 else:
42 # If the acquired data contains no image data.
43 print("Image data does not exist.")
44 except st.PyStError as exception:
45 print("An exception occurred.", exception)
46
47
48def set_enumeration(nodemap, enum_name, entry_name):
49 """
50 Function to set enumeration value.
51
52 :param nodemap: node map.
53 :param enum_name: name of the enumeration node.
54 :param entry_name: symbolic value of the enumeration entry node.
55 """
56 enum_node = st.PyIEnumeration(nodemap.get_node(enum_name))
57 entry_node = st.PyIEnumEntry(enum_node[entry_name])
58 # Note that depending on your use case, there are three ways to set
59 # the enumeration value:
60 # 1) Assign the integer value of the entry with set_int_value(val) or .value
61 # 2) Assign the symbolic value of the entry with set_symbolic_value("val")
62 # 3) Assign the entry (PyIEnumEntry) with set_entry_value(entry)
63 # Here set_entry_value is used:
64 enum_node.set_entry_value(entry_node)
65
66
67if __name__ == "__main__":
68 try:
69 # Initialize StApi before using.
70 st.initialize()
71
72 # Create a system object for device scan and connection.
73 st_system = st.create_system()
74
75 # Connect to first detected device.
76 st_device = st_system.create_first_device()
77
78 # Display DisplayName of the device.
79 print('Device=', st_device.info.display_name)
80
81 # Get the nodemap for the camera settings.
82 nodemap = st_device.remote_port.nodemap
83
84 # Set the TriggerSelector for FrameStart or ExposureStart.
85 try:
86 set_enumeration(
87 nodemap, TRIGGER_SELECTOR, TRIGGER_SELECTOR_FRAME_START)
88 except st.PyStError:
89 set_enumeration(
90 nodemap, TRIGGER_SELECTOR, TRIGGER_SELECTOR_EXPOSURE_START)
91
92 # Set the TriggerMode to On.
93 set_enumeration(nodemap, TRIGGER_MODE, TRIGGER_MODE_ON)
94
95 # Set the TriggerSource to Software
96 set_enumeration(nodemap, TRIGGER_SOURCE, TRIGGER_SOURCE_SOFTWARE)
97
98 # Get and cast to Command interface of the TriggerSoftware mode
99 trigger_software = st.PyICommand(nodemap.get_node(TRIGGER_SOFTWARE))
100
101 # Create a datastream object for handling image stream data.
102 st_datastream = st_device.create_datastream()
103
104 # Register callback for datastream
105 callback = st_datastream.register_callback(datastream_callback)
106
107 # Start the image acquisition of the host (local machine) side.
108 st_datastream.start_acquisition()
109
110 # Start the image acquisition of the camera side.
111 st_device.acquisition_start()
112
113 while True:
114 print("0 : Generate trigger")
115 print("Else : Exit")
116 selection = input("Select : ")
117 if selection == '0':
118 trigger_software.execute()
119 else:
120 break
121
122 # Stop the image acquisition of the camera side
123 st_device.acquisition_stop()
124
125 # Stop the image acquisition of the host side
126 st_datastream.stop_acquisition()
127
128 # Set the TriggerMode to Off.
129 set_enumeration(nodemap, TRIGGER_MODE, TRIGGER_MODE_OFF)
130
131 except Exception as exception:
132 print(exception)
gige_action_command.py¶
1"""
2 This sample shows how to use GigE Action command.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to GigE camera
6 - Set and send action command
7"""
8
9import time
10import stapipy as st
11
12DEVICE_KEY = 0x12345678
13GROUP_KEY = 0x00000001
14GROUP_MASK = 0xFFFFFFFF
15SCHEDULED_TIME_ENABLE = False
16
17scheduled_time = 0
18
19
20class CActionCommandEvent:
21 def __init__(self, iface):
22 self.iface = iface
23 self.callback_func_sent = self.on_command_sent
24 self.callback_func_recv = self.on_ack_received
25
26 nodemap = self.iface.port.nodemap
27 self.event_action_cmd = nodemap.get_node("EventActionCommand")
28 self.cb_command_sent = self.event_action_cmd.register_callback(
29 self.callback_func_sent, self.iface, st.EGCCallbackType.OutsideLock)
30
31 self.event_action_cmd_req_id = \
32 nodemap.get_node("EventActionCommandRequestID")
33
34 self.event_action_cmd_ack = \
35 nodemap.get_node("EventActionCommandAcknowledge")
36 self.cb_ack_received = self.event_action_cmd_ack.register_callback(
37 self.callback_func_recv, self.iface, st.EGCCallbackType.OutsideLock)
38
39 self.event_action_cmd_ack_src_ip = \
40 nodemap.get_node("EventActionCommandAcknowledgeSourceIPAddress")
41 self.event_action_cmd_ack_status = \
42 nodemap.get_node("EventActionCommandAcknowledgeStatus")
43 self.event_action_cmd_ack_id = \
44 nodemap.get_node("EventActionCommandAcknowledgeAcknowledgeID")
45
46 self.gev_action_dest_ip = \
47 nodemap.get_node("GevActionDestinationIPAddress")
48
49 def __del__(self):
50 self.event_action_cmd.deregister_callbacks()
51 self.event_action_cmd_ack.deregister_callbacks()
52
53 def on_command_sent(self, node, context):
54 """Callback function triggered when action command is sent."""
55 print("Sent action command[{0}]: {1}".format(
56 self.event_action_cmd_req_id.value,
57 self.gev_action_dest_ip.get().to_string()
58 ))
59
60 def on_ack_received(self, node, context):
61 """Callback function triggered when action command ack is received."""
62 print("Received action command[{0}] : {1}({2})".format(
63 self.event_action_cmd_ack_id.value,
64 self.event_action_cmd_ack_src_ip.get().to_string(),
65 self.event_action_cmd_ack_status.get().current_entry.display_name
66 ))
67
68
69class CActionCommandInterface:
70 def __init__(self, iface):
71 self._iface = iface
72 self._action_cmd_event = CActionCommandEvent(self._iface)
73 nodemap = self._iface.port.nodemap
74 self.action_cmd = nodemap.get_node("ActionCommand")
75
76 def get_interface(self):
77 return self._iface
78
79 def execute(self):
80 self.action_cmd.get().execute()
81
82
83def send_action_command(action_interfaces):
84 """Send action command."""
85 while True:
86 selection = input("Input (0: Action Command, 1: Exit) : ")
87 if selection == "0":
88 for item in action_interfaces:
89 item.execute()
90 time.sleep(0.5)
91 elif selection == '1':
92 break
93
94
95def adjust_gev_scpd(device_list):
96 """Adjust GevSCPD for the devices in the device_list."""
97 packet_size = device_list[0].remote_port.nodemap.get_node(
98 "GevSCPSPacketSize")
99 if packet_size is None:
100 return
101
102 timestamp_latch = device_list[0].remote_port.nodemap.get_node(
103 "TimestampLatchValue")
104 if timestamp_latch is None:
105 return
106
107 max_bps = 100000000
108 each_packet_time_ns = packet_size.value * 1000000000 * \
109 (len(device_list) - 1) / max_bps
110 timestamp_unit = timestamp_latch.get().inc
111 if timestamp_unit == 0:
112 timestamp_unit = 40
113 for device in device_list:
114 device.remote_port.nodemap.get_node("GevSCPD").value = \
115 each_packet_time_ns / timestamp_unit
116
117
118def datastream_callback(handle=None, context=None):
119 """
120 Callback to handle events from DataStream.
121
122 :param handle: handle that trigger the callback.
123 :param context: user data passed on during callback registration.
124 """
125 st_datastream = handle.module
126 if st_datastream:
127 with st_datastream.retrieve_buffer() as st_buffer:
128 # Check if the acquired data contains image data.
129 if st_buffer.info.is_image_present:
130 # Create an image object.
131 st_image = st_buffer.get_image()
132 # Display the information of the acquired image data.
133 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
134 st_buffer.info.frame_id,
135 st_image.width, st_image.height,
136 st_image.get_image_data()[0]))
137 else:
138 # If the acquired data contains no image data.
139 print("Image data does not exist.")
140
141
142def set_device_action_cmd_param(device):
143 """Set device action command parameters."""
144 nodemap = device.remote_port.nodemap
145 trigger_selector = nodemap.get_node("TriggerSelector").get()
146 trigger_selector.set_symbolic_value("FrameStart")
147 print(" TriggerSelector = FrameStart")
148
149 trigger_mode = nodemap.get_node("TriggerMode").get()
150 trigger_mode.set_symbolic_value("On")
151 print(" TriggerMode = On")
152
153 trigger_source = nodemap.get_node("TriggerSource").get()
154 trigger_source_list = ["Action0", "Action1"]
155 for trigger_src_name in trigger_source_list:
156 try:
157 trigger_source.set_symbolic_value(trigger_src_name)
158 print(" TriggerSource =", trigger_src_name)
159 break
160 except st.PyStError:
161 pass
162
163 action_device_key = nodemap.get_node("ActionDeviceKey")
164 action_device_key.value = DEVICE_KEY
165 print(" ActionDeviceKey =", hex(DEVICE_KEY))
166
167 action_selector = nodemap.get_node("ActionSelector")
168 action_selector.value = action_selector.get().min
169 print(" ActionSelector =", action_selector.get().min)
170
171 action_group_key = nodemap.get_node("ActionGroupKey")
172 action_group_key.value = GROUP_KEY
173 print(" ActionGroupKey =", hex(GROUP_KEY))
174
175 action_group_mask = nodemap.get_node("ActionGroupMask")
176 action_group_mask.value = GROUP_MASK
177 print(" ActionGroupMask =", hex(GROUP_MASK))
178
179
180def set_host_action_cmd_param(iface):
181 """Set host action command parameters."""
182 nodemap = iface.port.nodemap
183 event_selector = nodemap.get_node("EventSelector").get()
184 event_notification = nodemap.get_node("EventNotification").get()
185
186 event_names = ["ActionCommand", "ActionCommandAcknowledge"]
187 for item in event_names:
188 event_selector.set_symbolic_value(item)
189 print(" EventSelector =", item)
190 event_notification.set_symbolic_value("On")
191 print(" EventNotification = On")
192
193 action_device_key = nodemap.get_node("ActionDeviceKey")
194 action_device_key.value = DEVICE_KEY
195 print(" ActionDeviceKey =", hex(DEVICE_KEY))
196
197 action_group_key = nodemap.get_node("ActionGroupKey")
198 action_group_key.value = GROUP_KEY
199 print(" ActionGroupKey =", hex(GROUP_KEY))
200
201 action_group_mask = nodemap.get_node("ActionGroupMask")
202 action_group_mask.value = GROUP_MASK
203 print(" ActionGroupMask =", hex(GROUP_MASK))
204
205 action_scheduled_time_enable = nodemap.get_node("ActionScheduledTimeEnable")
206 action_scheduled_time_enable.value = SCHEDULED_TIME_ENABLE
207 print(" ActionScheduledTimeEnable =", SCHEDULED_TIME_ENABLE)
208 if SCHEDULED_TIME_ENABLE:
209 action_scheduled_time = nodemap.get_node("ActionScheduledTime")
210 action_scheduled_time.value = scheduled_time
211 print(" ActionScheduledTIme =", scheduled_time)
212
213
214if __name__ == "__main__":
215 try:
216 # Initialize StApi before using.
217 st.initialize()
218
219 # Create a system object for device scan and connection.
220 st_system = st.create_system(st.EStSystemVendor.Default,
221 st.EStInterfaceType.GigEVision)
222
223 st_action_interfaces = []
224
225 # Check if there is no GigE device, raise Exception.
226 for index in range(st_system.interface_count):
227 iface = st_system.get_interface(index)
228 try:
229 iface_subnet_ip = iface.port.nodemap.get_node(
230 "GevInterfaceSubnetIPAddress").get()
231 print("Interface {0} = {1} [{2}]".format(
232 index, iface.info.display_name,
233 iface_subnet_ip.to_string()))
234 set_host_action_cmd_param(iface)
235 iface.start_event_acquisition()
236 action_interface = CActionCommandInterface(iface)
237 st_action_interfaces.append(action_interface)
238 except Exception as exception:
239 print("An exception occurred.", exception)
240
241 if len(st_action_interfaces) == 0:
242 raise RuntimeError("There is no GigE interface found.")
243
244 # Try to connect to all possible device:
245 st_devices = []
246 st_datastreams = []
247 while True:
248 try:
249 st_devices.append(st_system.create_first_device())
250 except:
251 if len(st_devices) == 0:
252 raise
253 break
254
255 # Display the DisplayName of the device.
256 print("Device {0} = {1} [{2}]".format(len(st_devices),
257 st_devices[len(st_devices)-1].info.display_name,
258 st_devices[len(st_devices)-1].local_port.nodemap.get_node(
259 "GevDeviceIPAddress").get().to_string()))
260
261 # Set action command parameter.
262 set_device_action_cmd_param(st_devices[len(st_devices)-1])
263
264 # Create a DataStream object.
265 st_datastreams.append(
266 st_devices[len(st_devices)-1].create_datastream())
267
268 # Register callback for grabbing.
269 st_datastreams[len(st_datastreams)-1].register_callback(
270 datastream_callback)
271
272 # Start the image acquisition of the host side.
273 for datastream in st_datastreams:
274 datastream.start_acquisition()
275
276 # Start the image acquisition of the camera side.
277 for device in st_devices:
278 device.acquisition_start()
279
280 # Adjust GevSCPD and send action command.
281 adjust_gev_scpd(st_devices)
282 send_action_command(st_action_interfaces)
283
284 # Stop the image acquisition of the camera side.
285 for device in st_devices:
286 device.acquisition_stop()
287
288 # Stop the image acquisition of the host side.
289 for datastream in st_datastreams:
290 datastream.stop_acquisition()
291
292 # Stop event acquisition thread.
293 for action_interface in st_action_interfaces:
294 action_interface.get_interface().stop_event_acquisition()
295
296 except Exception as exception:
297 print(exception)
gige_configurations.py¶
1"""
2 This sample shows how to setup the IP address and heartbeat timeout of GigE camera.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Acquire image data
7 - Check and update IP address of GigE camera
8 - Update heartbeat timeout of GigE camera
9"""
10
11import time
12import ipaddress
13import stapipy as st
14
15# Number of images to grab
16number_of_images_to_grab = 100
17
18# Feature names
19GEV_INTERFACE_SUBNET_IP_ADDRESS = "GevInterfaceSubnetIPAddress"
20GEV_INTERFACE_SUBNET_MASK = "GevInterfaceSubnetMask"
21
22DEVICE_SELECTOR = "DeviceSelector"
23GEV_DEVICE_IP_ADDRESS = "GevDeviceIPAddress"
24GEV_DEVICE_SUBNET_MASK = "GevDeviceSubnetMask"
25
26GEV_DEVICE_FORCE_IP_ADDRESS = "GevDeviceForceIPAddress"
27GEV_DEVICE_FORCE_SUBNET_MASK = "GevDeviceForceSubnetMask"
28GEV_DEVICE_FORCE_IP = "GevDeviceForceIP"
29DEVICE_LINK_HEARTBEAT_TIMEOUT = "DeviceLinkHeartbeatTimeout"
30GEV_HEARTBEAT_TIMEOUT = "GevHeartbeatTimeout"
31
32
33def update_device_ip_address(nodemap):
34 """
35 Function for checking and updating device IP address.
36
37 :param nodemap: node map of the device.
38 """
39 # Display the IP address of the host side.
40 iface_ip = nodemap.get_node(GEV_INTERFACE_SUBNET_IP_ADDRESS).get()
41 print("Interface IP address =", iface_ip.to_string())
42
43 # Display the subnet mask of the host side.
44 iface_mask = nodemap.get_node(GEV_INTERFACE_SUBNET_MASK).get()
45 print("Interface Subnet mask =", iface_mask.to_string())
46
47 while True:
48 # Select the first device.
49 device_selector = nodemap.get_node(DEVICE_SELECTOR)
50 device_selector.value = 0
51
52 # Display the current IP address of the device.
53 device_ip = nodemap.get_node(GEV_DEVICE_IP_ADDRESS).get()
54 print("Device IP Address =", device_ip.to_string())
55
56 # Display the current subnet mask of the device.
57 device_mask = nodemap.get_node(GEV_DEVICE_SUBNET_MASK).get()
58 print("Device Subnet Mask =", device_mask.to_string())
59
60 new_ip_str = input("Input new device IP address (x.x.x.x) : ")
61 new_ip_int = int(ipaddress.ip_address(new_ip_str))
62 iface_ip_int = iface_ip.value
63 iface_mask_int = iface_mask.value
64
65 # Ensure the subnet address of the host and the device are matched
66 # and the host and the device have different IP address.
67 if (iface_ip_int & iface_mask_int) == (new_ip_int & iface_mask_int)\
68 and iface_ip_int != new_ip_int:
69 # Specify the new ip address of the device.
70 force_ip = nodemap.get_node(GEV_DEVICE_FORCE_IP_ADDRESS)
71 force_ip.value = new_ip_int
72
73 # Specify the new subnet mask of the device.
74 force_mask = nodemap.get_node(GEV_DEVICE_FORCE_SUBNET_MASK)
75 force_mask.value = iface_mask_int
76
77 # Update the device setting.
78 force_ip_cmd = nodemap.get_node(GEV_DEVICE_FORCE_IP).get()
79 force_ip_cmd.execute()
80 return
81
82
83def update_heartbeat_timeout(nodemap):
84 """
85 Function for reading and updating heartbeat timeout.
86
87 :param nodemap: nodemap of the device.
88 """
89 while True:
90 heartbeat = nodemap.get_node(DEVICE_LINK_HEARTBEAT_TIMEOUT).get()
91 if heartbeat:
92 unit = "[us]"
93 else:
94 heartbeat = nodemap.get_node(GEV_HEARTBEAT_TIMEOUT).get()
95 if heartbeat:
96 unit = "[ms]"
97 else:
98 print("Unable to get the current heartbeat value")
99 return
100
101 print()
102 print("Warning: the heartbeat sending interval is fixed when the device "
103 "is initialized (opened).")
104 print("Thus, changing the heartbeat timeout smaller than the current "
105 "value may cause timeout.")
106 print("In practical situation, please either set environment variable "
107 "STGENTL_GIGE_HEARTBEAT before opening the device")
108 print("or re-open the device after changing the heartbeat value without "
109 "setting the environment variable and debugger.")
110 print()
111 print("Current Heartbeat Timeout%s=%.4f" % (unit, heartbeat.value))
112
113 # Update the HeartbeatTimeout setting.
114 new_heartbeat = input("Input new Heartbeat Timeout"+unit+":")
115 heartbeat.from_string(new_heartbeat)
116 return
117
118
119def create_ist_device_by_ip(pinterface, ip_address) -> st.PyStDevice:
120 """
121 Function to connect to device based on the given ip address.
122
123 :param pinterface PyStDevice: interface of the device.
124 :param ip_address: IP address of the device in integer.
125 :return: connected device (PyStDevice).
126 """
127 pinterface.update_device_list()
128 iface_nodemap = pinterface.port.nodemap
129 device_selector = iface_nodemap.get_node("DeviceSelector").get()
130 max_index = device_selector.max
131 device_ip = iface_nodemap.get_node("GevDeviceIPAddress")
132 for index in range(max_index+1):
133 device_selector.value = index
134 if device_ip.is_available:
135 if device_ip.value == ip_address:
136 return pinterface.create_device_by_index(index)
137 return None
138
139
140if __name__ == "__main__":
141 try:
142 # Initialize StApi before using.
143 st.initialize()
144
145 # Create a system object for device scan and connection only for GigE.
146 st_system = st.create_system(st.EStSystemVendor.Default,
147 st.EStInterfaceType.GigEVision)
148 for index in range(st_system.interface_count):
149 st_interface = st_system.get_interface(index)
150 if st_interface.device_count > 0:
151 break
152
153 # Update the IP address setting of the first detected GigE device.
154 update_device_ip_address(st_interface.port.nodemap)
155
156 # Get the updated IP address
157 device_force_ip = st_interface.port.nodemap\
158 .get_node(GEV_DEVICE_FORCE_IP_ADDRESS)
159
160 # Create a camera device object and connect.
161 st_device = None
162 for loop in range(30):
163 time.sleep(1)
164 st_device = create_ist_device_by_ip(st_interface,
165 device_force_ip.value)
166 if st_device:
167 break
168 if st_device is None:
169 raise Exception("A device ip IP address {0} could not be found"\
170 .format(device_force_ip.get().to_string()))
171
172 # Display DisplayName of the device.
173 print('Device=', st_device.info.display_name)
174
175 # Update the HeartBeatTimeout settings.
176 update_heartbeat_timeout(st_device.remote_port.nodemap)
177
178 # Create a datastream object for handling image stream data.
179 st_datastream = st_device.create_datastream()
180
181 # Start the image acquisition of the host (local machine) side.
182 st_datastream.start_acquisition(number_of_images_to_grab)
183
184 # Start the image acquisition of the camera side.
185 st_device.acquisition_start()
186
187 # A while loop for acquiring data and checking status
188 while st_datastream.is_grabbing:
189 # Create a localized variable st_buffer using 'with'
190 # Warning: if st_buffer is in a global scope, st_buffer must be
191 # assign to None to allow Garbage Collector release the buffer
192 # properly.
193 with st_datastream.retrieve_buffer() as st_buffer:
194 # Check if the acquired data contains image data.
195 if st_buffer.info.is_image_present:
196 # Create an image object.
197 st_image = st_buffer.get_image()
198 # Display the information of the acquired image data.
199 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
200 st_buffer.info.frame_id,
201 st_image.width, st_image.height,
202 st_image.get_image_data()[0]))
203 else:
204 # If the acquired data contains no image data.
205 print("Image data does not exist.")
206
207 # Stop the image acquisition of the camera side
208 st_device.acquisition_stop()
209
210 # Stop the image acquisition of the host side
211 st_datastream.stop_acquisition()
212
213 except Exception as exception:
214 print(exception)
gige_multicast.py¶
1"""
2 This sample shows how to use the multicast function of GigE camera for multiple receivers.
3 The monitor clients must connect after any one client connect to camera in control mode.
4 The following points will be demonstrated in this sample code:
5 - Initialize StApi
6 - Connect to camera
7 - Acquire image data (with waiting in main thread)
8 - Connect to camera in control mode / monitor mode
9 - Multicast the image data
10 - Broadcast the image data
11"""
12
13import stapipy as st
14
15# Number of images to grab
16number_of_images_to_grab = 100
17
18# Feature names
19DESTINATION_IP_ADDRESS = "DestinationIPAddress"
20DESTINATION_PORT = "DestinationPort"
21TRANSMISSION_TYPE = "TransmissionType"
22TRANSMISSION_TYPE_USE_CAMERA_CONFIGURATION = "UseCameraConfiguration"
23
24try:
25 # Initialize StApi before using.
26 st.initialize()
27
28 # Select the connecting mode (control/monitor) of the camera.
29 # You can connect to a camera in monitor mode if it has already connected
30 # by other host with control mode.
31 # Note if you connect to a camera in monitor mode, you cannot modify the
32 # camera settings.
33 is_monitor = False
34 while True:
35 print()
36 print("c : Control mode")
37 print("m : Monitor mode")
38 selection = input("Select a mode : ")
39 if selection not in ['c', 'C', 'm', 'M']:
40 continue
41 is_monitor = True if selection == 'm' or selection == 'M' else False
42 break
43
44 st_system = st.create_system(st.EStSystemVendor.Default,
45 st.EStInterfaceType.GigEVision)
46
47 # Connect to first detected device.
48 st_device = st_system.create_first_device(
49 st.ETLDeviceAccessFlags.AccessReadOnly if is_monitor else \
50 st.ETLDeviceAccessFlags.AccessControl)
51
52 # Display DisplayName of the device.
53 print('Device=', st_device.info.display_name)
54
55 # Create a datastream object for handling image stream data.
56 st_datastream = st_device.create_datastream()
57
58 # Get the IENumeration of TransmissionType.
59 transtype = st_datastream.port.nodemap\
60 .get_node(TRANSMISSION_TYPE).get()
61 # Get the setting based on the connection type.
62 if is_monitor:
63 camera_config = transtype[TRANSMISSION_TYPE_USE_CAMERA_CONFIGURATION]
64 transtype_value = camera_config.value
65 else:
66 transtype_list = transtype.entries
67 while True:
68 print("Supported transmission types are as follows.")
69 for index in range(len(transtype_list)):
70 print("{0} : {1}".format(index,
71 transtype_list[index].get().symbolic_value))
72 selection = int(input("Select a transmission type : "))
73 if 0 <= selection <= len(transtype_list):
74 transtype_value = transtype_list[selection].value
75 break
76
77 # Configure the selected transmission type.
78 transtype.set_int_value(transtype_value)
79
80 # Get and display the IP address of the image data.
81 dest_ip = st_datastream.port.nodemap.get_node(DESTINATION_IP_ADDRESS).get()
82 print("Destination IP Address =", dest_ip.to_string())
83
84 # Start the image acquisition of the host (local machine) side.
85 st_datastream.start_acquisition(number_of_images_to_grab)
86
87 # Start the image acquisition of the camera side if in control mode.
88 if not is_monitor:
89 st_device.acquisition_start()
90
91 # A while loop for acquiring data and checking status
92 while st_datastream.is_grabbing:
93 # Create a localized variable st_buffer using 'with'
94 # Warning: if st_buffer is in a global scope, st_buffer must be
95 # assign to None to allow Garbage Collector release the buffer
96 # properly.
97 with st_datastream.retrieve_buffer() as st_buffer:
98 # Check if the acquired data contains image data.
99 if st_buffer.info.is_image_present:
100 # Create an image object.
101 st_image = st_buffer.get_image()
102 # Display the information of the acquired image data.
103 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
104 st_buffer.info.frame_id,
105 st_image.width, st_image.height,
106 st_image.get_image_data()[0]))
107 else:
108 # If the acquired data contains no image data.
109 print("Image data does not exist.")
110
111 # Stop the image acquisition of the camera side if in control mode.
112 if not is_monitor:
113 st_device.acquisition_stop()
114
115 # Stop the image acquisition of the host side
116 st_datastream.stop_acquisition()
117
118except Exception as exception:
119 print(exception)
grab_callback_class.py¶
1"""
2 This sample shows how to use callback class function to acquire image data
3 from camera.
4 The following points will be demonstrated in this sample code:
5 - Initialize StApi
6 - Connect to camera
7 - Register and use callback class function with StApi
8 - Acquire image data via callback function
9"""
10
11import stapipy as st
12
13
14class CMyCallback:
15 """
16 Class that contains a callback function.
17 """
18
19 def datastream_callback(self, handle=None, context=None):
20 """
21 Callback to handle events from DataStream.
22
23 :param handle: handle that trigger the callback.
24 :param context: user data passed on during callback registration.
25 """
26 st_datastream = handle.module
27 if st_datastream:
28 with st_datastream.retrieve_buffer() as st_buffer:
29 # Check if the acquired data contains image data.
30 if st_buffer.info.is_image_present:
31 # Create an image object.
32 st_image = st_buffer.get_image()
33 # Display the information of the acquired image data.
34 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
35 st_buffer.info.frame_id,
36 st_image.width, st_image.height,
37 st_image.get_image_data()[0]))
38 else:
39 # If the acquired data contains no image data.
40 print("Image data does not exist.")
41
42
43if __name__ == "__main__":
44
45 # Get the callback function:
46 my_callback = CMyCallback()
47 cb_func = my_callback.datastream_callback
48
49 try:
50 # Initialize StApi before using.
51 st.initialize()
52
53 # Create a system object for device scan and connection.
54 st_system = st.create_system()
55
56 # Connect to first detected device.
57 st_device = st_system.create_first_device()
58
59 # Display DisplayName of the device.
60 print('Device=', st_device.info.display_name)
61
62 # Create a datastream object for handling image stream data.
63 st_datastream = st_device.create_datastream()
64
65 # Register callback for datastream
66 callback = st_datastream.register_callback(cb_func)
67
68 # Start the image acquisition of the host (local machine) side.
69 st_datastream.start_acquisition()
70
71 # Start the image acquisition of the camera side.
72 st_device.acquisition_start()
73
74 # Press enter to terminate.
75 input("Press enter to terminate")
76
77 # Stop the image acquisition of the camera side
78 st_device.acquisition_stop()
79
80 # Stop the image acquisition of the host side
81 st_datastream.stop_acquisition()
82
83 except Exception as exception:
84 print(exception)
grab_callback_opencv.py¶
1"""
2 This sample shows how to use OpenCV for format conversion and display.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Register and use callback function with StApi
7 - Acquire image data via callback class function
8 - Copy image data for OpenCV
9 - Convert Bayer image format to RGB using OpenCV
10 - Preview image using OpenCV
11 Note: opencv-python and numpy packages are required:
12 pip install numpy
13 pip install opencv-python
14"""
15
16import cv2
17import threading
18import numpy as np
19import stapipy as st
20
21# Image scale when displaying using OpenCV.
22DISPLAY_RESIZE_FACTOR = 0.3
23
24
25class CMyCallback:
26 """
27 Class that contains a callback function.
28 """
29
30 def __init__(self):
31 self._image = None
32 self._lock = threading.Lock()
33
34 @property
35 def image(self):
36 duplicate = None
37 self._lock.acquire()
38 if self._image is not None:
39 duplicate = self._image.copy()
40 self._lock.release()
41 return duplicate
42
43 def datastream_callback(self, handle=None, context=None):
44 """
45 Callback to handle events from DataStream.
46
47 :param handle: handle that trigger the callback.
48 :param context: user data passed on during callback registration.
49 """
50 st_datastream = handle.module
51 if st_datastream:
52 with st_datastream.retrieve_buffer() as st_buffer:
53 # Check if the acquired data contains image data.
54 if st_buffer.info.is_image_present:
55 # Create an image object.
56 st_image = st_buffer.get_image()
57
58 # Check the pixelformat of the input image.
59 pixel_format = st_image.pixel_format
60 pixel_format_info = st.get_pixel_format_info(pixel_format)
61
62 # Only mono or bayer is processed.
63 if not(pixel_format_info.is_mono or
64 pixel_format_info.is_bayer):
65 return
66
67 # Get raw image data.
68 data = st_image.get_image_data()
69
70 # Perform pixel value scaling if each pixel component is
71 # larger than 8bit. Example: 10bit Bayer/Mono, 12bit, etc.
72 if pixel_format_info.each_component_total_bit_count > 8:
73 nparr = np.frombuffer(data, np.uint16)
74 division = pow(2, pixel_format_info
75 .each_component_valid_bit_count - 8)
76 nparr = (nparr / division).astype('uint8')
77 else:
78 nparr = np.frombuffer(data, np.uint8)
79
80 # Process image for display.
81 nparr = nparr.reshape(st_image.height, st_image.width, 1)
82
83 # Perform color conversion for Bayer.
84 if pixel_format_info.is_bayer:
85 bayer_type = pixel_format_info.get_pixel_color_filter()
86 if bayer_type == st.EStPixelColorFilter.BayerRG:
87 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_RG2RGB)
88 elif bayer_type == st.EStPixelColorFilter.BayerGR:
89 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GR2RGB)
90 elif bayer_type == st.EStPixelColorFilter.BayerGB:
91 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GB2RGB)
92 elif bayer_type == st.EStPixelColorFilter.BayerBG:
93 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_BG2RGB)
94
95 # Resize image and store to self._image.
96 nparr = cv2.resize(nparr, None,
97 fx=DISPLAY_RESIZE_FACTOR,
98 fy=DISPLAY_RESIZE_FACTOR)
99 self._lock.acquire()
100 self._image = nparr
101 self._lock.release()
102
103
104if __name__ == "__main__":
105 my_callback = CMyCallback()
106 cb_func = my_callback.datastream_callback
107 try:
108 # Initialize StApi before using.
109 st.initialize()
110
111 # Create a system object for device scan and connection.
112 st_system = st.create_system()
113
114 # Connect to first detected device.
115 st_device = st_system.create_first_device()
116
117 # Display DisplayName of the device.
118 print('Device=', st_device.info.display_name)
119
120 # Create a datastream object for handling image stream data.
121 st_datastream = st_device.create_datastream()
122
123 # Register callback for datastream
124 callback = st_datastream.register_callback(cb_func)
125
126 # Start the image acquisition of the host (local machine) side.
127 st_datastream.start_acquisition()
128
129 # Start the image acquisition of the camera side.
130 st_device.acquisition_start()
131
132 print("To terminate, focus on the OpenCV window and press any key.")
133 while True:
134 output_image = my_callback.image
135 if output_image is not None:
136 cv2.imshow('image', output_image)
137 key_input = cv2.waitKey(1)
138 if key_input != -1:
139 break
140
141 # Stop the image acquisition of the camera side
142 st_device.acquisition_stop()
143
144 # Stop the image acquisition of the host side
145 st_datastream.stop_acquisition()
146
147 except Exception as exception:
148 print(exception)
grab_callback.py¶
1"""
2 This sample shows how to use callback function to acquire image data from camera.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Register and use callback function with StApi
7 - Acquire image data via callback function
8"""
9
10import stapipy as st
11
12
13def datastream_callback(handle=None, context=None):
14 """
15 Callback to handle events from DataStream.
16
17 :param handle: handle that trigger the callback.
18 :param context: user data passed on during callback registration.
19 """
20 st_datastream = handle.module
21 if st_datastream:
22 with st_datastream.retrieve_buffer() as st_buffer:
23 # Check if the acquired data contains image data.
24 if st_buffer.info.is_image_present:
25 # Create an image object.
26 st_image = st_buffer.get_image()
27 # Display the information of the acquired image data.
28 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
29 st_buffer.info.frame_id,
30 st_image.width, st_image.height,
31 st_image.get_image_data()[0]))
32 else:
33 # If the acquired data contains no image data.
34 print("Image data does not exist.")
35
36
37if __name__ == "__main__":
38 try:
39 # Initialize StApi before using.
40 st.initialize()
41
42 # Create a system object for device scan and connection.
43 st_system = st.create_system()
44
45 # Connect to first detected device.
46 st_device = st_system.create_first_device()
47
48 # Display DisplayName of the device.
49 print('Device=', st_device.info.display_name)
50
51 # Create a datastream object for handling image stream data.
52 st_datastream = st_device.create_datastream()
53
54 # Register callback for datastream
55 callback = st_datastream.register_callback(datastream_callback)
56
57 # Start the image acquisition of the host (local machine) side.
58 st_datastream.start_acquisition()
59
60 # Start the image acquisition of the camera side.
61 st_device.acquisition_start()
62
63 # Press enter to terminate.
64 input("Press enter to terminate")
65
66 # Stop the image acquisition of the camera side
67 st_device.acquisition_stop()
68
69 # Stop the image acquisition of the host side
70 st_datastream.stop_acquisition()
71
72 except Exception as exception:
73 print(exception)
grab_camera_event.py¶
1"""
2 This sample shows how to register an event callback with callback function.
3 Here we register the callback function to "ExposureEnd" event (Defined as
4 TARGET_EVENT_NAME) with a callback function to handle this event.
5 The following points will be demonstrated in this sample code:
6 - Initialize StApi
7 - Connect to camera
8 - Acquire image data with callback function
9 - Enable the event message sending function of camera
10 - Register callback function of indicated event
11"""
12
13import stapipy as st
14
15# Number of images to grab
16number_of_images_to_grab = 100
17
18# Feature names
19EVENT_SELECTOR = "EventSelector"
20EVENT_NOTIFICATION = "EventNotification"
21EVENT_NOTIFICATION_ON = "On"
22TARGET_EVENT_NAME = "ExposureEnd"
23CALLBACK_NODE_NAME = "EventExposureEndTimestamp"
24
25
26def node_callback(node=None, context=None):
27 """
28 Callback to handle events from GenICam node.
29
30 :param node: node that trigger the callback.
31 :param context: user data passed on during callback registration.
32 """
33 try:
34 if node.is_readable:
35 print("{0} = {1}".format(node.name, node.value))
36 else:
37 print("{0} is not readable".format(node.name))
38 except Exception as my_exception:
39 print("node_callback", my_exception)
40
41
42if __name__ == "__main__":
43
44 try:
45 # Initialize StApi before using.
46 st.initialize()
47
48 # Create a system object for device scan and connection.
49 st_system = st.create_system()
50
51 # Connect to first detected device.
52 st_device = st_system.create_first_device()
53
54 # Display DisplayName of the device.
55 print('Device=', st_device.info.display_name)
56
57 # Create a datastream object for handling image stream data.
58 st_datastream = st_device.create_datastream()
59
60 # Get the nodemap object to access current setting of the camera.
61 st_nodemap_remote = st_device.remote_port.nodemap
62
63 # Get node of "EventExposureEndTimestamp" for event registration.
64 st_event_node = st_nodemap_remote.get_node(CALLBACK_NODE_NAME)
65
66 # Register callback for EventExposureEndTimestamp.
67 st_event_node.register_callback(node_callback)
68
69 # Get event selector.
70 st_event_selector = st_nodemap_remote.get_node(EVENT_SELECTOR).get()
71 # As alternative of the above statement, it is also possible to
72 # use the following statement to make the code easier to understand:
73 # st_event_selector = st.PyIEnumeration(
74 # st_nodemap_remote.get_node(EVENT_SELECTOR))
75
76 # Select the target event.
77 # Note that depending on your use case, there are three ways to set
78 # the enumeration value:
79 # 1) Assign the integer value of the entry with set_int_value or .value
80 # st_event_selector_entry = st_event_selector[TARGET_EVENT_NAME].get()
81 # st_event_selector.set_int_value(st_event_selector_entry.numeric_value)
82 # or: st_event_selector.value = st_event_selector_entry.numeric_value
83 # 2) Assign the symbolic value of the entry with set_symbolic_value
84 # st_event_selector.set_symbolic_value(TARGET_EVENT_NAME)
85 # 3) Assign the entry (PyIEnumEntry) with set_entry_value
86 # st_event_selector_entry = st_event_selector[TARGET_EVENT_NAME].get()
87 # st_event_selector.set_entry_value(st_event_selector_entry)
88 # Here we used 2) because we already know and sure the symbolic name.
89 st_event_selector.set_symbolic_value(TARGET_EVENT_NAME)
90
91 # Enable event notification.
92 st_event_notification = st.PyIEnumeration(st_nodemap_remote
93 .get_node(EVENT_NOTIFICATION))
94 st_event_notification.set_symbolic_value(EVENT_NOTIFICATION_ON)
95
96 # Start event handling thread
97 st_device.start_event_acquisition()
98
99 # Start the image acquisition of the host (local machine) side.
100 st_datastream.start_acquisition(number_of_images_to_grab)
101
102 # Start the image acquisition of the camera side.
103 st_device.acquisition_start()
104
105 # A while loop for acquiring data and checking status
106 while st_datastream.is_grabbing:
107 # Create a localized variable st_buffer using 'with'
108 with st_datastream.retrieve_buffer() as st_buffer:
109 # Check if the acquired data contains image data.
110 if st_buffer.info.is_image_present:
111 # Create an image object.
112 st_image = st_buffer.get_image()
113 # Display the information of the acquired image data.
114 print("BlockID={0} Size={1} x {2} First Byte={3} "
115 "Timestamp={4}".format(
116 st_buffer.info.frame_id,
117 st_image.width, st_image.height,
118 st_image.get_image_data()[0],
119 st_buffer.info.timestamp))
120 else:
121 # If the acquired data contains no image data.
122 print("Image data does not exist.")
123
124 # Stop the image acquisition of the camera side
125 st_device.acquisition_stop()
126
127 # Stop the image acquisition of the host side
128 st_datastream.stop_acquisition()
129
130 # Stop event acquisition thread
131 st_device.stop_event_acquisition()
132
133 except Exception as exception:
134 print(exception)
grab_chunk_image.py¶
1"""
2This sample shows the basic operation of using StApi and display chunk data
3of the received image.
4The following points will be demonstrated in this sample code:
5 - Initialize StApi
6 - Connect to camera
7 - Acquire and display chunk data.
8"""
9
10import stapipy as st
11
12# Number of images to grab
13number_of_images_to_grab = 100
14
15# Flag to indicate if all chunks are enabled
16enable_all_chunks = True
17
18# Feature names
19CHUNK_MODE_ACTIVE = "ChunkModeActive"
20CHUNK_SELECTOR = "ChunkSelector"
21CHUNK_ENABLE = "ChunkEnable"
22
23# If enable_all_chunks is False, enable only the following chunk:
24TARGET_CHUNK_NAME = "ExposureTime"
25
26
27def display_node_values(node_list):
28 """
29 Display node values.
30
31 :param node_list: list of nodes to display.
32 """
33 for node in node_list:
34 node_value = str(node.value) \
35 if node.is_readable else "not readable"
36 print("{0}: {1}".format(node.name, node_value))
37
38
39if __name__ == "__main__":
40
41 try:
42 # Initialize StApi before using.
43 st.initialize()
44
45 # Create a system object for device scan and connection.
46 st_system = st.create_system()
47
48 # Connect to first detected device.
49 st_device = st_system.create_first_device()
50
51 # Display DisplayName of the device.
52 print('Device=', st_device.info.display_name)
53
54 # Create a datastream object for handling image stream data.
55 st_datastream = st_device.create_datastream()
56
57 # Get the nodemap object to access current setting of the camera.
58 st_nodemap_remote = st_device.remote_port.nodemap
59
60 # Get related node to access and activate chunk
61 st_chunk_mode_active = st_nodemap_remote.get_node(CHUNK_MODE_ACTIVE)
62 st_chunk_mode_active.value = True
63
64 # Get the PyIEnumeration of the chunk selector.
65 # Here, .get() is used to shorten the code. To make the code more
66 # understandable, casting can be used as well:
67 # st_chunk_selector = \
68 # st.PyIEnumeration(st_nodemap_remote.get_node(CHUNK_SELECTOR))
69 st_chunk_selector = st_nodemap_remote.get_node(CHUNK_SELECTOR).get()
70
71 # Get chunk enable.
72 st_chunk_enable = st_nodemap_remote.get_node(CHUNK_ENABLE)
73
74 st_chunk_value_list = []
75 if enable_all_chunks:
76 chunk_lists = st_chunk_selector.entries
77 for chunk_item in chunk_lists:
78 # Skip unavailable chunk.
79 if not chunk_item.is_available:
80 continue
81 # Set selector to the chunk item and enable it.
82 st_chunk_selector.set_int_value(chunk_item.value)
83 if st_chunk_enable.is_writable:
84 st_chunk_enable.value = True
85
86 # Get the node for the value of the Chunk and put to list.
87 chunk_value = st_nodemap_remote.get_node(
88 "Chunk" + st.PyIEnumEntry(chunk_item).symbolic_value)
89 if chunk_value:
90 st_chunk_value_list.append(chunk_value)
91 chunk_value = None
92 else:
93 # Get the entry for the specified chunk.
94 chunk_item = st_chunk_selector[TARGET_CHUNK_NAME]
95 if chunk_item.is_available:
96 # Set the selector to the chunk and enable it.
97 st_chunk_selector.set_int_value(chunk_item.value)
98 if st_chunk_enable.is_writable:
99 st_chunk_enable.value = True
100 # Get the node for the value of the Chunk and put to list.
101 chunk_value = st_nodemap_remote.get_node(TARGET_CHUNK_NAME)
102 if chunk_value:
103 st_chunk_value_list.append(chunk_value)
104 chunk_value = None
105
106 # Start the image acquisition of the host (local machine) side.
107 st_datastream.start_acquisition(number_of_images_to_grab)
108
109 # Start the image acquisition of the camera side.
110 st_device.acquisition_start()
111
112 # A while loop for acquiring data and checking status
113 while st_datastream.is_grabbing:
114 # Create a localized variable st_buffer using 'with'
115 with st_datastream.retrieve_buffer() as st_buffer:
116 # Check if the acquired data contains image data.
117 if st_buffer.info.is_image_present:
118 # Create an image object.
119 st_image = st_buffer.get_image()
120 # Display the information of the acquired image data.
121 print("BlockID={0} Size={1} x {2} First Byte={3} "
122 "Timestamp={4}".format(
123 st_buffer.info.frame_id,
124 st_image.width, st_image.height,
125 st_image.get_image_data()[0],
126 st_buffer.info.timestamp))
127 display_node_values(st_chunk_value_list)
128 else:
129 # If the acquired data contains no image data.
130 print("Image data does not exist.")
131
132 # Stop the image acquisition of the camera side
133 st_device.acquisition_stop()
134
135 # Stop the image acquisition of the host side
136 st_datastream.stop_acquisition()
137
138 # Stop event acquisition thread
139 st_device.stop_event_acquisition()
140
141 except Exception as exception:
142 print(exception)
grab_ip_opencv.py¶
1"""
2 This sample shows how to use StApi with OpenCV for format conversion and display.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Acquire image data
7 - Copy image data for OpenCV
8 - Convert Bayer image format to BGR8 using StApi IP
9 - Preview image using OpenCV
10 Note: opencv-python and numpy packages are required:
11 pip install numpy
12 pip install opencv-python
13"""
14
15import cv2
16import numpy as np
17import stapipy as st
18
19# Number of images to grab
20number_of_images_to_grab = 1000
21
22# Image scale when displaying using OpenCV.
23DISPLAY_RESIZE_FACTOR = 0.3
24
25try:
26 # Initialize StApi before using.
27 st.initialize()
28
29 # Initialize converter
30 st_converter = st.create_converter(st.EStConverterType.PixelFormat)
31 st_converter.destination_pixel_format = \
32 st.EStPixelFormatNamingConvention.BGR8
33
34 # Create a system object for device scan and connection.
35 st_system = st.create_system()
36
37 # Connect to first detected device.
38 st_device = st_system.create_first_device()
39
40 # Display DisplayName of the device.
41 print('Device=', st_device.info.display_name)
42
43 # Create a datastream object for handling image stream data.
44 st_datastream = st_device.create_datastream()
45
46 # Start the image acquisition of the host (local machine) side.
47 st_datastream.start_acquisition(number_of_images_to_grab)
48
49 # Start the image acquisition of the camera side.
50 st_device.acquisition_start()
51
52 # A while loop for acquiring data and checking status
53 while st_datastream.is_grabbing:
54 # Create a localized variable st_buffer using 'with'
55 # Warning: if st_buffer is in a global scope, st_buffer must be
56 # assign to None to allow Garbage Collector release the buffer
57 # properly.
58 with st_datastream.retrieve_buffer() as st_buffer:
59 # Check if the acquired data contains image data.
60 if st_buffer.info.is_image_present:
61 # Create an image object.
62 st_image = st_buffer.get_image()
63
64 # Display the information of the acquired image data.
65 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
66 st_buffer.info.frame_id,
67 st_image.width, st_image.height,
68 st_image.get_image_data()[0]))
69
70 # Convert image and get the NumPy array.
71 st_image = st_converter.convert(st_image)
72 data = st_image.get_image_data()
73 nparr = np.frombuffer(data, np.uint8)
74 nparr = nparr.reshape(st_image.height, st_image.width, 3)
75
76 # Resize image.and display.
77 nparr = cv2.resize(nparr, None,
78 fx=DISPLAY_RESIZE_FACTOR,
79 fy=DISPLAY_RESIZE_FACTOR)
80 cv2.imshow('image', nparr)
81 cv2.waitKey(1)
82 else:
83 # If the acquired data contains no image data.
84 print("Image data does not exist.")
85
86 # Stop the image acquisition of the camera side
87 st_device.acquisition_stop()
88
89 # Stop the image acquisition of the host side
90 st_datastream.stop_acquisition()
91
92except Exception as exception:
93 print(exception)
grab_opencv.py¶
1"""
2 This sample shows how to use StApi with OpenCV for format conversion and display.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Acquire image data
7 - Copy image data for OpenCV
8 - Convert Bayer image format to RGB using OpenCV
9 - Preview image using OpenCV
10 Note: opencv-python and numpy packages are required:
11 pip install numpy
12 pip install opencv-python
13"""
14
15import cv2
16import numpy as np
17import stapipy as st
18
19# Number of images to grab
20number_of_images_to_grab = 1000
21
22# Image scale when displaying using OpenCV.
23DISPLAY_RESIZE_FACTOR = 0.3
24
25try:
26 # Initialize StApi before using.
27 st.initialize()
28
29 # Create a system object for device scan and connection.
30 st_system = st.create_system()
31
32 # Connect to first detected device.
33 st_device = st_system.create_first_device()
34
35 # Display DisplayName of the device.
36 print('Device=', st_device.info.display_name)
37
38 # Create a datastream object for handling image stream data.
39 st_datastream = st_device.create_datastream()
40
41 # Start the image acquisition of the host (local machine) side.
42 st_datastream.start_acquisition(number_of_images_to_grab)
43
44 # Start the image acquisition of the camera side.
45 st_device.acquisition_start()
46
47 # A while loop for acquiring data and checking status
48 while st_datastream.is_grabbing:
49 # Create a localized variable st_buffer using 'with'
50 # Warning: if st_buffer is in a global scope, st_buffer must be
51 # assign to None to allow Garbage Collector release the buffer
52 # properly.
53 with st_datastream.retrieve_buffer() as st_buffer:
54 # Check if the acquired data contains image data.
55 if st_buffer.info.is_image_present:
56 # Create an image object.
57 st_image = st_buffer.get_image()
58
59 # Display the information of the acquired image data.
60 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
61 st_buffer.info.frame_id,
62 st_image.width, st_image.height,
63 st_image.get_image_data()[0]))
64
65 # Check the pixelformat of the input image.
66 pixel_format = st_image.pixel_format
67 pixel_format_info = st.get_pixel_format_info(pixel_format)
68
69 # Only mono or bayer is processed.
70 if not(pixel_format_info.is_mono or pixel_format_info.is_bayer):
71 continue
72
73 # Get raw image data.
74 data = st_image.get_image_data()
75
76 # Perform pixel value scaling if each pixel component is
77 # larger than 8bit. Example: 10bit Bayer/Mono, 12bit, etc.
78 if pixel_format_info.each_component_total_bit_count > 8:
79 nparr = np.frombuffer(data, np.uint16)
80 division = pow(2, pixel_format_info
81 .each_component_valid_bit_count - 8)
82 nparr = (nparr / division).astype('uint8')
83 else:
84 nparr = np.frombuffer(data, np.uint8)
85
86 # Process image for display.
87 nparr = nparr.reshape(st_image.height, st_image.width, 1)
88
89 # Perform color conversion for Bayer.
90 if pixel_format_info.is_bayer:
91 bayer_type = pixel_format_info.get_pixel_color_filter()
92 if bayer_type == st.EStPixelColorFilter.BayerRG:
93 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_RG2RGB)
94 elif bayer_type == st.EStPixelColorFilter.BayerGR:
95 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GR2RGB)
96 elif bayer_type == st.EStPixelColorFilter.BayerGB:
97 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GB2RGB)
98 elif bayer_type == st.EStPixelColorFilter.BayerBG:
99 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_BG2RGB)
100
101 # Resize image.and display.
102 nparr = cv2.resize(nparr, None,
103 fx=DISPLAY_RESIZE_FACTOR,
104 fy=DISPLAY_RESIZE_FACTOR)
105 cv2.imshow('image', nparr)
106 cv2.waitKey(1)
107 else:
108 # If the acquired data contains no image data.
109 print("Image data does not exist.")
110
111 # Stop the image acquisition of the camera side
112 st_device.acquisition_stop()
113
114 # Stop the image acquisition of the host side
115 st_datastream.stop_acquisition()
116
117except Exception as exception:
118 print(exception)
grab.py¶
1"""
2 This sample shows the basic operation of using StApi for connecting,
3 controlling, and acquiring image from camera.
4 The following points will be demonstrated in this sample code:
5 - Initialize StApi
6 - Connect to camera
7 - Acquire image data (with waiting in main thread)
8"""
9
10import stapipy as st
11
12# Number of images to grab
13number_of_images_to_grab = 100
14
15try:
16 # Initialize StApi before using.
17 st.initialize()
18
19 # Create a system object for device scan and connection.
20 st_system = st.create_system()
21
22 # Connect to first detected device.
23 st_device = st_system.create_first_device()
24
25 # Display DisplayName of the device.
26 print('Device=', st_device.info.display_name)
27
28 # Create a datastream object for handling image stream data.
29 st_datastream = st_device.create_datastream()
30
31 # Start the image acquisition of the host (local machine) side.
32 st_datastream.start_acquisition(number_of_images_to_grab)
33
34 # Start the image acquisition of the camera side.
35 st_device.acquisition_start()
36
37 # A while loop for acquiring data and checking status
38 while st_datastream.is_grabbing:
39 # Create a localized variable st_buffer using 'with'
40 # Warning: if st_buffer is in a global scope, st_buffer must be
41 # assign to None to allow Garbage Collector release the buffer
42 # properly.
43 with st_datastream.retrieve_buffer() as st_buffer:
44 # Check if the acquired data contains image data.
45 if st_buffer.info.is_image_present:
46 # Create an image object.
47 st_image = st_buffer.get_image()
48 # Display the information of the acquired image data.
49 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
50 st_buffer.info.frame_id,
51 st_image.width, st_image.height,
52 st_image.get_image_data()[0]))
53 else:
54 # If the acquired data contains no image data.
55 print("Image data does not exist.")
56
57 # Stop the image acquisition of the camera side
58 st_device.acquisition_stop()
59
60 # Stop the image acquisition of the host side
61 st_datastream.stop_acquisition()
62
63except Exception as exception:
64 print(exception)
host_side_roi_opencv.py¶
1"""
2 This sample shows how to divide image data into multiple ROI images in local
3 side and display them using OpenCV.
4 The following points will be demonstrated in this sample code:
5 - Initialize StApi
6 - Connect to camera
7 - Acquire image
8 - Process image ROI in host side (local computer)
9 - Copy image data for OpenCV
10 - Convert Bayer image format to RGB using OpenCV
11 - Preview image using OpenCV
12 Note: opencv-python and numpy packages are required:
13 pip install numpy
14 pip install opencv-python
15"""
16
17import cv2
18import numpy as np
19import stapipy as st
20
21# Number of images to grab
22number_of_images_to_grab = 1000
23
24# Image scale when displaying using OpenCV.
25DISPLAY_RESIZE_FACTOR = 0.5
26
27# Regions of each direction.
28HORIZONTAL_ROI_COUNT = 4
29VERTICAL_ROI_COUNT = 2
30
31
32def display_with_opencv(window_title, img, pixel_format_info):
33 """
34 Function to convert PyIStImage pixel format and display it using OpenCV.
35
36 :param img: Image to process
37 :param pixel_format_info: Pixel format info.
38 """
39 # Get raw image data.
40 data = img.get_image_data()
41
42 # Perform pixel value scaling if each pixel component is
43 # larger than 8bit. Example: 10bit Bayer/Mono, 12bit, etc.
44 if pixel_format_info.each_component_total_bit_count > 8:
45 nparr = np.frombuffer(data, np.uint16)
46 division = pow(2, pixel_format_info
47 .each_component_valid_bit_count - 8)
48 nparr = (nparr / division).astype('uint8')
49 else:
50 nparr = np.frombuffer(data, np.uint8)
51
52 # Process image for display.
53 nparr = nparr.reshape(img.height, img.width, 1)
54
55 # Perform color conversion for Bayer.
56 if pixel_format_info.is_bayer:
57 bayer_type = pixel_format_info.get_pixel_color_filter()
58 if bayer_type == st.EStPixelColorFilter.BayerRG:
59 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_RG2RGB)
60 elif bayer_type == st.EStPixelColorFilter.BayerGR:
61 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GR2RGB)
62 elif bayer_type == st.EStPixelColorFilter.BayerGB:
63 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_GB2RGB)
64 elif bayer_type == st.EStPixelColorFilter.BayerBG:
65 nparr = cv2.cvtColor(nparr, cv2.COLOR_BAYER_BG2RGB)
66
67 # Resize image and display.
68 nparr = cv2.resize(nparr, None,
69 fx=DISPLAY_RESIZE_FACTOR,
70 fy=DISPLAY_RESIZE_FACTOR)
71 cv2.imshow(window_title, nparr)
72
73
74if __name__ == "__main__":
75 try:
76 # Initialize StApi before using.
77 st.initialize()
78
79 # Create a system object for device scan and connection.
80 st_system = st.create_system()
81
82 # Connect to first detected device.
83 st_device = st_system.create_first_device()
84
85 # Display DisplayName of the device.
86 print('Device=', st_device.info.display_name)
87
88 # Create a datastream object for handling image stream data.
89 st_datastream = st_device.create_datastream()
90
91 # Get the device nodemap to access the device settings.
92 remote_nodemap = st_device.remote_port.nodemap
93
94 # Get current setting of the image size.
95 image_size = [remote_nodemap.get_node("Width").value,
96 remote_nodemap.get_node("Height").value]
97
98 # Get current pixel format information.
99 pixel_format = remote_nodemap.get_node("PixelFormat").value
100 pixel_format_info = st.get_pixel_format_info(pixel_format)
101
102 # Get the minimum setting unit of both sides (X and Y).
103 pixel_increment = [pixel_format_info.pixel_increment_x,
104 pixel_format_info.pixel_increment_y]
105
106 # Calculate the size of the ROI.
107 roi_window_count = [HORIZONTAL_ROI_COUNT, VERTICAL_ROI_COUNT]
108 roi_image_size = []
109 for index in range(2):
110 size = image_size[index] // roi_window_count[index]
111 size = size - (size % pixel_increment[index])
112 roi_image_size.append(size)
113
114 # Prepare display window
115 for pos_y in range(roi_window_count[1]):
116 for pos_x in range(roi_window_count[0]):
117 window_title = "image_{0}{1}".format(pos_y, pos_x)
118 cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)
119 cv2.moveWindow(window_title,
120 int(pos_x * roi_image_size[0] * DISPLAY_RESIZE_FACTOR),
121 int(pos_y * roi_image_size[1] * DISPLAY_RESIZE_FACTOR))
122 cv2.resizeWindow(window_title,
123 int(roi_image_size[0] * DISPLAY_RESIZE_FACTOR),
124 int(roi_image_size[1] * DISPLAY_RESIZE_FACTOR))
125
126 # Start the image acquisition of the host (local machine) side.
127 st_datastream.start_acquisition(number_of_images_to_grab)
128
129 # Start the image acquisition of the camera side.
130 st_device.acquisition_start()
131
132 # A while loop for acquiring data and checking status
133 while st_datastream.is_grabbing:
134 # Create a localized variable st_buffer using 'with'
135 # Warning: if st_buffer is in a global scope, st_buffer must be
136 # assign to None to allow Garbage Collector release the buffer
137 # properly.
138 with st_datastream.retrieve_buffer() as st_buffer:
139 # Check if the acquired data contains image data.
140 if not st_buffer.info.is_image_present:
141 print("Image data does not exist.")
142 continue
143
144 # Create an image object.
145 st_image = st_buffer.get_image()
146
147 # Display the information of the acquired image data.
148 print("BlockID={0} Size={1} x {2} {3}[fps]".format(
149 st_buffer.info.frame_id,
150 st_image.width, st_image.height,
151 st_datastream.current_fps))
152
153 # Only mono or bayer is processed.
154 if not(pixel_format_info.is_mono or pixel_format_info.is_bayer):
155 continue
156
157 # Display image.
158 display_with_opencv("image", st_image, pixel_format_info)
159
160 # Process and display each ROI image.
161 for pos_y in range(roi_window_count[1]):
162 for pos_x in range(roi_window_count[0]):
163 roi_image = st_image.get_roi_image(
164 pos_x * roi_image_size[0],
165 pos_y * roi_image_size[1],
166 roi_image_size[0],
167 roi_image_size[1])
168 window_title = "image_{0}{1}".format(pos_y, pos_x)
169 display_with_opencv(window_title,
170 roi_image, pixel_format_info)
171 cv2.waitKey(1)
172
173 # Stop the image acquisition of the camera side
174 st_device.acquisition_stop()
175
176 # Stop the image acquisition of the host side
177 st_datastream.stop_acquisition()
178
179 except Exception as exception:
180 print(exception)
multiple_cameras.py¶
1"""
2 This sample shows how to conect and get images from all available cameras.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to all available cameras
6 - Acquire image from the list of camera
7 You can see how to handle multiple cameras/stream objects in this sample.
8"""
9
10import stapipy as st
11
12# Number of images to grab
13number_of_images_to_grab = 10
14
15try:
16 # Initialize StApi before using.
17 st.initialize()
18
19 # Create a system object for device scan and connection.
20 st_system = st.create_system()
21
22 # Create a camera device list object to store all the cameras.
23 device_list = st.PyStDeviceList()
24
25 # Create a DataStream list object to store all the data stream object related to the cameras.
26 stream_list = st.PyStDataStreamList()
27
28 while True:
29 try:
30 st_device = st_system.create_first_device()
31 except:
32 if not device_list:
33 raise
34 break
35 # Add the camera into device object list for later usage.
36 device_list.register(st_device)
37
38 # Display the DisplayName of the device.
39 print("Device {0} = {1}".format(len(device_list), st_device.info.display_name))
40
41 # Create a DataStream object then add into DataStream list for later usage.
42 stream_list.register(st_device.create_datastream(0))
43
44 # Start the image acquisition of the host side.
45 stream_list.start_acquisition(number_of_images_to_grab)
46
47 # Start the image acquisition of the camera side.
48 device_list.acquisition_start()
49
50 # Loop for aquiring data and checking status
51 while stream_list.is_grabbing_any:
52 # Retrieve data buffer of image data from any camera with a timeout of 5000ms.
53 with stream_list.retrieve_buffer(5000) as st_buffer:
54 # Check if the acquired data contains image data.
55 if st_buffer.info.is_image_present:
56 print("{0} : BlockID={1} {2:.2f}FPS"\
57 .format(st_buffer.datastream.device.info.display_name,
58 st_buffer.info.frame_id,
59 st_buffer.datastream.current_fps))
60 else:
61 print("Image data does not exist.")
62
63 # Stop the image acquisition of the camera side.
64 device_list.acquisition_stop()
65
66 # Stop the image acquisition of the host side.
67 stream_list.stop_acquisition()
68
69except Exception as exception:
70 print(exception)
71finally:
72 input("Press enter to terminate")
multiple_systems.py¶
1"""
2 This sample shows how to use multiple GenTL modules (cti files) for acquiring image data.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to the first detected camera of all system
6 - Acquire image data (with waiting in main thread)
7 - Use multiple GenTL module.
8"""
9
10import stapipy as st
11
12# Number of images to grab
13number_of_images_to_grab = 100
14
15try:
16 # Initialize StApi before using.
17 st.initialize()
18
19 # Create a system object list for store system object.
20 # Then we try to create objects of all available systems.
21 system_list = st.PyStSystemList()
22
23 for system_vendor in st.EStSystemVendor:
24 if system_vendor == st.EStSystemVendor.Count:
25 continue
26 try:
27 # For each available system,
28 # try to create object for it then register it into system list for further usage.
29 system_list.register(st.create_system(system_vendor, st.EStInterfaceType.All))
30 except st.PyStError as st_error:
31 print("An exception occurred.", st_error)
32
33 # Create a device object of the first detected device to connect.
34 st_device = system_list.create_first_device(st.ETLDeviceAccessFlags.AccessExclusive)
35
36 # Display DisplayName of the device.
37 print('Device=', st_device.info.display_name)
38
39 # Create a datastream object for handling image stream data.
40 st_datastream = st_device.create_datastream(0)
41
42 # Start the image acquisition of the host side.
43 st_datastream.start_acquisition(number_of_images_to_grab)
44
45 # Start the image acquisition of the camera side.
46 st_device.acquisition_start()
47
48 # A while loop for acquiring data and checking status
49 while st_datastream.is_grabbing:
50 # Retrieve the buffer of image data with a timeout of 5000ms.
51 with st_datastream.retrieve_buffer(5000) as st_buffer:
52 # Check if the acquired data contains image data.
53 if st_buffer.info.is_image_present:
54 # Create an image object.
55 st_image = st_buffer.get_image()
56 # Display the information of the acquired image data.
57 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
58 st_buffer.info.frame_id,
59 st_image.width, st_image.height,
60 st_image.get_image_data()[0]))
61 else:
62 # If the acquired data contains no image data.
63 print("Image data does not exist.")
64
65 # Stop the image acquisition of the camera side
66 st_device.acquisition_stop()
67
68 # Stop the image acquisition of the host side
69 st_datastream.stop_acquisition()
70
71except Exception as exception:
72 print(exception)
73finally:
74 input("Press enter to terminate")
save_and_load_image.py¶
1"""
2 This sample shows how to save a captured image into RAW file of StApi.
3 After saving to RAW file, this sample will load the file,
4 convert it to BGR8 image, and save as BMP/TIF/PNG/JPG files.
5 The following points will be demonstrated in this sample code:
6 - Initialize StApi
7 - Connect to camera
8 - Acquire 1 image data
9 - Save image to / Load image from file from temp folder
10 - Apply Pixel format conversion
11"""
12
13import os
14import tempfile
15
16import stapipy as st
17
18# Number of images to grab
19number_of_images_to_grab = 1
20
21try:
22 # Initialize StApi before using.
23 st.initialize()
24
25 # Create a system object for device scan and connection.
26 st_system = st.create_system()
27
28 # Connect to first detected device.
29 st_device = st_system.create_first_device()
30
31 # Display DisplayName of the device.
32 print('Device=', st_device.info.display_name)
33
34 # File for image file
35 filename_prefix = st_device.info.display_name
36 file_location = os.path.join(tempfile.gettempdir(),
37 filename_prefix + ".StApiRaw")
38
39 # Create a datastream object for handling image stream data.
40 st_datastream = st_device.create_datastream()
41
42 # Start the image acquisition of the host (local machine) side.
43 st_datastream.start_acquisition(number_of_images_to_grab)
44
45 # Start the image acquisition of the camera side.
46 st_device.acquisition_start()
47
48 is_image_saved = False
49 with st_datastream.retrieve_buffer() as st_buffer:
50 # Check if the acquired data contains image data.
51 if st_buffer.info.is_image_present:
52 # Create an image object.
53 st_image = st_buffer.get_image()
54 # Display the information of the acquired image data.
55 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
56 st_buffer.info.frame_id,
57 st_image.width, st_image.height,
58 st_image.get_image_data()[0]))
59
60 # Create a still image file handling class object (filer)
61 st_stillimage_filer = st.create_filer(st.EStFilerType.StillImage)
62
63 # Save the image file as StApiRaw file format.
64 print("Saving {0} ... ".format(file_location), end="")
65 st_stillimage_filer.save(st_image,
66 st.EStStillImageFileFormat.StApiRaw, file_location)
67 print("done.")
68 is_image_saved = True
69 else:
70 # If the acquired data contains no image data.
71 print("Image data does not exist.")
72
73 # Stop the image acquisition of the camera side
74 st_device.acquisition_stop()
75
76 # Stop the image acquisition of the host side
77 st_datastream.stop_acquisition()
78
79 # Load StapiRaw and process the image.
80 if is_image_saved:
81 # Load image
82 st_stillimage_filer = st.create_filer(st.EStFilerType.StillImage)
83 print("Loading {0} ... ".format(file_location), end="")
84 st_image = st_stillimage_filer.load(file_location)
85 print("done.")
86
87 # Convert image to BGR8 format.
88 st_converter = st.create_converter(st.EStConverterType.PixelFormat)
89 st_converter.destination_pixel_format = \
90 st.EStPixelFormatNamingConvention.BGR8
91 st_image = st_converter.convert(st_image)
92
93 # Save as bitmap, tiff, png, jpg, csv
94 save_list = {st.EStStillImageFileFormat.Bitmap: '.bmp',
95 st.EStStillImageFileFormat.TIFF: '.tif',
96 st.EStStillImageFileFormat.PNG: '.png',
97 st.EStStillImageFileFormat.JPEG: '.jpg',
98 st.EStStillImageFileFormat.CSV: '.csv',
99 }
100 for file_format, file_ext in save_list.items():
101 file_location = os.path.join(tempfile.gettempdir(),
102 filename_prefix + file_ext)
103 print("Saving {0} ... ".format(file_location), end="")
104 st_stillimage_filer.save(st_image, file_format, file_location)
105 print("done.")
106
107except Exception as exception:
108 print(exception)
save_load_features.py¶
1"""
2 This sample shows how to save/load camera setting with using featureBag.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Save/load camera setting to/from file
7 - Apply the loaded setting to camera
8"""
9
10import os
11import tempfile
12
13import stapipy as st
14
15try:
16 # Initialize StApi before using.
17 st.initialize()
18
19 # Create a system object for device scan and connection.
20 st_system = st.create_system()
21
22 # Connect to first detected device.
23 st_device = st_system.create_first_device()
24
25 # Display DisplayName of the device.
26 print('Device=', st_device.info.display_name)
27
28 filename = os.path.join(tempfile.gettempdir(), "features.cfg")
29
30 # Get the remote nodemap.
31 nodemap = st_device.remote_port.nodemap
32
33 # Create feature bag object.
34 featurebag = st.create_featurebag()
35 featurebag.store_nodemap_to_bag(nodemap)
36
37 # Display all settings.
38 features = featurebag.save_to_string()
39 print(features)
40
41 # Save settings in the feature bag to file.
42 print("Saving", filename)
43 featurebag.save_to_file(filename)
44 print("Saving done")
45
46 # Create another feature bag for loading setting from file.
47 featurebag2 = st.create_featurebag()
48
49 # Load the setting from file created above to the feature bag
50 featurebag2.store_file_to_bag(filename)
51
52 # Load the setting from the feature bag to camera
53 print("Loading to camera..")
54 featurebag2.load(nodemap, True)
55 print("Loading to camera done")
56
57except Exception as exception:
58 print(exception)
save_video.py¶
1"""
2 This sample shows how to save acquired image as AVI video file.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Create AVI video file
7"""
8
9import os
10import tempfile
11
12import stapipy as st
13import time
14
15# Number of images to grab
16number_of_images_to_grab = 10
17
18# Maximum number of frames in one video file
19maximum_frame_count_per_file = 5
20
21# Number of video files
22video_files_count = 3
23
24
25def videofiler_callback(handle=None, context=None):
26 """
27 Callback to handle events from Video Filer.
28
29 :param handle: handle that trigger the callback.
30 :param context: user data passed on during callback registration.
31 """
32 callback_type = handle.callback_type
33 videofiler = handle.module
34 if callback_type == st.EStCallbackType.StApiIPVideoFilerOpen:
35 print("Open:", handle.data['filename'])
36 elif callback_type == st.EStCallbackType.StApiIPVideoFilerClose:
37 print("Close:", handle.data['filename'])
38 elif callback_type == st.EStCallbackType.StApiIPVideoFilerError:
39 print("Error:", handle.error[1])
40 context['error'] = True
41
42
43if __name__ == "__main__":
44 try:
45 # Initialize StApi before using.
46 st.initialize()
47
48 # Create a system object for device scan and connection.
49 st_system = st.create_system()
50
51 # Connect to first detected device.
52 st_device = st_system.create_first_device()
53
54 # Display DisplayName of the device.
55 print('Device=', st_device.info.display_name)
56
57 # Get the acquisition fps of the camera.
58 fps = 60.0
59 acquisition_frame_rate = st_device.remote_port.nodemap.get_node(
60 "AcquisitionFrameRate")
61 if acquisition_frame_rate:
62 fps = acquisition_frame_rate.value
63
64 # Create PyStVideoFiler
65 st_videofiler = st.create_filer(st.EStFilerType.Video)
66
67 # Register a callback function.
68 callback_info = {'error': False}
69 videofiler_cb = st_videofiler.register_callback(videofiler_callback,
70 callback_info)
71
72 # Configure the video file settings.
73 st_videofiler.maximum_frame_count_per_file = \
74 maximum_frame_count_per_file
75 st_videofiler.video_file_format = st.EStVideoFileFormat.AVI2
76 st_videofiler.video_file_compression = \
77 st.EStVideoFileCompression.MotionJPEG
78 st_videofiler.fps = fps
79
80 # Register video files
81 filename_prefix = st_device.info.display_name
82 for file_index in range(video_files_count):
83 file_location = os.path.join(tempfile.gettempdir(),
84 filename_prefix + str(file_index) + ".avi")
85 st_videofiler.register_filename(file_location)
86
87 # Create a datastream object for handling image stream data.
88 st_datastream = st_device.create_datastream()
89
90 # Start the image acquisition of the host (local machine) side.
91 st_datastream.start_acquisition(number_of_images_to_grab)
92
93 # Start the image acquisition of the camera side.
94 st_device.acquisition_start()
95
96 first_frame = True
97 first_timestamp = 0
98 while st_datastream.is_grabbing:
99
100 if callback_info['error']:
101 break
102 with st_datastream.retrieve_buffer() as st_buffer:
103 # Check if the acquired data contains image data.
104 if st_buffer.info.is_image_present:
105 # Create an image object.
106 st_image = st_buffer.get_image()
107 # Display the information of the acquired image data.
108 print("BlockID={0} Size={1} x {2} {3:.2f} fps".format(
109 st_buffer.info.frame_id,
110 st_image.width, st_image.height,
111 st_datastream.current_fps))
112
113 # Calculate frame number in case of frame drop.
114 frame_no = 0
115 current_timestamp = st_buffer.info.timestamp
116 if first_frame:
117 first_frame = False
118 first_timestamp = current_timestamp
119 else:
120 delta = current_timestamp - first_timestamp
121 tmp = delta * fps / 1000000000.0
122 frame_no = int(tmp + 0.5)
123
124 # Add the image data to video file.
125 st_videofiler.register_image(st_image, frame_no)
126 else:
127 # If the acquired data contains no image data.
128 print("Image data does not exist.")
129
130 # Stop the image acquisition of the camera side
131 st_device.acquisition_stop()
132
133 # Stop the image acquisition of the host side
134 st_datastream.stop_acquisition()
135
136 except Exception as exception:
137 print(exception)
singleconverter_opencv.py¶
1"""
2This sample shows how to process received image with converter.
3The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Acquire image data
7 - Apply image processing with StApi converter (reverse Y and pixel format BGR8)
8 - Copy image data for OpenCV
9 - Preview image using OpenCV
10 Note: opencv-python and numpy packages are required:
11 pip install numpy
12 pip install opencv-python
13"""
14
15import cv2
16import numpy as np
17import stapipy as st
18
19# Number of images to grab
20number_of_images_to_grab = 100
21
22# Image scale when displaying using OpenCV.
23DISPLAY_RESIZE_FACTOR = 0.3
24
25try:
26 # Initialize StApi before using.
27 st.initialize()
28
29 # Create a system object for device scan and connection.
30 st_system = st.create_system()
31
32 # Connect to first detected device.
33 st_device = st_system.create_first_device()
34
35 # Display DisplayName of the device.
36 print('Device=', st_device.info.display_name)
37
38 # Create a converter object for vertical reverse.
39 st_converter_reverse = st.create_converter(st.EStConverterType.Reverse)
40 st_converter_reverse.reverse_y = True
41
42 # Create a converter object for converting pixel format to BGR8.
43 st_converter_pixelformat = \
44 st.create_converter(st.EStConverterType.PixelFormat)
45 st_converter_pixelformat.destination_pixel_format = \
46 st.EStPixelFormatNamingConvention.BGR8
47
48 # Create a datastream object for handling image stream data.
49 st_datastream = st_device.create_datastream()
50
51 # Start the image acquisition of the host (local machine) side.
52 st_datastream.start_acquisition(number_of_images_to_grab)
53
54 # Start the image acquisition of the camera side.
55 st_device.acquisition_start()
56
57 # A while loop for acquiring data and checking status
58 while st_datastream.is_grabbing:
59 # Create a localized variable st_buffer using 'with'
60 # Warning: if st_buffer is in a global scope, st_buffer must be
61 # assign to None to allow Garbage Collector release the buffer
62 # properly.
63 with st_datastream.retrieve_buffer() as st_buffer:
64 # Check if the acquired data contains image data.
65 if st_buffer.info.is_image_present:
66 # Create an image object and convert
67 st_image = st_converter_pixelformat.convert(
68 st_converter_reverse.convert(st_buffer.get_image()))
69
70 # Display the information of the acquired image data.
71 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
72 st_buffer.info.frame_id,
73 st_image.width, st_image.height,
74 st_image.get_image_data()[0]))
75
76 # Get raw image data.
77 data = st_image.get_image_data()
78
79 nparr = np.frombuffer(data, np.uint8)
80
81 # Process image for displaying the BGR8 image.
82 nparr = nparr.reshape(st_image.height, st_image.width, 3)
83
84 # Resize image.and display.
85 nparr = cv2.resize(nparr, None,
86 fx=DISPLAY_RESIZE_FACTOR,
87 fy=DISPLAY_RESIZE_FACTOR)
88 cv2.imshow('image', nparr)
89 cv2.waitKey(1)
90 else:
91 # If the acquired data contains no image data.
92 print("Image data does not exist.")
93
94 # Stop the image acquisition of the camera side
95 st_device.acquisition_stop()
96
97 # Stop the image acquisition of the host side
98 st_datastream.stop_acquisition()
99
100except Exception as exception:
101 print(exception)
singlefilter_opencv.py¶
1"""
2This sample shows how to process received image with filter and converter.
3The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Acquire image data
7 - Apply image processing with StApi filter and converter.
8 - Copy image data for OpenCV
9 - Preview image using OpenCV
10 Note: opencv-python and numpy packages are required:
11 pip install numpy
12 pip install opencv-python
13"""
14
15import cv2
16import numpy as np
17import stapipy as st
18
19# Number of images to grab
20number_of_images_to_grab = 100
21
22# Image scale when displaying using OpenCV.
23DISPLAY_RESIZE_FACTOR = 0.3
24
25try:
26 # Initialize StApi before using.
27 st.initialize()
28
29 # Create a system object for device scan and connection.
30 st_system = st.create_system()
31
32 # Connect to first detected device.
33 st_device = st_system.create_first_device()
34
35 # Display DisplayName of the device.
36 print('Device=', st_device.info.display_name)
37
38 # Create EdgeEnhancement filter object
39 st_filter_edge = st.create_filter(st.EStFilterType.EdgeEnhancement)
40 st_filter_edge.strength = 5
41
42 # Create a converter object for converting pixel format to BGR8.
43 st_converter_pixelformat = \
44 st.create_converter(st.EStConverterType.PixelFormat)
45 st_converter_pixelformat.destination_pixel_format = \
46 st.EStPixelFormatNamingConvention.BGR8
47
48 # Create a datastream object for handling image stream data.
49 st_datastream = st_device.create_datastream()
50
51 # Start the image acquisition of the host (local machine) side.
52 st_datastream.start_acquisition(number_of_images_to_grab)
53
54 # Start the image acquisition of the camera side.
55 st_device.acquisition_start()
56
57 # A while loop for acquiring data and checking status
58 while st_datastream.is_grabbing:
59 # Create a localized variable st_buffer using 'with'
60 # Warning: if st_buffer is in a global scope, st_buffer must be
61 # assign to None to allow Garbage Collector release the buffer
62 # properly.
63 with st_datastream.retrieve_buffer() as st_buffer:
64 # Check if the acquired data contains image data.
65 if st_buffer.info.is_image_present:
66 # Filter and convert the acquired image.
67 st_image = st_filter_edge.apply_filter(st_buffer.get_image())
68 st_image = st_converter_pixelformat.convert(st_image)
69
70 # Display the information of the acquired image data.
71 print("BlockID={0} Size={1} x {2} First Byte={3}".format(
72 st_buffer.info.frame_id,
73 st_image.width, st_image.height,
74 st_image.get_image_data()[0]))
75
76 # Get raw image data.
77 data = st_image.get_image_data()
78
79 nparr = np.frombuffer(data, np.uint8)
80
81 # Process image for displaying the BGR8 image.
82 nparr = nparr.reshape(st_image.height, st_image.width, 3)
83
84 # Resize image.and display.
85 nparr = cv2.resize(nparr, None,
86 fx=DISPLAY_RESIZE_FACTOR,
87 fy=DISPLAY_RESIZE_FACTOR)
88 cv2.imshow('image', nparr)
89 cv2.waitKey(1)
90 else:
91 # If the acquired data contains no image data.
92 print("Image data does not exist.")
93
94 # Stop the image acquisition of the camera side
95 st_device.acquisition_stop()
96
97 # Stop the image acquisition of the host side
98 st_datastream.stop_acquisition()
99
100except Exception as exception:
101 print(exception)
user_memory.py¶
1"""
2 This sample shows how to use UserMemory function.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - How to read user data from the rom and to write user data to the rom.
7"""
8
9import stapipy as st
10
11# Feature names
12DEVICE_USER_MEMORY = "DeviceUserMemory"
13
14def display_register(register_node):
15 buffer = register_node.value
16 for i, val in enumerate(buffer):
17 if (i & 0xF) == 0:
18 print("{0:04X}\t".format(i), end='')
19 print("{0:02X} ".format(val), end='')
20 if (i & 0xF) == 0xF:
21 print("")
22 print("")
23
24if __name__ == "__main__":
25 try:
26 # Initialize StApi before using.
27 st.initialize()
28
29 # Create a system object for device scan and connection.
30 st_system = st.create_system()
31
32 # Connect to first detected device.
33 st_device = st_system.create_first_device(
34 st.ETLDeviceAccessFlags.AccessExclusive)
35
36 # Display DisplayName of the device.
37 print('Device=', st_device.info.display_name)
38
39 # Get the remote nodemap.
40 nodemap = st_device.remote_port.nodemap
41
42 # Use NodeMap object to access current setting of the camera.
43 node_user_memory = nodemap.get_node(DEVICE_USER_MEMORY)
44
45 if node_user_memory:
46 display_register(node_user_memory.get())
47 else:
48 print(DEVICE_USER_MEMORY + " is not supported by this camera.")
49
50 except Exception as exception:
51 print(exception)
user_set_ctrl.py¶
1"""
2 This sample shows how to use UserSet to load/save setting from/into camera ROM.
3 The following points will be demonstrated in this sample code:
4 - Initialize StApi
5 - Connect to camera
6 - Load/Save UserSet with FeatureBag
7"""
8
9import stapipy as st
10
11# Feature names
12USER_SET_SELECTOR = "UserSetSelector"
13USER_SET_TARGET = "UserSet1"
14USER_SET_LOAD = "UserSetLoad"
15USER_SET_SAVE = "UserSetSave"
16USER_SET_DEFAULT = "UserSetDefault"
17USER_SET_DEFAULT_SELECTOR = "UserSetDefaultSelector"
18PIXEL_FORMAT = "PixelFormat"
19
20
21def set_enumeration(nodemap, enum_name, entry_name):
22 """
23 Function to set enumeration value.
24
25 :param nodemap: node map.
26 :param enum_name: name of the enumeration node.
27 :param entry_name: symbolic value of the enumeration entry node.
28 """
29 enum_node = st.PyIEnumeration(nodemap.get_node(enum_name))
30 entry_node = st.PyIEnumEntry(enum_node[entry_name])
31 # Note that depending on your use case, there are three ways to set
32 # the enumeration value:
33 # 1) Assign the integer value of the entry with set_int_value(val) or .value
34 # 2) Assign the symbolic value of the entry with set_symbolic_value("val")
35 # 3) Assign the entry (PyIEnumEntry) with set_entry_value(entry)
36 # Here set_entry_value is used:
37 enum_node.set_entry_value(entry_node)
38
39
40def display_current_enumeration(nodemap, enum_name):
41 """
42 Display the current setting of the indicated enumeration of the node map.
43
44 :param nodemap: node map.
45 :param enum_name: name of the enumeration node.
46 """
47 enum_node = st.PyIEnumeration(nodemap.get_node(enum_name))
48 print("Current {0} = {1}".format(
49 enum_name, st.PyIEnumEntry(enum_node.current_entry).symbolic_value))
50
51
52def edit_enumeration(nodemap, enum_name):
53 """
54 Display and allow user to modify the enumeration value.
55
56 :param nodemap: node map.
57 :param enum_name: name of the enumeration node.
58 """
59 node = nodemap.get_node(enum_name)
60 if not node.is_writable:
61 return
62
63 # Get PyIEnumeration from PyNode.
64 enum_node = st.PyIEnumeration(node)
65
66 while True:
67 print(enum_name)
68 enum_entries = enum_node.entries
69 for index in range(len(enum_entries)):
70 enum_entry = enum_entries[index]
71 if enum_entry.is_available:
72 print("{0} : {1} {2}".format(index,
73 st.PyIEnumEntry(enum_entry).symbolic_value,
74 "(Current)" if enum_node.value == enum_entry.value
75 else ""))
76 selection = int(input("Select : "))
77 if selection < len(enum_entries):
78 enum_entry = enum_entries[selection]
79 enum_node.set_int_value(enum_entry.value)
80 break
81
82
83if __name__ == "__main__":
84 try:
85 # Initialize StApi before using.
86 st.initialize()
87
88 # Create a system object for device scan and connection.
89 st_system = st.create_system()
90
91 # Connect to first detected device.
92 st_device = st_system.create_first_device(
93 st.ETLDeviceAccessFlags.AccessExclusive)
94
95 # Display DisplayName of the device.
96 print('Device=', st_device.info.display_name)
97
98 # Get the remote nodemap.
99 nodemap = st_device.remote_port.nodemap
100
101 # Set the UserSet to be used by UserSetSelector.
102 set_enumeration(nodemap, USER_SET_SELECTOR, USER_SET_TARGET)
103
104 # Load the UserSet stored in the ROM to the camera.
105 # Here, .get() is used to automatically cast the PyNode to PyICommand.
106 nodemap.get_node(USER_SET_LOAD).get().execute()
107
108 print("Loaded :", USER_SET_TARGET)
109
110 # Create a FeatureBag object for acquiring/saving camera settings.
111 featurebag = st.create_featurebag()
112
113 # Save the current settings to FeatureBag.
114 featurebag.store_nodemap_to_bag(nodemap)
115
116 # Set the pixel format.
117 edit_enumeration(nodemap, PIXEL_FORMAT)
118
119 # Display current pixel format setting.
120 display_current_enumeration(nodemap, PIXEL_FORMAT)
121
122 # Load the UserSet that are stored in the ROM to the camera.
123 # Here, .get() is used to automatically cast the PyNode to PyICommand.
124 nodemap.get_node(USER_SET_LOAD).get().execute()
125 print("Loaded :", USER_SET_TARGET)
126
127 # Display current pixel format setting.
128 display_current_enumeration(nodemap, PIXEL_FORMAT)
129
130 # Load the settings in the FeatureBag to the camera.
131 featurebag.load(nodemap)
132
133 # Set the UserSet for UserSetSelector.
134 set_enumeration(nodemap, USER_SET_SELECTOR, USER_SET_TARGET)
135
136 # Save the current settings to UserSet.
137 # Here, .get() is used to automatically cast the PyNode to PyICommand.
138 nodemap.get_node(USER_SET_SAVE).get().execute()
139 print("Saved :", USER_SET_TARGET)
140
141 if nodemap.get_node(USER_SET_DEFAULT):
142 display_current_enumeration(nodemap, USER_SET_DEFAULT)
143 else:
144 display_current_enumeration(nodemap, USER_SET_DEFAULT_SELECTOR)
145
146 except Exception as exception:
147 print(exception)