Luke
Luke

Reputation: 105

CreateImage Bug in DigitalMicrograph (python)

I seem to have encountered a very strange bug while trying to create an image in DigitalMicrograph using python. In short, I define an array that holds 32 x- and y-coordinates that I then reshape into a 2x4x4 matrix. When creating an image, DM then plots alternating x- and y- coordinates in the x-plane. I think it is best described with this MWE:

import numpy as np

num1 = np.arange(32.)
num1 = num1.reshape((2,4,4))
print(f'num1: {num1}')


num2 = np.zeros((16,2))
for i in range(16):
    num2[i, :] = i, i+16
num2 = num2.reshape((4,4,2))
num2 = np.copy(np.transpose(num2, (2, 0, 1)))
print(f'num2: {num2}')

print(f"Are the arrays equal? {np.array_equal(num1, num2)}" )

print(f'num1 shape: {num1.shape}')
print(f'num2 shape: {num2.shape}')

img1 = DM.CreateImage(np.copy(num1))
img1.ShowImage()

img2 = DM.CreateImage(np.copy(num2))
img2.ShowImage()

del img1
del img2

num2 demonstrates the bug - stripes are visible in the image. DM plots the first x-coordinate in the x-plane (1x4x4) and then the first y-coordinate and continues to alternate until all places are filled. If I get the array from this image, the resulting array is different than the one I pass to the CreateImage function.

In comparison, num1 creates the exact same original array, is passed to the same function, but is plotted as expected.

The script output is:

num1: [[[ 0.  1.  2.  3.]
  [ 4.  5.  6.  7.]
  [ 8.  9. 10. 11.]
  [12. 13. 14. 15.]]

 [[16. 17. 18. 19.]
  [20. 21. 22. 23.]
  [24. 25. 26. 27.]
  [28. 29. 30. 31.]]]
num2: [[[ 0.  1.  2.  3.]
  [ 4.  5.  6.  7.]
  [ 8.  9. 10. 11.]
  [12. 13. 14. 15.]]

 [[16. 17. 18. 19.]
  [20. 21. 22. 23.]
  [24. 25. 26. 27.]
  [28. 29. 30. 31.]]]
Are the arrays equal? True
num1 shape: (2, 4, 4)
num2 shape: (2, 4, 4)

Maybe a memory problem? Has anyone else encountered this?

Upvotes: 1

Views: 125

Answers (1)

BmyGuest
BmyGuest

Reputation: 2939

The issue you are encountering is due to the Numpy copy command. From the documentation it can be seen, that it uses the 'K' parameter as default:

‘K’ means match the layout of a as closely as possible.

The memory layout does not (seem to) matter in Python scripts, but it certainly matters when creating DM images which map to the same continuous memory section.

This is the reason why a copy is needed in the first place.

If you replace

img1 = DM.CreateImage(np.copy(num1))
img1.ShowImage()

img2 = DM.CreateImage(np.copy(num2))
img2.ShowImage()

with

img1 = DM.CreateImage(np.copy(num1, order = 'C'))
img1.ShowImage()

img2 = DM.CreateImage(np.copy(num2, order = 'C'))
img2.ShowImage()

things are fixed. (Order 'A' also seems to work in this case.)

Upvotes: 1

Related Questions