How can I remove certain part in each slice of a Nifti image using Python?

86 Views Asked by At

I have a Nifti image (not labeled) with shape (512, 512, 299) I want to perform Unsupervised segmentation on this 3D image. However, the image contains bed area which are creating trouble for my clusters. I have tried clustering and the result is a clustered image with shape (512, 512)

2

There are 2 best solutions below

2
Bradley Duncan Junior On

Try this:

import numpy as np

# Load the Nifti image
nifti_file = 'your_image.nii.gz'
img = nib.load(nifti_file)
data = img.get_fdata()

# Define a function to remove the bed area from a single 2D slice
def remove_bed_area(slice_data):
    # Implement your logic here to remove the bed area
    # You might use thresholding, segmentation, or other techniques

    # For example, you can threshold the slice to remove dark areas
    threshold = 100  # Adjust this threshold as needed
    slice_data[slice_data < threshold] = 0

    return slice_data

# Process each slice in the 3D image
for slice_idx in range(data.shape[2]):
    data[:, :, slice_idx] = remove_bed_area(data[:, :, slice_idx])

# Create a new Nifti image with the modified data
modified_img = nib.Nifti1Image(data, img.affine)

# Save the modified Nifti image to a new file
modified_file = 'modified_image.nii.gz'
nib.save(modified_img, modified_file)
0
alle_meije On

Maybe try

import nibabel as nib;
img = nib.load ( "withbed.nii.gz" );
data = img.get_fdata();

removed_bed_area = data [ :200, 4:111, : ];
removed_bed_img  = nib.Nifti1Image( removed_bed_area, img.affine );
nib.save( removed_bed_img, "removed_bed.nii.gz" );

Mind that this is essentially the same answer as @BradleyDuncanJunior's (and the regions in my example are almost certainly incorrect, so I gave his answer an upvote.