I have a dicom image but the image is padded. I have code to remove the padding from the image so that only the scan is left but I have to open the image using ImageJ and manually find min and max values for the x and y axis for where the image starts and ends. The scan has a gray value range of -3000 to 2000. The padded area has a value of 0. Is there a way to find these min and max values without having do it manually?
Original Image:

Desired Image:

Below a Python script using SimpleITK that crops out the background.
The basic idea is that it creates a mask image of pixels that are not the background value. Then it uses SimpleITK's LabelShapeStatisticsImageFilter to find the bounding box for the non-zero pixels in that mask image.
import SimpleITK as sitk
img = sitk.ReadImage("padded-image.png")
# Grey background in this example
bg_value = 161
# Create a mask image that is just non-background pixels
fg_mask = (img != bg_value)
# Compute shape statistics on the mask
lsif = sitk.LabelShapeStatisticsImageFilter()
lsif.Execute(fg_mask)
# Get the bounds of the mask.
# Bounds are given as [Xstart, Ystart, Xwidth, Ywidth]
bounds = lsif.GetBoundingBox(1)
print(bounds)
Xmin_crop = bounds[0]
Ymin_crop = bounds[1]
Xmax_crop = img.GetWidth() - (bounds[0]+bounds[2])
Ymax_crop = img.GetHeight() - (bounds[1]+bounds[3])
# Crop parameters are how much to crop off each side
cropped_img = sitk.Crop(img, [Xmin_crop, Ymin_crop], [Xmax_crop, Ymax_crop])
sitk.Show(cropped_img)
sitk.WriteImage(cropped_img, "cropped-image.png")
Because I used your 8-bit PNG image, the background value is set to 161. If you use your original 16-bit DICOM CT, you'd use a background value of 0. SimpleITK can read DICOM, along with a number of other image formats.
For more info about the LabelShapeStatisticsImageFilter class, here's the documentation: https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelShapeStatisticsImageFilter.html#details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With