示例#1
0
def myshow3d(img,
             xslices=[],
             yslices=[],
             zslices=[],
             title=None,
             margin=0.05,
             dpi=80):
    img_xslices = [img[s, :, :] for s in xslices]
    img_yslices = [img[:, s, :] for s in yslices]
    img_zslices = [img[:, :, s] for s in zslices]

    maxlen = max(len(img_xslices), len(img_yslices), len(img_zslices))

    img_null = sitk.Image([0, 0], img.GetPixelID(),
                          img.GetNumberOfComponentsPerPixel())

    img_slices = []
    d = 0

    if len(img_xslices):
        img_slices += img_xslices + [img_null] * (maxlen - len(img_xslices))
        d += 1

    if len(img_yslices):
        img_slices += img_yslices + [img_null] * (maxlen - len(img_yslices))
        d += 1

    if len(img_zslices):
        img_slices += img_zslices + [img_null] * (maxlen - len(img_zslices))
        d += 1

    if maxlen != 0:
        if img.GetNumberOfComponentsPerPixel() == 1:
            img = sitk.Tile(img_slices, [maxlen, d])
        # TO DO check in code to get Tile Filter working with vector images
        else:
            img_comps = []
            for i in range(0, img.GetNumberOfComponentsPerPixel()):
                img_slices_c = [
                    sitk.VectorIndexSelectionCast(s, i) for s in img_slices
                ]
                img_comps.append(sitk.Tile(img_slices_c, [maxlen, d]))
            img = sitk.Compose(img_comps)

    myshow(img, title, margin, dpi)
示例#2
0
# Add formula for it here.


def marschner_lobb(size=40, alpha=0.25, f_M=6.0):
    img = sitk.PhysicalPointSource(sitk.sitkVectorFloat32, [size] * 3,
                                   [-1] * 3, [2.0 / size] * 3)
    imgx = sitk.VectorIndexSelectionCast(img, 0)
    imgy = sitk.VectorIndexSelectionCast(img, 1)
    imgz = sitk.VectorIndexSelectionCast(img, 2)
    r = sitk.Sqrt(imgx**2 + imgy**2)
    pr = sitk.Cos((2.0 * math.pi * f_M) * sitk.Cos((math.pi / 2.0) * r))
    return (1.0 - sitk.Sin((math.pi / 2.0) * imgz) + alpha * (1.0 + pr)) / \
        (2.0 * (1.0 + alpha))


myshow(marschner_lobb(200), title='Marschner-Lobb Image')

##############################################################################
# Interpolations
# --------------
# Let's use ``Expand`` to rescale image by a factor of 5 in all dimensions.
#
# Compare these interpolations with the image above.

