Context Managers¶
Context managers can be used in order to avoid writing verbose boilerplate code like the following:
try:
api.initialize()
# User code.
except NxLibException as e:
print(f"An NxLibException occured: Error Text: {e.get_error_text()}")
except Exception as e:
print("Something bad happenend, that has been out of our control.\n")
raise e
This can simplified with a context manager, who performs the initialization and takes care of the exception handling as follows:
with NxLib() as api:
# User code.
See Examples for more on how the following classes can be used to simplify and beautify your code.
NxLib¶
- class nxlib.context.NxLib(path=None)¶
This class offers a simple to use interface for interacting with a normal NxLib. It implements the context manager protocol and thus can be used in a
with
statement, which automatically initializes the NxLib and takes care of the exception handling.- Parameters
path (str, optional) – The path to the NxLib shared library. Defaults to None.
NxLibRemote¶
- class nxlib.context.NxLibRemote(hostname, port)¶
This class offers a simple to use interface for interacting with a remote NxLib. It implements the context manager protocol and thus can be used in a
with
statement, which automatically loads the remote NxLib, connects to the given hostname (and port) when entering the scope and automatically disconnects when exiting the scope. It also takes care of the exception handling.- Parameters
hostname (str) – The hostname of the remote NxLib.
port (int) – The port number of the remote NxLib.
MonoCamera¶
- class nxlib.context.MonoCamera(serial, open_params={})¶
This class implements the context manager protocol and simplifies the handling of a mono camera.
It provides the camera tree node by calling
get_node()
or lets you directly access anNxLibItem
within the camera node by using the[]
operator.- Parameters
serial (str) – The serial number of the target camera.
open_params (dict) – Optional parameters for opening the target camera.
- Raises
CameraTypeError – If the camera with the given serial number is not a monocular camera.
CameraNotFoundError – If no camera was found for the given serial number.
CameraOpenError – If the camera with the given serial cannot be opened.
- capture(params={})¶
Capture the image(s).
- Parameters
params (dict, optional) – Parameters for the capture command.
- Raises
NxLibException – If the capture fails.
- close()¶
Closes the connection to the camera device.
This method should be called to properly release the camera and associated resources when using the Camera class in manual mode (i.e., without a context manager).
Note
The default and preferred usage of the Camera class is as a context manager using the
with
statement. In that case,close()
is called automatically when exiting the context and should not be invoked manually.Examples
Preferred usage (context manager):
with Camera(serial, open_params) as cam: cam.capture() # Camera is automatically closed when the block exits
Manual usage (if context management is not possible):
cam = Camera(serial, open_params) cam.open() try: cam.capture() finally: cam.close()
- classmethod from_serial(serial, expected_types=None, open_params={})¶
- get_model_name() str ¶
Returns the camera’s model name as a string.
- Raises
NxLibException – If the model name cannot be retrieved or is missing.
- Returns
The model name of the camera.
- Return type
str
- get_node()¶
Get the camera tree node of the stereo camera the context object opens and represents.
- Returns
The camera node of the stereo camera.
- Return type
NxLibItem
- get_required_action() nxlib.context.CameraAction ¶
Returns the required action as a CameraAction enum.
- get_serial_number() str ¶
Returns the camera’s serial number as a string.
- Raises
NxLibException – If the serial number cannot be retrieved or is missing.
- Returns
The serial number of the camera.
- Return type
str
- is_available() bool ¶
True if camera is available.
- is_open() bool ¶
True if camera is open.
- open()¶
Opens a connection to the camera device.
This method establishes communication with the camera and must be called before performing any operations that require an active connection (e.g., capturing images).
Note
The default and preferred usage of the Camera class is as a context manager using the
with
statement. In that case,open()
is called automatically and should not be invoked manually.Examples
Preferred usage (context manager):
with Camera(serial, open_params) as cam: cam.capture() # Camera is automatically closed when the block exits
Manual usage (if context management is not possible):
cam = Camera(serial, open_params) cam.open() try: cam.capture() finally: cam.close()
- rectify()¶
Rectify the captured images (requires
capture()
to be called first). Use this method only if you want to have the rectified raw images and no further data.
- requires_action() bool ¶
True if any action other than NONE is required.
StereoCamera¶
- class nxlib.context.StereoCamera(serial, open_params={})¶
This class implements the context manager protocol and simplifies the handling of an Ensenso stereo camera.
It provides the camera tree node by calling
get_node()
or lets you directly access anNxLibItem
within the camera node by using the[]
operator.- Parameters
serial (str) – The serial number of the target camera.
open_params (dict) – Optional parameters for opening the target camera.
- Raises
CameraTypeError – If the camera with the given serial number is not a stereo camera.
CameraNotFoundError – If no camera was found for the given serial number.
CameraOpenError – If the camera with the given serial cannot be opened.
- capture(params={})¶
Capture the image(s).
- Parameters
params (dict, optional) – Parameters for the capture command.
- Raises
NxLibException – If the capture fails.
- close()¶
Closes the connection to the camera device.
This method should be called to properly release the camera and associated resources when using the Camera class in manual mode (i.e., without a context manager).
Note
The default and preferred usage of the Camera class is as a context manager using the
with
statement. In that case,close()
is called automatically when exiting the context and should not be invoked manually.Examples
Preferred usage (context manager):
with Camera(serial, open_params) as cam: cam.capture() # Camera is automatically closed when the block exits
Manual usage (if context management is not possible):
cam = Camera(serial, open_params) cam.open() try: cam.capture() finally: cam.close()
- compute_disparity_map()¶
Compute the disparity map (requires
capture()
to be called first).- Returns
The disparity map node.
- Return type
NxLibItem
- compute_point_map()¶
Compute the point map (requires
compute_disparity_map()
to be called first).- Returns
The point map node.
- Return type
NxLibItem
- compute_texture()¶
Compute the rectified texture image (requires
rectify()
orcompute_disparity_map()
to be called first).- Returns
- The node containing the rectified texture image for
the camera’s left sensor.
- Return type
NxLibItem
- classmethod from_serial(serial, expected_types=None, open_params={})¶
- get_disparity_map()¶
The computed disparity map (requires
compute_disparity_map()
).- Returns
A byte buffer containing the disparity map.
- Return type
Object
- get_model_name() str ¶
Returns the camera’s model name as a string.
- Raises
NxLibException – If the model name cannot be retrieved or is missing.
- Returns
The model name of the camera.
- Return type
str
- get_node()¶
Get the camera tree node of the stereo camera the context object opens and represents.
- Returns
The camera node of the stereo camera.
- Return type
NxLibItem
- get_point_map()¶
The computed point map (requires
compute_point_map()
).- Returns
A byte buffer containing the point map.
- Return type
Object
- get_required_action() nxlib.context.CameraAction ¶
Returns the required action as a CameraAction enum.
- get_serial_number() str ¶
Returns the camera’s serial number as a string.
- Raises
NxLibException – If the serial number cannot be retrieved or is missing.
- Returns
The serial number of the camera.
- Return type
str
- get_texture()¶
The computed rectified texture image (requires
compute_texture()
).- Returns
- A byte buffer containing the rectified texture image for
the camera’s left sensor.
- Return type
Object
- is_available() bool ¶
True if camera is available.
- is_open() bool ¶
True if camera is open.
- open()¶
Opens a connection to the camera device.
This method establishes communication with the camera and must be called before performing any operations that require an active connection (e.g., capturing images).
Note
The default and preferred usage of the Camera class is as a context manager using the
with
statement. In that case,open()
is called automatically and should not be invoked manually.Examples
Preferred usage (context manager):
with Camera(serial, open_params) as cam: cam.capture() # Camera is automatically closed when the block exits
Manual usage (if context management is not possible):
cam = Camera(serial, open_params) cam.open() try: cam.capture() finally: cam.close()
- rectify()¶
Rectify the captured images (requires
capture()
to be called first). Use this method only if you want to have the rectified raw images and no further data.
- requires_action() bool ¶
True if any action other than NONE is required.
- save_model(filename: str, texture: bool = True, threads: int = - 1, wait: bool = True)¶
Save the 3D mesh model of the camera to a file in STL or PLY format.
The mesh includes vertices and triangle indices, and optionally vertex color data (RGB) when saved in PLY format and
texture
is set to True.- Parameters
filename (str) – Path to the file where the model will be saved.
texture (bool, optional) – Whether to include RGB texture data in the model. Defaults to True.
threads (int, optional) – Number of threads to use for saving. If <= 0, the default is used.
wait (bool, optional) – Whether to execute the command synchronously. If False,
NxLibCommand (the method returns immediately. The caller can use the returned) –
True. (object to wait for completion manually. Defaults to) –
- Returns
The command used to save the model. In asynchronous mode, the caller can use
.wait()
to wait for completion.- Return type
- Raises
NxLibException – If the model saving process fails.
Note
The file format (STL or PLY) is inferred from the file extension.
PLY format includes a structured header followed by binary data for vertices and faces.
If
texture
is True, each vertex in the PLY file includes red, green, and blue components.Triangles are represented as a list of three vertex indices.
StructuredLightCamera¶
- class nxlib.context.StructuredLightCamera(serial, open_params={})¶
This class implements the context manager protocol and simplifies the handling of an Ensenso structured light camera and has the same functionality as a stereo camera except that it does not have a disparity map.
It provides the camera tree node by calling
get_node()
or lets you directly access anNxLibItem
within the camera node by using the[]
operator.- Parameters
serial (str) – The serial number of the target camera.
open_params (dict) – Optional parameters for opening the target camera.
- Raises
CameraTypeError – If the camera with the given serial number is not a structured light camera.
CameraNotFoundError – If no camera was found for the given serial number.
CameraOpenError – If the camera with the given serial cannot be opened.
CameraDisparityMapError – If a disparity map is requested.
- capture(params={})¶
Capture the image(s).
- Parameters
params (dict, optional) – Parameters for the capture command.
- Raises
NxLibException – If the capture fails.
- compute_disparity_map()¶
Does nothing, because a structured light camera does not have a disparity map. Existing for compatibility reasons.
- compute_point_map()¶
Compute the point map (requires
capture()
to be called first).- Returns
The point map node.
- Return type
NxLibItem
- compute_texture()¶
Compute the rectified texture image (requires
rectify()
orcompute_disparity_map()
to be called first).- Returns
- The node containing the rectified texture image for
the camera’s left sensor.
- Return type
NxLibItem
- get_node()¶
Get the camera tree node of the stereo camera the context object opens and represents.
- Returns
The camera node of the stereo camera.
- Return type
NxLibItem
- get_point_map()¶
The computed point map (requires
compute_point_map()
).- Returns
A byte buffer containing the point map.
- Return type
Object
- get_texture()¶
The computed rectified texture image (requires
compute_texture()
).- Returns
- A byte buffer containing the rectified texture image for
the camera’s left sensor.
- Return type
Object
Exceptions¶
- exception nxlib.context.CameraTypeError¶
Raised if camera has the wrong type (Mono/Stereo/StructuredLight).
- exception nxlib.context.CameraNotFoundError¶
Raised if no camera is found for a given serial number.
- exception nxlib.context.CameraOpenError¶
Raised if a camera cannot be opened.
- exception nxlib.context.CameraDisparityMapError¶
Raised if a non-existing disparity map is requested.