Home > database >  Center cropping of 3D images for MRI images
Center cropping of 3D images for MRI images

Time:06-22

I have a list of 3D MRI images, and I would like to crop these images to the center so that I leave only the ROI, any suggestions on how to do that?

I tried the following code, but it returned the original size at the end... Any idea how to crop all the images with different dimensions to a center?

path1=(r"\*.*")
#ALL after resliced and resized 

#path_2(r"C")
#Reading multiple files ED images for all pateints 1 to 72 and reslice them to 3D. 
dimensions_img =np.zeros((len(glob.glob(path1)),3)) # this help to as counter 
for i, img in enumerate(sorted(glob.glob(path1))): 
    print(img)
    a= nib.load(img) 
    img_data = a.get_data()    
    #print(a.shape)
    if len(a.shape)== 4:# if the shape is 4
      resliced = img_data[:,:,:,0]
      print(resliced.shape)
      dimensions_img[i,:]=resliced.shape
      #print(dimensions_img)  
    #print(resliced.shape)
    #dimensions_img[i,:]=resliced.shape   
    #print(dimensions_img)      
    #new_dim = np.max(dimensions_img,axis=0).astype(int)
    #center = (new_dim/2).astype(int)      
    #new_image_zeros[int(center[0] - resliced.shape[0]/2):int(resliced.shape[0]/2 center[0]),int(center[1] - resliced.shape[1]/2):int(resliced.shape[1]/2 center[1]),int(center[2] - resliced.shape[2]/2):int(resliced.shape[2]/2 center[2])] =  resliced 

CodePudding user response:

You might try this function and loop over your 3D MRI volumes to apply it.

def crop3D(path_scan):
    start = (90,90) # You change the values here to fit well your ROI 
    end = (290,290)
    slices = tuple(map(slice, start, end))
    return scan[slices]

CodePudding user response:

A link to the dataset would be good, but posting a single image would be helpful too: makes it much easier for everyone to replicate your issue.

Normally with a numpy image you should be able to do something like this:

cropped_image = your_image[crop_y_start_index:cropy_y_stop_index,crop_x_start_index:crop_x_stop_index]

It may depend a bit on how the image is loaded / what the shape of the image numpy array is.

You would need to offset the start/end indices based on the image dimensions (and crop size).

Once you can crop one image, wrap that in a reusable function so you can apply different crop sizes per slice if you need to.

I'd recomment slowing down a bit, breaking the problem further, then confidentely moving forward:

  1. load a single image/slice
  2. crop a part of the image (can be 50x50 area at the top left: easy enough to work out image[0:50,0:50])
  3. if that works as expected: great, move to computing the start/end x and y crop coordinates to crop from centre, otherwise debug where the basic crop test fails. Once you can easily crop a slice from the centre with a given size, looping through all slices, adjusting the crop area as needed and cropping should be straight foward
  • Related