Working with the Python interfaceđź”—
Note
This section describes how to use HALCON’s interfaces in Python.
For HALCON/C++ or HALCON/.NET, see the corresponding section.
How to import the moduleđź”—
To strike a good balance between ease of use, readability, and traceability we recommend importing the HALCON/Python module like this:
Using HALCON/Python with HALCON XLđź”—
HALCON XL
Only use HALCON XL when you need its features.
To use HALCON XL, set the environment variable HALCON_PYTHON_XL to the string true before the halcon module is imported.
This can be done directly in Python:
Alternatively, you can set the environment variable through the usual system-specific settings. If possible, we recommend using the suggested method to minimize external dependencies.
How to call operatorsđź”—
In HALCON/Python, you call HALCON operators directly as non-member functions, exposed directly through the top-level halcon module.
Example
The following code grabs the first image of an image sequence using a framegrabber and displays the image in a window:
framegrabber = ha.open_framegrabber(
name='File',
horizontal_resolution=1,
vertical_resolution=1,
image_width=0,
image_height=0,
start_row=0,
start_column=0,
field='default',
bits_per_channel=-1,
color_space='default',
generic=-1,
external_trigger='default',
camera_type='board/board.seq',
device='default',
port=1,
line_in=-1
)
img = ha.grab_image(framegrabber)
width, height = ha.get_image_size_s(img)
window = ha.open_window(
row=0,
column=0,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
ha.disp_obj(img, window)
- Operators are standalone functions.
-
Notice how all operator calls are standalone functions in the above example:
- Inputs are parameters, outputs are return values.
-
Another important aspect of HALCON/Python is the split of inputs and outputs. Inputs are function parameters, and outputs are return values.
-
Single outputs are returned directly, and multiple outputs are returned as Python tuple. This allows clearer reasoning about data transformations, aided by ergonomic features such as destructuring. It can be seen with
get_image_size_s, which returns two values, both of which can be given names directly. - HALCON tuples are represented with native Python types.
-
Both when passing values into operators as input parameters, and when receiving values as return values from operators, what is represented with HALCON tuples in HDevelop is a native Python value in HALCON/Python.
Important
Do not confuse HALCON tuples with Python tuples, they are unconnected concepts.
Example
The return value for
get_image_size_sis truly of type int and not something that represents the HALCON version of integers. -
In HALCON/Python,
HTuplemaps to either one of the following types or to a possibly mixed list of them:intfloatstr- the class
HHandle
-
Python’s
floatmaps to HALCON’srealtype. While Python’sintis of arbitrary precision, calling operators withintvalues outside what a signed integer of platform size can represent, for example:ptrdiff_tin C, will result in an exception. - Operator and parameter names use snake case.
- Following Python’s PEP8 standard for code style, functions and parameter in HALCON/Python are snake_case.
About handle, iconic object, and HDict representationđź”—
HHandle classđź”—
The HHandle class represents control handle values.
Example
camera_model = ha.create_camera_setup_model(num_cameras=4)
assert isinstance(camera_model, ha.HHandle)
create_camera_setup_model returns a HHandle that represents a camera model.
This HHandle can later be passed to other operators that work with camera models.
Other than equality comparison, HHandle does not implement any further functionality by itself.
HObject classđź”—
The HObject class represents iconic objects.
In HALCON, iconic objects model a hierarchy:
%%{ init: { 'flowchart': { 'curve': 'linear' } } }%%
flowchart TD
object --> image
object --> region
object ~~~ distance_dummy:::hidden
object --> xld
xld --> xld_cont
xld --> xld_poly
xld --> xld_para
xld --> xld_mod_para
xld --> xld_ext_para
classDef hidden display: none;
HALCON/Python does not model this object hierarchy with a class hierarchy, rather it only provides a single class HObject.
Iconic objects in HALCON can represent collections of objects, such as a sequence of images, or multiple regions etc. HALCON/Python mirrors this behavior:
img = ha.read_image('pcb')
img_seq = ha.concat_obj(img, ha.read_image('fuse'))
width, height = ha.get_image_size(img_seq)
assert width == [1109, 768]
assert height == [871, 576]
Here, img_seq represents two images, and follow-up operators like get_image_size work in a batch fashion accordingly.
HObject behaves similarly to lists in Python:
assert len(img_seq) == 2
for single_img in img_seq:
assert ha.get_image_size_s(single_img) > (600, 400)
assert ha.get_image_size_s(img_seq[1]) == (768, 576)
assert ha.get_image_size_s(img_seq[-2]) == (1109, 871)
assert ha.get_image_size(img_seq[:4]) == ([1109, 768], [871, 576])
assert ha.get_image_size(img_seq[1:4]) == ([768], [576])
This includes support for len, iteration, positive and negative indexing, and efficient slicing.
HALCON dictionariesđź”—
HALCON dictionaries (“HDicts”) can be converted to Python dicts and vice versa with the following functions:
as_python_dict_s- Converts HDict to Python dict
as_python_dict- Converts HDict to Python dict
from_python_dict- Converts Python dict to a HDict
An HDict can always be represented as a Python dict.
However, not all Python dicts can be represented as HDict.
Consult the documentation of from_python_dict for more details and examples.
HALCON/Python can convert both single values and lists of values to their HTuple representation, that is, the Python values 345 and [345] share the same HTuple representation.
As a consequence, once Python values have been converted to their HALCON counterparts, this information is lost.
Accordingly, roundtrip converting a Python dict through an HDict and back is a lossy operation.
as_python_dict represents all HTuples as lists.
In addition, as_python_dict_s can be used if the user expects that all HTuple values are single values.
as_python_dict_s represents all HTuples as single values and not as lists.
as_python_dict_s raises an HError if any HTuple has more than one value.
An example usage of the conversion hooks can be found in Using HALCON/Python with NumPy.
About output valuesđź”—
Outputs come in three variants:
- Always as single value, for example:
read_image
In this case, the Python version of the operator will return a single value of the list’s element type. - Always as list, for example:
quat_normalize
In this case, the Python version of the operator will always return a list. - Maybe as single value or maybe as list, for example:
get_image_size
In this case, the Python version of the operator will also return a list. However, in many cases it will be known in advance (for example, from the number of input parameters) that only a single value is expected.
For convenience, a second variant of the operator with suffix_sis provided. This will always return a single value, or raise an exception when the operator does not return a single value.
The difference between operators that always return a list and those that sometimes return a list is rather just conceptual. The advantage lies mainly in the convenience of access for the common case of working with single values.
Example
img = ha.read_image('pcb')
width, height = ha.get_image_size_s(img)
assert width == 1109
assert height == 871
width, height = ha.get_image_size(img)
assert width == [1109]
assert height == [871]
img_seq = ha.concat_obj(img, ha.read_image('fuse'))
width, height = ha.get_image_size(img_seq)
assert width == [1109, 768]
assert height == [871, 576]
Asking for the size of a single image, and getting a list with a single element is not particularly useful.
_s versions express the expectation that there should always be exactly one answer, neither zero nor many, explicitly and conveniently.
For information about which operators have _s versions, see the HALCON operator reference.
Using HALCON/Python with NumPyđź”—
HALCON images can be converted to NumPy arrays and vice versa with the following functions:
himage_from_numpy_array- Converts NumPy array to HALCON object
himage_as_numpy_array- Converts single HALCON image to NumPy array
The functions are only usable if the third-party library NumPy package has been installed.
Example
import halcon as ha
import numpy as np
if __name__ == '__main__':
# Single-channel image.
img = ha.read_image('pcb')
numpy_array = ha.himage_as_numpy_array(img)
assert (numpy_array[0][:4] == [225, 216, 224, 230]).all()
img_roundtrip = ha.himage_from_numpy_array(numpy_array)
assert ha.compare_obj(img, img_roundtrip, 0)
# Multi-channel image: Supported
_ = ha.himage_as_numpy_array(ha.read_image('patras'))
# Image list: Not supported
img_list = ha.HObject([ha.read_image('pcb'), ha.read_image('pcb')])
try:
_ = ha.himage_as_numpy_array(img_list)
assert False
except Exception as exc:
assert isinstance(exc, ha.HTupleConversionError)
The dict conversion functions (see HALCON dictionaries) have customization points that can be used in conjunction with the NumPy conversion functions:
Example
import halcon as ha
import numpy as np
if __name__ == '__main__':
numpy_image = np.array([[5, 6, 7], [8, 2, 6], [4, 4, 5]], dtype=np.int32)
py_dict = {'val': [4, 6], 'img': numpy_image}
hdict = ha.from_python_dict(py_dict, unknown_hook=ha.himage_from_numpy_array)
py_dict_roundtrip = ha.as_python_dict(hdict, hobject_hook=ha.himage_as_numpy_array)
assert isinstance(py_dict_roundtrip['img'], np.ndarray)
About memory managementđź”—
HALCON/Python objects that have some natively backed resources implement cleanup via finalizers by implementing __del__.
This means no additional care needs to be taken to ensure that native resources such as memory are freed after a variable is no longer reachable.
For example, CPython uses reference counting to implement garbage collection, which results in moderately deterministic behavior.
About error handlingđź”—
Just like Python, HALCON/Python handles errors via exceptions. As shown in the example below, HALCON error constants are defined at the module level.
Example
def load_custom_pcb_img_or_fallback(custom_pcb_filename):
try:
return ha.read_image(custom_pcb_filename)
except ha.HOperatorError as err:
if err.error_code != ha.errors.H_ERR_FNF: # HALCON error code File not found.
raise err
return ha.read_image('pcb')
img = load_custom_pcb_img_or_fallback('does-not-exist')
In this example, we want to either load a custom PCB image or fallback to the default PCB image if the image cannot be found. If another error occurs, we want to propagate the original error further up the call stack.
Custom HALCON/Python exceptionsđź”—
The custom exceptions used by HALCON/Python form an inheritance hierarchy:
%%{ init: { 'flowchart': { 'curve': 'linear' } } }%%
flowchart TD
Exceptions --> HError
HError --> HOperatorError
HError --> HTupleConversionError
HError --> HDevEngineError
HError --> HInteropError
It starts with the standard Python Exception, from which HError inherits, followed by four more specific exceptions that inherit from HError.
They occur in different situations. Operators and other functions may raise more than one type of exception.
HErroris the base exception all other exceptions inherit from.HTupleConversionErroris for errors that occur during conversion to or from a native HALCON tuple.HDevEngineErroris for errors that occur while using HALCON Script Engine.HInteropErroris for errors that are conceptually related to functionality while interfacing with third-party libraries, such as NumPy.
All custom HALCON/Python exceptions implement __str__.
Example: HTupleConversionError exception
For any instance where a conversion to or from a native HALCON tuple fails, an instance of HTupleConversionError is raised.
Here, HALCON/Python does not know how to pass the custom user-defined class to the HALCON operator read_image.
UTF-8 in HALCON/Pythonđź”—
By default, all strings passed to HALCON from Python are encoded as UTF-8 bytes, and all string bytes passed from HALCON to HALCON/Python are decoded as UTF-8 strings. This is the only supported encoding.
Important
Configuring HALCON via set_system('filename_encoding', 'locale') to use a local encoding (“legacy mode”) is not supported.
Workaround for legacy mode
When used in a legacy mode, some operators may return strings that are invalid UTF-8, even when 'filename_encoding' is set to 'utf8'.
A workaround for such situations exists in the following way:
try:
# Replace invalid UTF-8 when encoding HALCON strings for use in Python.
ha.ffi.enable_utf8_error_replace()
# Call problematic operator ...
finally:
# Restore default behavior of raising a UnicodeError.
ha.ffi.disable_utf8_error_replace()
Disabling the safe default mode is only recommended as a workaround and should only be done where needed, for as long as needed.
About global HALCON functions in HALCON/Pythonđź”—
The following functions can be used to change global HALCON behavior.
They must be called before any HALCON usage to prevent undefined behavior.
The only exceptions are HCancelDraw and HSetMemoryAllocatorType, which can be called at any time.
It is safe to call these functions multiple times.
HUseSpinLock- See Spinlocks, the HALCON thread pool, and real-time scheduling.
HDoLicenseError- Controls the display license error messages.
HStartUpThreadPool- See Spinlocks, the HALCON thread pool, and real-time scheduling.
HCancelDraw- Cancels draw operators explicitly.
HSetMemoryAllocatorType- Sets the allocator used by HALCON.
Can be used to avoid mimalloc initialization.
Supported values are
'system'and'mimalloc'.
See also Managing memory.
Example
import halcon as ha
ha.ffi.HUseSpinLock(False)
ha.ffi.HSetMemoryAllocatorType('system')
if __name__ == '__main__':
img = ha.read_image('pcb')
assert ha.get_system_s('memory_allocator') == 'system'
# ha.ffi.HUseSpinLock(False) This is not allowed
# ha.ffi.HUseSpinLock(True) This is not allowed
# Allowed because HSetMemoryAllocatorType is exempt.
ha.ffi.HSetMemoryAllocatorType('mimalloc')
# The same can be achieved with set_system.
ha.set_system('memory_allocator', 'mimalloc')