ml = marschner_lobb(40)
ml = ml[:, :, ml.GetSize()[-1] // 2]

myshow(sitk.Expand(ml, [5] * 3, sitk.sitkNearestNeighbor),
       title="nearest neighbor")
myshow(sitk.Expand(ml, [5] * 3, sitk.sitkLinear), title="linear")
myshow(sitk.Expand(ml, [5] * 3, sitk.sitkBSpline), title="b-spline")
示例#3
0
Get Images
----------
"""
import matplotlib.pyplot as plt
import SimpleITK as sitk
from downloaddata import fetch_data as fdata
from myshow import myshow

img_T1 = sitk.ReadImage(
    fdata("nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT1.nrrd"))
img_T2 = sitk.ReadImage(
    fdata("nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT2.nrrd"))
img_labels = sitk.ReadImage(
    fdata("nac-hncma-atlas2013-Slicer4Version/Data/hncma-atlas.nrrd"))

myshow(img_T1, title='T1')
myshow(img_T2, title='T2')
myshow(sitk.LabelToRGB(img_labels), title='lables')

##############################################################################
# Visualize another axis.

size = img_T1.GetSize()
myshow(img_T1[:, size[1] // 2, :])

##############################################################################
# Let's visualize all three orthogonal views. You can use ``sitk.Tile`` for
# tiling images.

slices = [
    img_T1[size[0] // 2, :, :], img_T1[:, size[1] // 2, :],
示例#4
0
superList = os.walk('')
for root, dirs, files in superList:
    for file in files:
        path = os.path.join(root, file)
        if path.endswith('.nrrd'):
            img = sitk.ReadImage(path)
            #myshow(img)
            size = img.GetSize()
            myshow3d(img,
                     yslices=range(50, size[1] - 50, 30),
                     zslices=range(50, size[2] - 50, 20),
                     dpi=30)
            plt.savefig(p + '\\' + file + '.png')
            plt.close()
#%%Save slices of segmented medical images in a loop
p = ('')
superList = os.walk('')
for root, dirs, files in superList:
    for file in files:
        path = os.path.join(root, file)
        if path.endswith('.mhd'):
            if file.endswith('segmentation.mhd'):
                imgLabel = sitk.ReadImage(path)
                img = sitk.ReadImage(path.replace('_segmentation.mhd', '.mhd'))
                size = img.GetSize()
                myshow(
                    sitk.LabelOverlay(floatToInt(setIntensity(img, 255)),
                                      floatToInt(setIntensity(imgLabel, 255))))
                plt.savefig(p + '\\' + file + '.png')
                plt.close()
示例#5
0
def create_snapshop(fileName_CT, fileName_segmentation, output_dir, patient,
                    study, struct_name):

    image_CT = sitk.ReadImage(fileName_CT)
    image_seg = sitk.ReadImage(fileName_segmentation)

    ## resample segmentation image with CT image
    identity = sitk.Transform(3, sitk.sitkIdentity)
    image_seg_resampled = sitk.Resample(image_seg, image_CT.GetSize(),
                                        identity, sitk.sitkNearestNeighbor,
                                        image_CT.GetOrigin(),
                                        image_CT.GetSpacing(),
                                        image_CT.GetDirection())

    ## get center of the segmentation (in physical space, then in image indices)
    statistics_label_filter = sitk.LabelShapeStatisticsImageFilter()
    statistics_label_filter.Execute(image_seg_resampled)
    centroid = statistics_label_filter.GetCentroid(1)
    #    print("Centroid : ", centroid)
    centroid_indices = list(centroid)
    for i in range(0, 3):
        centroid_indices[i] = int(
            (centroid[i] - image_CT.GetOrigin()[i]) / image_CT.GetSpacing()[i])

    ## cast CT image to char
    image_CT_256 = sitk.Cast(
        sitk.IntensityWindowing(image_CT,
                                windowMinimum=20 - 200,
                                windowMaximum=20 + 200), sitk.sitkUInt8)

    overlay_img = sitk.LabelOverlay(image_CT_256,
                                    image_seg_resampled,
                                    opacity=0.15)

    #    seg = sitk.Cast(image_seg_resampled, sitk.sitkLabelUInt8)
    #
    #    overlay_img_contour = sitk.LabelMapContourOverlay(seg, image_CT_256,opacity = 0.5,
    #                                                 contourThickness=[1,1,1]
    #                                              )
    #
    img_xslices = overlay_img[centroid_indices[0], :, :]
    img_yslices = overlay_img[:, centroid_indices[1], :]
    img_zslices = overlay_img[:, :, centroid_indices[2]]

    myshow(img_xslices,
           title=patient + " " + struct_name,
           invertX=True,
           zoom=2.5,
           save=output_dir + patient + "_" + study + "_" + struct_name +
           "1.png",
           figsize=(7, 7))
    myshow(img_yslices,
           title=patient + " " + struct_name,
           invertX=True,
           zoom=2.5,
           save=output_dir + patient + "_" + study + "_" + struct_name +
           "2.png",
           figsize=(7, 7))
    myshow(img_zslices,
           title=patient + " " + struct_name,
           invertY=True,
           save=output_dir + patient + "_" + study + "_" + struct_name +
           "3.png",
           figsize=(7, 7))

    plt.close("all")
示例#6
0
import matplotlib.pyplot as plt
import SimpleITK as sitk
from downloaddata import fetch_data as fdata
from myshow import myshow, myshow3d

##############################################################################
# LabelOverlay In 2D
# ------------------
# We start by loading a segmented image. As the segmentation is just an image
# with integral data, we can display the labels as we would any other image.

img1 = sitk.ReadImage(fdata("cthead1.png"))
img1_seg = sitk.ReadImage(fdata("2th_cthead1.png"))

myshow(img1, title="cthead1")
myshow(img1_seg, title="Label Image as Grayscale")

##############################################################################
# We can also map the scalar label image to a color image as shown below.

myshow(sitk.LabelToRGB(img1_seg), title="Label Image as RGB")

##############################################################################
# Most filters which take multiple images as arguments require that the images
# occupy the same physical space. That is the pixel you are operating must
# refer to the same location. Luckily for us our image and labels do occupy the
# same physical space, allowing us to overlay the segmentation onto the
# original image.

myshow(sitk.LabelOverlay(img1, img1_seg), title="Label Overlayed")
示例#7
0
# A number of other transforms exist to represent non-affine deformations,
# well-behaved rotation in 3D, etc. See the :doc:`Next guide` for more
# information.
#
# Applying Transforms to Images
# =============================
# Let's create a grid image to illustrate our transforms.

grid = sitk.GridSource(outputPixelType=sitk.sitkUInt16,
                       size=(250, 250),
                       sigma=(0.5, 0.5),
                       gridSpacing=(5.0, 5.0),
                       gridOffset=(0.0, 0.0),
                       spacing=(0.2, 0.2))

myshow(grid, 'Grid Input')

##############################################################################
# To apply the transform, a resampling operation is required.
#
# .. note::
#
#   Resample applies transform to phyiscal space, not voxel cordinates directly.
#   Once phyiscal space is transformed, you will need to specify how you view
#   this space by setting output origin, spacing and direction. Alternatively,
#   you can specify a reference image so that output origin, spacing and
#   direction are set to that of the reference image.
#
# In the following ``resample`` function, output image Origin, Spacing, Size,
# Direction are taken from the reference
示例#8
0
img_T1 = sitk.ReadImage(
    fdata("nac-hncma-atlas2013-Slicer4Version/Data/A1_grayT1.nrrd"))

# To visualize the labels image in RGB needs a image with 0-255 range
img_T1_255 = sitk.Cast(sitk.RescaleIntensity(img_T1), sitk.sitkUInt8)

size = img_T1.GetSize()
myshow3d(img_T1_255, zslices=range(50, size[2] - 50, 20))

##############################################################################
# Threshold
# ---------
# Let's pick a threshold 200 for thresholding.

seg = img_T1 > 200
myshow(sitk.LabelOverlay(img_T1_255, seg), "Basic Thresholding")

##############################################################################
# You can also use a upper and lower threshold.

seg = sitk.BinaryThreshold(img_T1,
                           lowerThreshold=100,
                           upperThreshold=400,
                           insideValue=1,
                           outsideValue=0)
myshow(sitk.LabelOverlay(img_T1_255, seg), "Binary Thresholding")

##############################################################################
# Otsu Thresholding
# -----------------
#