A Python script can directly manipulate image data held in DigitalMicrograph®. This is achieved by mapping NumPy arrays onto the memory of the DigitalMicrograph images. This sharing of memory access imposes some restrictions—see the examples on Images and NumPy arrays.
Inversion of dimensions
DigitalMicrograph image images store their elements with first dimension index incrementing first, e.g., consecutive values describe the next pixel in X-direction until a row is completed. Only then does the Y-coordinate get incremented by one and the X-coordinate reset to zero. Similarly, only after all rows have been filled will the Z-coordinate be incremented to move to the next plane.
NumPy arrays, unfortunately, use the opposite indexing concept, incrementing the last dimension index first. As a result, NumPy arrays mapped onto DigitalMicrograph images, and DigitalMicrograph images created from NumPy arrays exhibit an apparent flip of dimensions.
For example, a DigitalMicrograph image of size 100 x 20 is represented by a NumPy array of shape (20, 100).
Similarly, a DigitalMicrograph stack of size 100 x 20 x 10 is represented by a NumPy array of shape (10, 20, 100).
Updating image data
NumPy arrays connected to DigitalMicrograph images directly address the same memory space. When using a Python script to change these values, one has to be careful to only use syntax which modifies the existing memory. Many Python commands instead create new data arrays and subsequently assign a variable to this new array. Such commands will not update DigitalMicrograph image data.
Updating image displays
Updating the data in a NumPy array that is connected to a DigitalMicrograph image does not automatically trigger a display update in DigitalMicrograph. This has to be explicitly requested by the UpdateImage() script command.
Creating an image from a NumPy array
NumPy arrays are a very flexible object and not all of them can be used as a source for a DigitalMicrograph image. If an invalid data format is encountered, an error message will be presented. NumPy arrays also support views on data. Here, the actual data order in memory is unchanged, but auxiliary metadata describes how it should be addressed. This is most often used to access non-contiguous data, which can not be used as a memory array for a DigitalMicrograph image. For this reason, it is not possible to create a DigitalMicrograph image directly from a NumPy array view. Instead, a contiguous copy of the view needs to be created first.
Deleting DigitalMicrograph image variables (Py_Image)
Python scripts keep references to DigitalMicrograph images in variables of type Py_Image. However, when the Python script ends, all such variables need to be explicitly deleted in the script using the del command. If they are not deleted they will prevent DigitalMicrograph from properly closing the images and they will remain in memory until the application is shut down.