I’m trying to extract a slice from a volume using numpy.
The volume is 512x512x132 and I want the slice number 66.
Each voxel is an unsigned 16-bit integer.
My code is:
import numpy
original = numpy.fromfile(filepath, dtype=numpy.uint16)
original = numpy.reshape(original, (512,512,132))
slice = original[:,:,66]
f = open('test.rawl', 'w')
slice.tofile(f)
f.close()
The code complete cleanly, but when I open the slice with an external program, it is not the slice data but garbage.
What I am doing wrong?
Thanks
Your first problem is that you have your axes wrong. Assuming you have 132 layers of 512×512 images you want to use:
Then for the slice take:
Also, binary data such as Numpy arrays use:
The ‘b’ in the mode is for binary. Otherwise Python will assume you’re trying to write text and do things like convert newlines to the appropriate format for the system, among other things.
By the way, the
ndarray.tofile()method also takes a filename, so unless you have a particular reason to it’s not necessary to create a file handle first. You can just useOne final note: Try not to use
sliceas a variable. That’s a builtin name in Python and you could run into trouble by shadowing it with something else.