Creating DigitalMicrograph images and accessing image data
Python Script
DigitalMicrograph images can be created from Numpy arrays. DigitalMicrograph image values can be accessed as a Numpy array.
Preview
'''
DM images can be created from Numpy arrays.
DM image values can be accessed as Numpy array.
'''
import DigitalMicrograph as DM
import numpy as np
# Create a DM Image from a Numpy Array
# Note that the shape of the array lists the highest dimension first
imgArray = np.array([
[1,2,3,4,5],
[0,0,0,0,0],
[6,7,8,9,10]
])
print( 'Shape of Numpy array:',imgArray.shape )
print( imgArray )
# Create DM image with values of array.
# This creates a new memory array.
# The variable imgArray does not reference the image data array.
img = DM.CreateImage(imgArray)
img.SetName('Test image')
img.ShowImage()
DM.OkDialog('Changing values now')
# Get Numpy array referencing the image data
testImg = img.GetNumArray()
# When assigning new values to the array, care must be taken
# that values of the array are updated and not a new array is
# created and assigned to the variable!
# Invalid options are any of the following
# testImg = 5
# testImg = np.random.choice(20,size=[3,5])
# Valid options are any of the following:
testImg *= 5
testImg[:,:] = np.random.choice(20,size=[3,5])
np.copyto(testImg, np.arange(15).reshape(3,5))
# The values of the image have changed now.
# However, the image display will only change on an update
if ( DM.OkCancelDialog('Update display?') ):
img.UpdateImage()
# All DM image variables need to be explicitly deleted by the script.
# Otherwise, the referenced image can not be removed fully from memory.
del img