Downloading 7.5 format analytic images in python

I am doing some work in which I have to load CT manipulation images in the Analyze 7.5 file format .

Part of this manipulation, which takes absolutely age with large images, loads the raw binary data into a numpy array and converts them to the correct sizes. Here is an example:

headshape = (512,512,245) # The shape the image should be headdata = np.fromfile("Analyze_CT_Head.img", dtype=np.int16) # loads the image as a flat array, 64225280 long. For testing, a large array of random numbers would do head_shaped = np.zeros(shape=headshape) # Array to hold the reshaped data # This set of loops is the problem for ux in range(0, headshape[0]): for uy in range(0, headshape[1]): for uz in range(0, headshape[2]): head_shaped[ux][uy][uz] = headdata[ux + headshape[0]*uy + (headshape[0]*headshape[1])*uz] # Note the weird indexing of the flat array - this is the pixel ordering I have to work with 

I know that numpy can quickly convert arrays, but I can't figure out the right combination of transforms needed to replicate the effect of nested loops.

Is there any way to reproduce this weird indexing with some combination of numpy.reshape / numpy.ravel etc.

+6
source share
3 answers

You can use conversion in conjunction with swapaxes

 headshape = (2,3,4) headdata = rand(2*3*4) head_shaped_short = headdata.reshape(headshape[::-1]).swapaxes(0,2) 

worked great in my case.

0
source

numpy stores arrays in memory. The strides attribute contains the necessary information on how to map multidimensional indexes to flat indexes in memory.

Below is some additional information about the numpy layout.

This should work for you:

 # get the number of bytes of the specified dtype dtype = headdata.dtype byte_count = dtype.itemsize headdata = headdata.reshape(headshape) x, y, z = headshape headdata.strides = (byte_count, byte_count * x, byte_count * x * y) # copy data to get back to standard memory layout data = headdata.copy() 

The code uses the strides attribute, which reflects your own memory mapping and creates (hopefully) a valid multidimensional array. After that, it copies the entire array to data to return to the standard memory layouts.

0
source

Take a look at nibabel , a python library that implements readers / writers for the Analysis format. Perhaps he has already decided this for you.

0
source

Source: https://habr.com/ru/post/979702/


All Articles