# Using numpy reslice to get slices of segment

Hey guys (and especially Andras! (@lassoan)

A while back Andras helped me with a super handy python script to calculate the area of a segment’s slices slice-by-slice and put it in a table. I’ve been working on putting this into a general-use module where it uses the new plot functions to make graphs - not sure if it will be useful to anybody but me, but there it is.

The core of the script he provided used reslice() to reformat the segmentation data into an array of slices:.

``````segmentationNode = getNode('Segmentation')
segmentId = 'Segment_1'
vimage = segmentationNode.GetBinaryLabelmapRepresentation(segmentId)

narray = vtk.util.numpy_support.vtk_to_numpy(vimage.GetPointData().GetScalars())
vshape = vimage.GetDimensions()
narrayBySlice = narray.reshape([-1,vshape[1]*vshape[2]])
``````

Then the number of nonzero voxels is counted, and so on. For axial, coronal, and saggital I use different indexes into the vshape array for reshaping the array - [0] * [1], [0] * [2]. (I’m pretty sure this is where I’m going wrong. But I digress.)

The issue I’m having is that this works great in one direction. As a test case, I made a simple segment with a single sphere. In the axial direction, I get a very smooth curve:

When I switch to the coronal and saggital directions, the curve is very choppy - the values jump up and down around the “correct” curve line:

I’m pretty sure this is just a misunderstanding on my part on how reslice works.

Here’s a snippet of how I’m doing reslice for each direction:

``````  if direction == "Axial":
narrayBySlice = narray.reshape([-1,vshape[0]*vshape[1]])
if direction == "Coronal":
narrayBySlice = narray.reshape([-1,vshape[0]*vshape[2]])
if direction == "Saggital":
narrayBySlice = narray.reshape([-1,vshape[1]*vshape[2]])
``````

I’ve put the module code in a gist for perusal if that helps.

Thank you in advance for any help anyone can give!

-Hollister

To reslice a numpy along a different axis, it is not enough to reshape. You need to swap the axes as well. See https://stackoverflow.com/questions/35226115/numpy-reshaping-multdimensional-array-through-arbitrary-axis

Got it - this was very helpful, as always.

I don’t know if this kind of plot would be generally useful, but I’m happy to package it up and upload it if you think others might use it.

Thanks again!!!

-Hollister

1 Like

Any working examples may be useful for others. You can save it as a github Gist and copy the link here.

Sounds good - Here it is.