Question

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

Was it helpful?

Solution

Your first problem is that you have your axes wrong. Assuming you have 132 layers of 512x512 images you want to use:

original = numpy.fromfile(filepath, dtype=numpy.uint16).reshape((132, 512, 512))

Then for the slice take:

slc = original[66]

Also, binary data such as Numpy arrays use:

f = open('test.raw', 'wb')

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 use

arr.tofile('test.raw')

One final note: Try not to use slice as a variable. That's a builtin name in Python and you could run into trouble by shadowing it with something else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top