[Neuroimaging] [Nibabel] Crop image volume?

Michael Waskom mwaskom at nyu.edu
Fri Aug 18 13:49:24 EDT 2017


Thanks Chris, this seems to work well.

Could be a nice addition to nibabel.funcs too!

On Fri, Aug 18, 2017 at 11:39 AM, Christopher Markiewicz <effigies at bu.edu>
wrote:

> Michael,
>
> It's easier than it first looks. Steps 1 and 2, assuming a skull-stripped
> image:
>
> mask = nb.load(brainmask)
> bounds = np.sort(np.vstack(np.nonzero(mask.get_data())))[:, [0, -1]]
> x, y, z = bounds
>
> new_data = mask.get_data()[x[0]:x[1], y[0]:y[1], z[0]:z[1]]
>
> Step 3:
>
> Given A, we want to find A' that is identical up to the intercept, such
> that A * [x_0, y_0, z_0, 1]' == A' * [0, 0, 0, 1].
> Conveniently, A' * [0, 0, 0, 1]' is the fourth row in the affine matrix,
> so we're done as soon as we calculate the LHS:
>
> new_aff = mask.affine.copy()
> new_aff[:, [3]] = mask.affine.dot(np.vstack((bounds[:, [0]], [1])))
>
> new_img = nb.Nifti1Image(new_data, new_aff, mask.header)
>
> Chris
>
>
> On Fri, Aug 18, 2017 at 11:00 AM, Michael Waskom <mwaskom at nyu.edu> wrote:
>
>> Hi Matthew,
>>
>> Is there a nibabel function to crop a 3D image? I want to resample data
>> to match my anatomical, but to save space I want to crop the anatomical on
>> the xyz dimensions to a tight box around the brain volume.
>>
>> In other words I want to take:
>>
>> >>> img.shape
>> --> (256, 256, 256)
>> >>> cropped_img = nib.crop_image(img, [(50, 200), (50, 200), (50, 200)])
>> >>> cropped_img.shape
>> --> (150, 150, 150)
>>
>> If there isn't a function to do this, could you share a recipe for what
>> I'd need to do? My sense is I'd need to a) pass a cropped data array (easy)
>> b) change the data shape information in the header (easy) c) change the
>> fourth column of the affine matrix (tricky!)
>>
>> Thanks,
>> Michael
>>
>> _______________________________________________
>> Neuroimaging mailing list
>> Neuroimaging at python.org
>> https://mail.python.org/mailman/listinfo/neuroimaging
>>
>>
>
> _______________________________________________
> Neuroimaging mailing list
> Neuroimaging at python.org
> https://mail.python.org/mailman/listinfo/neuroimaging
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/neuroimaging/attachments/20170818/a0953c24/attachment.html>


More information about the Neuroimaging mailing list