コード例 #1
0
def VisualizeReferenceSpectrum(rf_files, freq_sampling):
    plt.figure(1, figsize=(5, 4))
    handles = []
    labels = []
    for rf_file in rf_files:
        ComponentType = itk.ctype('float')
        Dimension = 2
        ImageType = itk.VectorImage[ComponentType, Dimension]
        reader = itk.ImageFileReader[ImageType].New(FileName=rf_file)
        reader.Update()
        image = reader.GetOutput()
        arr = itk.GetArrayFromImage(image)
        arr /= arr[:,:,arr.shape[2]/3-arr.shape[2]/5:arr.shape[2]/2+arr.shape[2]/5].max()
        freq = np.linspace(freq_sampling / 2 / arr.shape[2], freq_sampling / 2, arr.shape[2])
        ax = plt.plot(freq, arr[0, 0, :].ravel(), label=rf_file)
        handles.append(ax[0])
        labels.append(rf_file)
        plt.xlabel('Frequency [Hz]')
        plt.ylabel('Power spectrum [V]')
    plt.figlegend(handles, labels, 'upper right')
    plt.ylim(0.0, 1.0)

    dirname = os.path.dirname(rf_files[0])
    plt.savefig(os.path.join(dirname, 'ReferenceSpectrum.png'), dpi=300)
    plt.show()
コード例 #2
0
def Resample_Labels(labels_filepath, reference_path, output_path):

    PixelType = itk.ctype('unsigned char')
    Dimension = 2
    ImageType = itk.Image[PixelType, Dimension]

    basename = os.path.basename(labels_filepath).split('_ManualLabel')[0]

    labels_reader = itk.ImageFileReader[ImageType].New()
    labels_reader.SetFileName(labels_filepath)
    labels_reader.UpdateLargestPossibleRegion()

    reference_filepath_glob = os.path.join(os.path.dirname(labels_filepath),
            reference_path, basename + '*')
    reference_filepath = glob.glob(reference_filepath_glob)[0]
    reference_reader = itk.ImageFileReader[ImageType].New()
    reference_reader.SetFileName(reference_filepath)
    reference_reader.UpdateLargestPossibleRegion()

    resampler = itk.ResampleImageFilter[ImageType, ImageType].New()
    resampler.SetInput(labels_reader.GetOutput())
    resampler.SetReferenceImage(reference_reader.GetOutput())
    resampler.SetUseReferenceImage(True)
    resampler.UpdateLargestPossibleRegion()

    output_path = os.path.join(os.path.dirname(labels_filepath), output_path)
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    writer = itk.ImageFileWriter.New(resampler.GetOutput())
    writer.SetFileName(os.path.join(output_path, basename + '_ManualLabelResampled.mha'))
    writer.Update()
コード例 #3
0
def test_mesh_to_geometry():
    # 3D
    Dimension = 3
    PixelType = itk.ctype('double')
    MeshType = itk.Mesh[PixelType, Dimension]
    mesh = MeshType.New()
    PointType = itk.Point[itk.F, Dimension]
    point0 = PointType()
    point0[0] = -1
    point0[1] = -1
    point0[2] = 0
    mesh.SetPoint(0, point0)
    point1 = PointType()
    point1[0] = 1
    point1[1] = -1
    point1[2] = 0
    mesh.SetPoint(1, point1)
    point2 = PointType()
    point2[0] = 1
    point2[1] = 1
    point2[2] = 0
    mesh.SetPoint(2, point2)
    point3 = PointType()
    point3[0] = 1
    point3[1] = 1
    point3[2] = 0
    mesh.SetPoint(3, point3)

    geometry = to_geometry(mesh)

    points = mesh.GetPoints()
    point_template = itk.template(points)
    element_type = point_template[1][1]
    point_values = itk.PyVectorContainer[
        element_type].array_from_vector_container(points)

    assert (geometry['vtkClass'] == 'vtkPolyData')
    assert (geometry['points']['vtkClass'] == 'vtkPoints')
    assert (geometry['points']['numberOfComponents'] == 3)
    assert (geometry['points']['dataType'] == 'Float32Array')
    assert (geometry['points']['size'] == 4 * 3)
    assert (np.array_equal(geometry['points']['values'],
                           point_values.astype(np.float32)))
コード例 #4
0
ファイル: utils.py プロジェクト: celiale/fly-by-cnn
def GetImage(img_np):
    img_np_shape = np.shape(img_np)
    ComponentType = itk.ctype('float')

    Dimension = img_np.ndim - 1
    PixelDimension = img_np.shape[-1]
    print("Dimension:", Dimension, "PixelDimension:", PixelDimension)

    if Dimension == 1:
        OutputImageType = itk.VectorImage[ComponentType, 2]
    else:
        OutputImageType = itk.VectorImage[ComponentType, Dimension]

    out_img = OutputImageType.New()
    out_img.SetNumberOfComponentsPerPixel(PixelDimension)

    size = itk.Size[OutputImageType.GetImageDimension()]()
    size.Fill(1)

    prediction_shape = list(img_np.shape[0:-1])
    prediction_shape.reverse()

    if Dimension == 1:
        size[1] = prediction_shape[0]
    else:
        for i, s in enumerate(prediction_shape):
            size[i] = s

    index = itk.Index[OutputImageType.GetImageDimension()]()
    index.Fill(0)

    RegionType = itk.ImageRegion[OutputImageType.GetImageDimension()]
    region = RegionType()
    region.SetIndex(index)
    region.SetSize(size)

    out_img.SetRegions(region)
    out_img.Allocate()

    out_img_np = itk.GetArrayViewFromImage(out_img)
    out_img_np.setfield(img_np.reshape(out_img_np.shape), out_img_np.dtype)

    return out_img
コード例 #5
0
def readDICOMImage(dir, outPutDir, identifier):
    PixelType = itk.ctype('signed short')
    Dimension = 3

    ImageType = itk.Image[PixelType, Dimension]

    namesGenerator = itk.GDCMSeriesFileNames.New()
    namesGenerator.SetUseSeriesDetails(False)
    namesGenerator.SetGlobalWarningDisplay(False)
    namesGenerator.SetDirectory(dir)

    seriesUID = namesGenerator.GetSeriesUIDs()

    if len(seriesUID) < 1:
        print('ERROR: No DICOMS in folder' + dir)
        sys.exit(1)
    if len(seriesUID) > 1:
        print('ERROR: In folder are more series')
        sys.exit(1)
    print('DICOMs red OK from: ' + dir)

    # SHOULD BE just one
    for uid in seriesUID:
        seriesIdentifier = uid

        print('Reading: ' + seriesIdentifier)
        fileNames = namesGenerator.GetFileNames(seriesIdentifier)

        reader = itk.ImageSeriesReader[ImageType].New()
        dicomIO = itk.GDCMImageIO.New()
        reader.SetImageIO(dicomIO)
        reader.SetFileNames(fileNames)

        outFileName = 'DIC_' + identifier + '.nrrd'
        writer = itk.ImageFileWriter[ImageType].New()
        writer.SetFileName(outPutDir + '/' + outFileName)
        writer.UseCompressionOn()
        writer.SetInput(reader.GetOutput())

        print('Writing: ' + outPutDir + '/' + outFileName)
        writer.Update()

        return sitk.ReadImage(outPutDir + '/' + outFileName, sitk.sitkFloat32)
コード例 #6
0
def laplacian_recursive_gaussian_filter(image):
    '''
    reference: C++ version https://itk.org/ITKExamples/src/Filtering/ImageFeature/LaplacianRecursiveGaussianImageFilter/Documentation.html
    :param image: itk 3D image
    :return: itk 3D image
    '''
    input_pixel_type = itk.ctype('float')
    input_image_type = itk.Image[input_pixel_type, 3]
    filter = itk.LaplacianRecursiveGaussianImageFilter[input_image_type,
                                                       input_image_type].New()
    filter.SetInput(image)
    filter.Update()
    result = filter.GetOutput()
    # rescale_filter = itk.RescaleIntensityImageFilter[input_image_type,input_image_type].New()
    # rescale_filter.SetInput(result)
    # outputPixelTypeMinimum = itk.NumericTraits[input_image_type].min()
    # outputPixelTypeMaximum = itk.NumericTraits[input_image_type].max()
    #
    #
    return result
コード例 #7
0
def read_dicom_series(patient_dir):
    '''
    given a image dir
    return itk image
    :param patient_dir:
    :return:
    '''
    input_pixel_type = itk.ctype('float')
    image_type = itk.Image[input_pixel_type, 3]
    reader = itk.ImageSeriesReader[image_type].New()
    gdcm_io = itk.GDCMImageIO.New()
    reader.SetImageIO(gdcm_io)
    names_generator = itk.GDCMSeriesFileNames.New()
    names_generator.SetInputDirectory(patient_dir)
    file_names = names_generator.GetInputFileNames()
    reader.SetFileNames(file_names)
    try:
        reader.Update()
    except:
        raise
    return reader.GetOutput()
コード例 #8
0
def create_itk_image(dimension, pixel_string, image_region):
    '''Create an ITK image.

    No checks are performed to guarantee the inputs are valid
    inputs.

    Args:
        dimension (int):                Image dimensions
        pixel_string (string):          The pixel type as a string
        image_region (itk.ImageRegion): The image region over which the image is defined

    Returns:
        itk.Image:                      The created ITK image
    '''
    pixel_type = itk.ctype(pixel_string)
    image_type = itk.Image[pixel_type, dimension]
    image = image_type.New()
    image.SetRegions(image_region)
    image.Allocate()

    return image
    def test_create_3d_image_successful(self):
        '''Test that create_itk_image can create a 3D image.'''
        # Parameters
        dimension = 3
        pixel_string = 'unsigned char'
        pixel_type = itk.ctype(pixel_string)
        image_type = itk.Image[pixel_type, dimension]
        this_image = image_type.New()

        start = itk.Index[dimension]()
        start[0] = 0  # first index on X
        start[1] = 0  # first index on Y
        start[2] = 0  # first index on Z

        size = itk.Size[dimension]()
        size[0] = 200  # size along X
        size[1] = 200  # size along Y
        size[2] = 200  # size along Z

        image_region = itk.ImageRegion[dimension]()
        image_region.SetSize(size)
        image_region.SetIndex(start)

        this_image.SetRegions(image_region)
        this_image.Allocate()

        # Call method
        created_image = create_itk_image(dimension, pixel_string, image_region)

        # Need to compare the components
        self.assertEqual(this_image.GetImageDimension(),
                         created_image.GetImageDimension())
        self.assertEqual(this_image.GetDirection(),
                         created_image.GetDirection())
        self.assertEqual(this_image.GetLargestPossibleRegion(), \
          created_image.GetLargestPossibleRegion())
        self.assertEqual(this_image.GetOrigin(), created_image.GetOrigin())
        self.assertEqual(this_image.GetSpacing(), created_image.GetSpacing())
コード例 #10
0
def image_convert(inputImage, pixeltype=None):
    """
    Compute relative statistical uncertainty 

    - inputImage: input itk image to convert
    - pixeltype: string representing the type of the output pixel:
        - unsigned char
        - signed short
        - unsigned short
        - float
    """

    #If pixel type is not None, convert it,
    #If None it could be a type conversion without pixel conversion
    if pixeltype is not None:
        InputType = type(inputImage)
        OutputType = itk.Image[itk.ctype(pixeltype),
                               inputImage.GetImageDimension()]
        castFilter = itk.CastImageFilter[InputType, OutputType].New()
        castFilter.SetInput(inputImage)
        return castFilter

    return inputImage
コード例 #11
0
def VisualizePixelSpectrum(spectra_file, freq_sampling, index):
    plt.figure(1, figsize=(5, 4))
    handles = []
    labels = []
    ComponentType = itk.ctype('float')
    Dimension = 2
    ImageType = itk.VectorImage[ComponentType, Dimension]
    reader = itk.ImageFileReader[ImageType].New(FileName=spectra_file)
    reader.Update()
    image = reader.GetOutput()
    arr = itk.GetArrayFromImage(image)
    freq = np.linspace(freq_sampling / 2 / arr.shape[2], freq_sampling / 2, arr.shape[2])
    ax = plt.plot(freq, arr[index[1], index[0], :].ravel(), label=spectra_file)
    handles.append(ax[0])
    labels.append(spectra_file)
    plt.xlabel('Frequency [Hz]')
    plt.ylabel('Power spectral density')
    plt.figlegend(handles, labels, 'upper right')
    plt.ylim(0.0, 2.0)

    dirname = os.path.dirname(spectra_file)
    # plt.savefig(os.path.join(dirname, 'PixelSpectrum.png'), dpi=300)
    plt.show()
コード例 #12
0
def canny_filter(image, variance, lower_threshold, upper_threshold):
    '''
    reference: C++ version https://itk.org/ITKExamples/src/Filtering/ImageFeature/SobelEdgeDetectionImageFilter/Documentation.html
    This filter is an implementation of a Canny edge detector for scalar-valued images.
    :param image: itk 3D image
    :param variance:Variance are used in the Gaussian smoothing
    :param lower_threshold:lower_threshold is the lowest allowed value in the output image.
    :param upper_threshold: values below the Threshold level will be replaced with the OutsideValue parameter value, whose default is zero.
    :return:itk 3D image
    '''

    input_pixel_type = itk.ctype('float')
    input_image_type = itk.Image[input_pixel_type, 3]
    filter = itk.CannyEdgeDetectionImageFilter[input_image_type,
                                               input_image_type].New()
    filter.SetInput(image)
    filter.SetVariance(variance)
    filter.SetLowerThreshold(lower_threshold)
    filter.SetUpperThreshold(upper_threshold)
    filter.Update()
    result = filter.GetOutput()

    return result
コード例 #13
0
    def setUp(self):
        '''Set up for TestGetITKImageType'''
        # Create a temporary directory
        self.test_dir = tempfile.mkdtemp()

        # Create an image with a known orientation
        pixel_types_as_strings = ['short', 'unsigned short', 'unsigned char']
        dimensions = [2, 3]
        extensions = ['nii', 'nii.gz', 'mhd', 'nrrd']

        # Create a bunch of files
        self.image_type_map = {}
        self.file_names = []
        for pixel_type_as_string in pixel_types_as_strings:
            for dimension in dimensions:
                # Create image
                index = [0 for x in range(dimension)]
                size = [10 for x in range(dimension)]
                image_region = create_itk_image_region(dimension, index, size)
                image = create_itk_image(dimension, pixel_type_as_string,
                                         image_region)

                image_type = itk.Image[itk.ctype(pixel_type_as_string),
                                       dimension]

                for extension in extensions:
                    # Create file name
                    file_name = os.path.join(
                        self.test_dir,
                        'image_{}_{}.{}'.format(pixel_type_as_string,
                                                dimension, extension))
                    self.file_names.append(file_name)
                    self.image_type_map[file_name] = image_type

                    # Write image out
                    itk.imwrite(image, file_name)
コード例 #14
0
    def test_NumPyBridge_FortranOrder(self):
        "Try to convert an ITK image to / from a NumPy array with Fortran order"

        Dimension = 2
        PixelType = itk.ctype('signed short')
        ImageType = itk.Image[PixelType, Dimension]
        dtype = np.int16

        arr = np.arange(6, dtype=dtype)
        arrC = np.reshape(arr, (2, 3), order='C')
        assert(arrC.flags.c_contiguous)
        image = itk.PyBuffer[ImageType].GetImageViewFromArray(arrC)

        index = itk.Index[Dimension]()
        index[0] = 0
        index[1] = 0
        assert(image.GetPixel(index) == 0)
        index[0] = 1
        index[1] = 0
        assert(image.GetPixel(index) == 1)
        index[0] = 0
        index[1] = 1
        assert(image.GetPixel(index) == 3)

        arrFortran = np.reshape(arr, (3, 2), order='F')
        assert(arrFortran.flags.f_contiguous)
        image = itk.PyBuffer[ImageType].GetImageViewFromArray(arrFortran)
        index[0] = 0
        index[1] = 0
        assert(image.GetPixel(index) == 0)
        index[0] = 1
        index[1] = 0
        assert(image.GetPixel(index) == 1)
        index[0] = 0
        index[1] = 1
        assert(image.GetPixel(index) == 3)
コード例 #15
0
    def test_NumPyBridge_FortranOrder(self):
        "Try to convert an ITK image to / from a NumPy array with Fortran order"

        Dimension = 2
        PixelType = itk.ctype('signed short')
        ImageType = itk.Image[PixelType, Dimension]
        dtype = np.int16

        arr = np.arange(6, dtype=dtype)
        arrC = np.reshape(arr, (2, 3), order='C')
        assert (arrC.flags.c_contiguous)
        image = itk.PyBuffer[ImageType].GetImageViewFromArray(arrC)

        index = itk.Index[Dimension]()
        index[0] = 0
        index[1] = 0
        assert (image.GetPixel(index) == 0)
        index[0] = 1
        index[1] = 0
        assert (image.GetPixel(index) == 1)
        index[0] = 0
        index[1] = 1
        assert (image.GetPixel(index) == 3)

        arrFortran = np.reshape(arr, (3, 2), order='F')
        assert (arrFortran.flags.f_contiguous)
        image = itk.PyBuffer[ImageType].GetImageViewFromArray(arrFortran)
        index[0] = 0
        index[1] = 0
        assert (image.GetPixel(index) == 0)
        index[0] = 1
        index[1] = 0
        assert (image.GetPixel(index) == 1)
        index[0] = 0
        index[1] = 1
        assert (image.GetPixel(index) == 3)
コード例 #16
0
ファイル: Code.py プロジェクト: xiaogengen-007/ITKExamples
# limitations under the License.

import argparse

import itk
from distutils.version import StrictVersion as VS
if VS(itk.Version.GetITKVersion()) < VS("5.0.0"):
    print("ITK 5.0.0 or newer is required.")
    sys.exit(1)

parser = argparse.ArgumentParser(description='Segment blood vessels.')
parser.add_argument('input_image')
parser.add_argument('output_image')
parser.add_argument('--sigma', type=float, default=1.0)
parser.add_argument('--alpha1', type=float, default=0.5)
parser.add_argument('--alpha2', type=float, default=2.0)
args = parser.parse_args()

input_image = itk.imread(args.input_image, itk.ctype('float'))

hessian_image = itk.hessian_recursive_gaussian_image_filter(input_image,
                                                            sigma=args.sigma)

vesselness_filter = itk.Hessian3DToVesselnessMeasureImageFilter[itk.ctype(
    'float')].New()
vesselness_filter.SetInput(hessian_image)
vesselness_filter.SetAlpha1(args.alpha1)
vesselness_filter.SetAlpha2(args.alpha2)

itk.imwrite(vesselness_filter, args.output_image)
コード例 #17
0
from distutils.version import StrictVersion as VS

if VS(itk.Version.GetITKVersion()) < VS("4.9.0"):
    print("ITK 4.9.0 is required.")
    sys.exit(1)

parser = argparse.ArgumentParser(
    description="Perform 2D Translation Registration With Mean Squares.")
parser.add_argument("fixed_input_image")
parser.add_argument("moving_input_image")
parser.add_argument("output_image")
parser.add_argument("difference_image_after")
parser.add_argument("difference_image_before")
args = parser.parse_args()

PixelType = itk.ctype("float")

fixedImage = itk.imread(args.fixed_input_image, PixelType)
movingImage = itk.imread(args.moving_input_image, PixelType)

Dimension = fixedImage.GetImageDimension()
FixedImageType = itk.Image[PixelType, Dimension]
MovingImageType = itk.Image[PixelType, Dimension]

TransformType = itk.TranslationTransform[itk.D, Dimension]
initialTransform = TransformType.New()

optimizer = itk.RegularStepGradientDescentOptimizerv4.New(
    LearningRate=4,
    MinimumStepLength=0.001,
    RelaxationFactor=0.5,
コード例 #18
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itk

Dimension = 3
ComponentType = itk.ctype('float')
PixelType = itk.Vector[ComponentType, Dimension]
ImageType = itk.Image[PixelType, Dimension]

image = ImageType.New()

start = itk.Index[Dimension]()
start[0] = 0
start[1] = 0
start[2] = 0

size = itk.Size[Dimension]()
size[0] = 200
size[1] = 200
size[2] = 200
コード例 #19
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import itk

if len(sys.argv) != 4:
    print('Usage: ' + sys.argv[0] +
          ' input3DImageFile  output3DImageFile  sliceNumber')
    sys.exit(1)
inputFilename = sys.argv[1]
outputFilename = sys.argv[2]

Dimension = 3
PixelType = itk.ctype('short')
ImageType = itk.Image[PixelType, Dimension]

reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(inputFilename)
reader.Update()
inputImage = reader.GetOutput()

extractFilter = itk.ExtractImageFilter.New(inputImage)
extractFilter.SetDirectionCollapseToSubmatrix()

# set up the extraction region [one slice]
inputRegion = inputImage.GetBufferedRegion()
size = inputRegion.GetSize()
size[2] = 1  # we extract along z direction
start = inputRegion.GetIndex()
コード例 #20
0
def MotionCorrect(fixedImageFile,movingImageFile):

    PixelType = itk.ctype('float')
    
    fixedImage = itk.GetImageViewFromArray(fixedImageFile)
    movingImage = itk.GetImageViewFromArray(movingImageFile)
#    fixedImage = itk.imread(fixedImageFile, PixelType)
#    movingImage = itk.imread(movingImageFile, PixelType)

    Dimension = fixedImage.GetImageDimension()
    FixedImageType = itk.Image[PixelType, Dimension]
    MovingImageType = itk.Image[PixelType, Dimension]
    
    TransformType = itk.TranslationTransform[itk.D, Dimension]
    initialTransform = TransformType.New()
    
    optimizer = itk.RegularStepGradientDescentOptimizerv4.New(
            LearningRate=4,
            MinimumStepLength=0.001,
            RelaxationFactor=0.5,
            NumberOfIterations=200)
    
    metric = itk.MeanSquaresImageToImageMetricv4[
        FixedImageType, MovingImageType].New()
    
    registration = itk.ImageRegistrationMethodv4.New(FixedImage=fixedImage,
            MovingImage=movingImage,
            Metric=metric,
            Optimizer=optimizer,
            InitialTransform=initialTransform)
    
    movingInitialTransform = TransformType.New()
    initialParameters = movingInitialTransform.GetParameters()
    initialParameters[0] = 0
    initialParameters[1] = 0
    movingInitialTransform.SetParameters(initialParameters)
    registration.SetMovingInitialTransform(movingInitialTransform)
    
    identityTransform = TransformType.New()
    identityTransform.SetIdentity()
    registration.SetFixedInitialTransform(identityTransform)
    
    registration.SetNumberOfLevels(1)
    registration.SetSmoothingSigmasPerLevel([0])
    registration.SetShrinkFactorsPerLevel([1])
    
    registration.Update()
    
#    transform = registration.GetTransform()
#    finalParameters = transform.GetParameters()
#    translationAlongX = finalParameters.GetElement(0)
#    translationAlongY = finalParameters.GetElement(1)
#    
#    numberOfIterations = optimizer.GetCurrentIteration()
#    
#    bestValue = optimizer.GetValue()
    
#    print("Result = ")
#    print(" Translation X = " + str(translationAlongX))
#    print(" Translation Y = " + str(translationAlongY))
#    print(" Iterations    = " + str(numberOfIterations))
#    print(" Metric value  = " + str(bestValue))
    
    CompositeTransformType = itk.CompositeTransform[itk.D, Dimension]
    outputCompositeTransform = CompositeTransformType.New()
    outputCompositeTransform.AddTransform(movingInitialTransform)
    outputCompositeTransform.AddTransform(registration.GetModifiableTransform())
    
    resampler = itk.ResampleImageFilter.New(Input=movingImage,
            Transform=outputCompositeTransform,
            UseReferenceImage=True,
            ReferenceImage=fixedImage)
    resampler.SetDefaultPixelValue(100)
    
    OutputImageType = itk.Image[PixelType, Dimension]
    
    caster = itk.CastImageFilter[FixedImageType,
            OutputImageType].New(Input=resampler)
    
    outputImageFile = itk.GetArrayFromImage(caster)
#    writer = itk.ImageFileWriter.New(Input=caster, FileName=outputImageFile)
#    writer.SetFileName(outputImageFile)
#    writer.Update()
    return outputImageFile
def Estimate_USRF_ReferenceSpectrum(input_filepath, side_lines=5, fft1D_size=128,
        subregion_depth_fraction=1.0):

    InputPixelType = itk.ctype('float')
    Dimension = 2
    ImageType = itk.Image[InputPixelType, Dimension]

    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(input_filepath)
    input_RF = reader.GetOutput()
    # Apply missing spacing information
    if 'LinearProbe' in input_filepath:
        change_information = itk.ChangeInformationImageFilter.New(input_RF)
        change_information.SetUseReferenceImage(True)
        change_information.SetChangeSpacing(True)
        output_spacing = [1.0, 1.0]
        size = itk.size(input_RF)
        sos = 1540.
        fs = 30000.
        output_spacing[0] = sos / (2 * fs)
        transducer_width = 30.0
        output_spacing[1] = transducer_width / (size[1] - 1)
        change_information.SetOutputSpacing(output_spacing)
        input_RF = change_information.GetOutput()
    input_RF.UpdateOutputInformation()

    # Look for the peak signal amplitude in a sub-region
    subregion_filter = itk.RegionOfInterestImageFilter.New(input_RF)
    subregion = itk.region(input_RF)
    input_size = itk.size(input_RF)
    input_index = itk.index(input_RF)
    # Skip the initial 10% of the beamline, which is in the nearfield
    subregion_index = itk.Index[Dimension]()
    subregion_index[0] = int(input_size[0] * 0.1)
    subregion_index[1] = input_index[1]
    subregion.SetIndex(subregion_index)
    subregion_size = itk.Size[Dimension]()
    subregion_size[0] = input_size[0] - subregion_index[0]
    subregion_size[0] = subregion_size[0] - int((1. - subregion_depth_fraction) * subregion_size[0])
    subregion_size[1] = input_size[1]
    subregion.SetSize(subregion_size)
    subregion_filter.SetRegionOfInterest(subregion)
    subregion_filter.UpdateLargestPossibleRegion()
    subregion_image = subregion_filter.GetOutput()

    max_calculator = itk.MinimumMaximumImageCalculator.New(subregion_image)
    max_calculator.ComputeMaximum()
    max_index = max_calculator.GetIndexOfMaximum()

    SideLinesPixelType = itk.ctype('unsigned char')
    SideLinesImageType = itk.Image[SideLinesPixelType, Dimension]
    side_lines_image = SideLinesImageType.New()
    side_lines_image.CopyInformation(subregion_image)
    side_lines_image.SetRegions(subregion_image.GetLargestPossibleRegion())
    side_lines_image.Allocate()
    side_lines_image.FillBuffer(side_lines)

    spectra_window_filter = itk.Spectra1DSupportWindowImageFilter.New(side_lines_image)
    spectra_window_filter.SetFFT1DSize(fft1D_size)

    spectra_filter = itk.Spectra1DImageFilter.New(subregion_filter)
    spectra_filter.SetSupportWindowImage(spectra_window_filter.GetOutput())
    spectra_filter.UpdateLargestPossibleRegion()

    reference_spectrum_filter = itk.RegionOfInterestImageFilter.New(spectra_filter)
    reference_spectrum_region = itk.region(spectra_filter.GetOutput())
    reference_spectrum_region.SetIndex(max_index)
    reference_spectrum_size = itk.Size[Dimension]()
    reference_spectrum_size.Fill(1)
    reference_spectrum_region.SetSize(reference_spectrum_size)
    reference_spectrum_filter.SetRegionOfInterest(reference_spectrum_region)

    input_dir, input_file = os.path.split(input_filepath)
    output_dir = os.path.join(input_dir, 'ReferenceSpectrum')
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    input_filename, input_fileext = os.path.splitext(input_file)
    identifier = '_ReferenceSpectrum_side_lines_{:02d}_fft1d_size_{:03d}.mha'.format(side_lines, fft1D_size)
    output_file = os.path.join(output_dir, input_filename + identifier)

    writer = itk.ImageFileWriter.New(reference_spectrum_filter)
    writer.SetFileName(output_file)
    writer.SetUseCompression(True)
    writer.Update()
コード例 #22
0
#        since higher values quickly start to undersegment the image.

import itk
import argparse

parser = argparse.ArgumentParser(
    description="Segment With Watershed Image Filter.")
parser.add_argument("input_image")
parser.add_argument("output_image")
parser.add_argument("threshold", type=float)
parser.add_argument("level", type=float)
args = parser.parse_args()

Dimension = 2

FloatPixelType = itk.ctype("float")
FloatImageType = itk.Image[FloatPixelType, Dimension]

reader = itk.ImageFileReader[FloatImageType].New()
reader.SetFileName(args.input_image)

gradientMagnitude = itk.GradientMagnitudeImageFilter.New(
    Input=reader.GetOutput())

watershed = itk.WatershedImageFilter.New(Input=gradientMagnitude.GetOutput())

threshold = args.threshold
level = args.level
watershed.SetThreshold(threshold)
watershed.SetLevel(level)
コード例 #23
0
ファイル: itkutils.py プロジェクト: serval2412/tomviz
def vtk_cast_map():
    """Set up mapping between VTK array numeric types to VTK numeric types
    that correspond to supported ITK numeric ctypes supported by the ITK
    wrapping."""
    global _vtk_cast_types

    if _vtk_cast_types is None:
        import itk
        _vtk_cast_types = {}

        # Map from VTK array type to list of possible types to which they can be
        # converted, listed in order of preference based on representability
        # and memory size required.
        import vtk
        type_map = {
            vtk.VTK_UNSIGNED_CHAR: [
                'unsigned char',
                'unsigned short',
                'unsigned int',
                'unsigned long',
                'signed short',
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_CHAR: [
                'signed char',
                'signed short',
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_SIGNED_CHAR: [
                'signed char',
                'signed short',
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_UNSIGNED_SHORT: [
                'unsigned short',
                'unsigned int',
                'unsigned long',
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_SHORT: [
                'signed short',
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_UNSIGNED_INT: [
                'unsigned int',
                'unsigned long',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_INT: [
                'signed int',
                'signed long',
                'float',
                'double'
            ],
            vtk.VTK_FLOAT: [
                'float',
                'double'
            ],
            vtk.VTK_DOUBLE: [
                'double',
                'float'
            ]
        }

        # Map ITK ctype back to VTK type
        ctype_to_vtk = {
            'unsigned char': vtk.VTK_UNSIGNED_CHAR,
            'signed char': vtk.VTK_CHAR,
            'unsigned short': vtk.VTK_UNSIGNED_SHORT,
            'signed short': vtk.VTK_SHORT,
            'unsigned int': vtk.VTK_UNSIGNED_INT,
            'signed int': vtk.VTK_INT,
            'unsigned long': vtk.VTK_UNSIGNED_LONG,
            'signed long': vtk.VTK_LONG,
            'float': vtk.VTK_FLOAT,
            'double': vtk.VTK_DOUBLE
        }

        # Import build options from ITK. Explicitly reference itk.Vector so
        # that the itk::Vector type information is available when
        # itk.BuildOptions is imported, otherwise we get an exception when
        # importing itkBuildOptions. This is a workaround for a bug in ITK.
        itk.Vector
        import itkBuildOptions

        # Select the best supported type available in the wrapping.
        for (vtk_type, possible_image_types) in py2to3.iteritems(type_map):
            type_map[vtk_type] = None
            for possible_type in possible_image_types:
                if itk.ctype(possible_type) in itkBuildOptions.SCALARS:
                    _vtk_cast_types[vtk_type] = ctype_to_vtk[possible_type]
                    break

    return _vtk_cast_types
コード例 #24
0
                        label_map = np.array(label_map)
                        assign_img = "label_map=label_map[0:1," + ",".join(
                            prediction_shape) + "]"
                        exec(assign_img)

                    #THE NUMBER OF CHANNELS OF THE OUTPUT ARE GIVEN BY THE NEURAL NET

                    Dimension = itk.template(img)[1][1]

                    label_map = np.array(label_map[0][0])
                    PixelDimension = label_map.shape[-1]

                    if (PixelDimension < 7):
                        if (PixelDimension >= 3 and os.path.splitext(
                                img_obj["out"])[1] not in ['.jpg', '.png']):
                            ComponentType = itk.ctype('float')
                            PixelType = itk.Vector[ComponentType,
                                                   PixelDimension]
                        elif (PixelDimension == 3):
                            PixelType = itk.RGBPixel.UC
                            label_map = np.absolute(label_map)
                            label_map = np.around(label_map).astype(np.uint16)
                        else:
                            PixelType = itk.ctype(out_ctype)
                            # label_map = np.absolute(label_map)
                            # label_map = np.around(label_map).astype(np.uint16)

                        OutputImageType = itk.Image[PixelType, Dimension]
                        out_img = OutputImageType.New()

                    else:
コード例 #25
0
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itk
import platform

Dimension = 3
CoordType = itk.ctype('float')
# Windows requires unsigned long long for 64-bit identifiers
if platform.system() == 'Windows':
    ElementIdentifierType = itk.ctype('unsigned long long')
else:
    ElementIdentifierType = itk.ctype('unsigned long')


PointSetType = itk.PointSet[CoordType, Dimension]

pointSet = PointSetType.New()
points = pointSet.GetPoints()

# Create points
p0 = itk.Point[CoordType, Dimension]()
p1 = itk.Point[CoordType, Dimension]()
コード例 #26
0
def Convert_USRF_BMode(inputFilePath):

    Input_Dir, Input_File = os.path.split(inputFilePath)
    Input_FileName, Input_FileExt = os.path.splitext(Input_File)

    ## Set Output Dir
    Out_Dir = Input_Dir +'/BMode/'
    if not os.path.exists(Out_Dir):
        os.makedirs(Out_Dir)

    ## Load RF data
    InputPixelType = itk.ctype('float')
    Dimension = 2
    ImageType = itk.Image[InputPixelType, Dimension]
    direction = 0

    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(inputFilePath)

    # Remove low frequency artifacts on the Interson array probe
    filterFunction = itk.ButterworthBandpass1DFilterFunction.New()
    # < 2 MHz
    filterFunction.SetLowerFrequency( 0.12 )
    filterFunction.SetOrder( 7 )
    ComplexPixelType = itk.complex[InputPixelType]
    ComplexImageType = itk.Image[ComplexPixelType, Dimension]
    frequencyFilter = itk.FrequencyDomain1DImageFilter[ComplexImageType,
            ComplexImageType].New()
    frequencyFilter.SetDirection(direction)
    filterFunctionBase = itk.FrequencyDomain1DFilterFunction.New()
    frequencyFilter.SetFilterFunction(filterFunctionBase.cast(filterFunction))

    ## Generate Pre-Scanconversion Data from the RF file
    bMode_Filter = itk.BModeImageFilter[ImageType, ImageType].New()
    bMode_Filter.SetInput(reader.GetOutput())
    bMode_Filter.SetDirection(direction)
    bMode_Filter.SetFrequencyFilter(frequencyFilter)
    bMode_Filter.Update()
    bMode = bMode_Filter.GetOutput()

    writerInput = bMode
    # Apply missing spacing information
    if 'LinearProbe' in inputFilePath:
        changeInformation = itk.ChangeInformationImageFilter.New(bMode)
        changeInformation.SetUseReferenceImage(True)
        changeInformation.SetChangeSpacing(True)
        output_spacing = [1.0, 1.0]
        size = itk.size(bMode)
        sos = 1540.
        fs = 30000.
        output_spacing[0] = sos / (2 * fs)
        transducer_width = 30.0
        output_spacing[1] = transducer_width / (size[1] - 1)
        changeInformation.SetOutputSpacing(output_spacing)
        writerInput = changeInformation.GetOutput()

    outputFilePath = Out_Dir + Input_FileName + '_BMode.mha'
    print(outputFilePath)
    writer = itk.ImageFileWriter[ImageType].New()
    writer.SetFileName(outputFilePath)
    writer.SetInput(writerInput)
    writer.SetUseCompression(True)
    writer.Update()
コード例 #27
0
#          http://www.apache.org/licenses/LICENSE-2.0.txt
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ==========================================================================*/

import itk
import sys

itk.auto_progress(2)

PixelType = itk.ctype("float")
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(sys.argv[1])

diffusion = itk.GradientAnisotropicDiffusionImageFilter.New(Input=reader.GetOutput())
diffusion.SetTimeStep(0.0625)
diffusion.SetConductanceParameter(9.0)
diffusion.SetNumberOfIterations(5)

gradient = itk.GradientMagnitudeImageFilter.New(Input=diffusion.GetOutput())

watershed = itk.WatershedImageFilter.New(Input=gradient.GetOutput())
watershed.SetThreshold(0.01)
watershed.SetLevel(0.2)
コード例 #28
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

import itk
from distutils.version import StrictVersion as VS
if VS(itk.Version.GetITKVersion()) < VS("5.0.0"):
    print("ITK 5.0.0 or newer is required.")
    sys.exit(1)

parser = argparse.ArgumentParser(description='Segment blood vessels.')
parser.add_argument('input_image')
parser.add_argument('output_image')
parser.add_argument('--sigma', type=float, default=1.0)
parser.add_argument('--alpha1', type=float, default=0.5)
parser.add_argument('--alpha2', type=float, default=2.0)
args = parser.parse_args()

input_image = itk.imread(args.input_image, itk.ctype('float'))

hessian_image = itk.hessian_recursive_gaussian_image_filter(input_image, sigma=args.sigma)

vesselness_filter = itk.Hessian3DToVesselnessMeasureImageFilter[itk.ctype('float')].New()
vesselness_filter.SetInput(hessian_image)
vesselness_filter.SetAlpha1(args.alpha1)
vesselness_filter.SetAlpha2(args.alpha2)

itk.imwrite(vesselness_filter, args.output_image)
コード例 #29
0
ファイル: Code.py プロジェクト: jhlegarreta/ITKExamples
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import itk
import argparse

parser = argparse.ArgumentParser(
    description="Overlay Label Map On Top Of An Image.")
parser.add_argument("input_image")
parser.add_argument("label_map")
parser.add_argument("output_image")
args = parser.parse_args()

PixelType = itk.ctype("unsigned char")
Dimension = 2

ImageType = itk.Image[PixelType, Dimension]

reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(args.input_image)

labelReader = itk.ImageFileReader[ImageType].New()
labelReader.SetFileName(args.label_map)

LabelType = itk.ctype("unsigned long")
LabelObjectType = itk.StatisticsLabelObject[LabelType, Dimension]
LabelMapType = itk.LabelMap[LabelObjectType]

converter = itk.LabelImageToLabelMapFilter[ImageType, LabelMapType].New()
コード例 #30
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itk
import argparse

parser = argparse.ArgumentParser(
    description="Process A 2D Slice Of A 3D Image.")
parser.add_argument("input_3D_image")
parser.add_argument("output_3D_image")
parser.add_argument("slice_number", type=int)
args = parser.parse_args()

Dimension = 3
PixelType = itk.ctype("short")
ImageType = itk.Image[PixelType, Dimension]

reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(args.input_3D_image)
reader.Update()
inputImage = reader.GetOutput()

extractFilter = itk.ExtractImageFilter.New(inputImage)
extractFilter.SetDirectionCollapseToSubmatrix()

# set up the extraction region [one slice]
inputRegion = inputImage.GetBufferedRegion()
size = inputRegion.GetSize()
size[2] = 1  # we extract along z direction
start = inputRegion.GetIndex()
コード例 #31
0
#%%

if __name__ == "__main__":

  args = parse_args()
  DicomDir = args.indir
  outdir = args.outdir

  # Parameters
  sigmaSmallScale = 1.5
  sigmasLargeScale = [0.6, 0.8]
  lowerThreshold = 25
  upperThreshold = 600

  # Useful shortcut
  ShortType = itk.ctype('short')
  UShortType = itk.ctype('unsigned short')
  UCType = itk.ctype('unsigned char')
  FType = itk.ctype('float')
  ULType = itk.ctype('unsigned long')
  FloatImageType = itk.Image[FType,3]
  ShortImageType = itk.Image[ShortType,3]
  UCImageType = itk.Image[UCType,3]
  ULImageType = itk.Image[ULType,3]

  # Read Dicoms Series and turn it into 3D object
  inputCT, Inputmetadata = dicomsTo3D(DicomDir, ShortType)
  # showSome(inputCT,50)

  print("Preprocessing")
#%%
コード例 #32
0
#!/usr/bin/env python

# Copyright Insight Software Consortium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itk

Dimension = 2
RGBPixelType = itk.RGBPixel[itk.ctype('unsigned char')]

image = itk.Image[RGBPixelType, Dimension].New()
コード例 #33
0
import numpy as np
import time
import itk

start = time.time()
# PixelType = itk.ctype('unsigned short')

# ImageType = itk.Image[PixelType, Dimension]

Dimension = 3
RealType = itk.ctype('float')
RealImageType = itk.Image[RealType, Dimension]
LabelImageType = itk.Image[itk.ctype('unsigned short'), Dimension]

readerType = itk.ImageFileReader[RealImageType]
reader = readerType.New()

reader.SetFileName(
    'C:/Users/duso/PycharmProjects/Semestralni_Prace/Registration/Frangis/RegistrationTests/test/Reg_8_GaborliversSmall.nrrd'
)
reader.Update()

#
image = reader.GetOutput()
#
origin = np.zeros(3)
spacing = np.ones(3)
size = np.ones(3, np.int) * 64
mean = np.zeros(3)
sigma = np.zeros(3)
コード例 #34
0
ファイル: complex.py プロジェクト: ygdmxy/ITK
def TestComplex(selectedType):
    cType = itk.complex[itk.ctype(selectedType)]
    c = cType(2.0, 3.0)
    assert c.real() == 2.0
    assert c.imag() == 3.0
    assert complex(c) == 2.0 + 3.0j
コード例 #35
0
import sys
import os

import itk

if len(sys.argv) < 2:
    print("Usage: " + sys.argv[0] +
          " [DicomDirectory [outputFileName [seriesName]]]")
    print("If DicomDirectory is not specified, current directory is used\n")

# current directory by default
dirName = '.'
if len(sys.argv) > 1:
    dirName = sys.argv[1]

PixelType = itk.ctype('signed short')
Dimension = 3

ImageType = itk.Image[PixelType, Dimension]

namesGenerator = itk.GDCMSeriesFileNames.New()
namesGenerator.SetUseSeriesDetails(True)
namesGenerator.AddSeriesRestriction("0008|0021")
namesGenerator.SetGlobalWarningDisplay(False)
namesGenerator.SetDirectory(dirName)

seriesUID = namesGenerator.GetSeriesUIDs()

if len(seriesUID) < 1:
    print('No DICOMs in: ' + dirName)
    sys.exit(1)
コード例 #36
0
def rigid_body_transform3D(input_filename,output_filename,rot=[0.,0.,0.],t=[0.,0.,0.],cor=[0.,0.,0.],threshold=0.,default_pixel_value=0,min_out=0,max_out=255,verbose=False):
    """This function makes a rigid body transform on the 3D volume of image and writes it in the output"""
    #    input_filename  = '/Volumes/Storage/Projects/Registration/QuickData/OA-BEADS-CT.nii'
    #    output_filename = '/Volumes/Storage/Projects/Registration/QuickData/transformed_ct.nii'
    #    
    #    threshold  = 0.
    #    default_pixel_value = 100
    #    min_out = 0
    #    max_out = 255
    #    
    #    rot = [40. ,0. ,0.]   # Rotation in degrees in x, y, and z direction. 
    #    t   = [100. ,100. ,100.]   # translation in x, y, and z directions. 
    #    cor = [0. ,0. ,0.]   # offset of the rotation from the center of image (3D)
    #    
    #    
    #    verbose = False      # Verbose details of all steps. 
    #    
    
    #% ------------------------------- Import Libraries ------------------------
    import itk # imports insight Toolkit
    import numpy
    import sys
    #import StereoFlouroscopyRegistration.util.itk_helpers as Functions
    #%%------------------ Starting the main body of the code ---------------- 
    # -------------------- Reader -------------------------
    InputPixelType  = itk.ctype("short")
    DimensionIn  = 3
    
    InputImageType  = itk.Image[InputPixelType , DimensionIn ]
    
    
    ReaderType = itk.ImageFileReader[InputImageType]
    reader     = ReaderType.New()
    reader.SetFileName(input_filename)
    
    try:
        print("Reading image: " + input_filename)
        reader.Update()
        print("Image Read Successfully")
    except ValueError: 
        print("ERROR: ExceptionObject cauth! \n")
        print(ValueError)
        sys.exit()
        
    inputImage = reader.GetOutput()
    
    if verbose :
        print(inputImage)
        
    inOrigin     = inputImage.GetOrigin()                   # Get the origin of the image.
    inSpacing    = inputImage.GetSpacing()                  # Get the resolution of the input image.
    inSize       = inputImage.GetBufferedRegion().GetSize() # Get the size of the input image.
    inDirection  = inputImage.GetDirection()
    
    #%% ------------------ Transformation 
    # This part is inevitable since the interpolator (Ray-cast) and resample Image
    # image filter uses a Transformation -- Here we set it to identity. 
    TransformType = itk.CenteredEuler3DTransform[itk.D]
    transform     = TransformType.New()
    
    direction_mat = get_vnl_matrix(inDirection.GetVnlMatrix())
    
    rot = numpy.dot(-1,rot)           # Due to Direction of transform mapping ( 8.3.1 in the ITK manual)
    t   = numpy.dot(-1,t  )           # Due to Direction of transform mapping ( 8.3.1 in the ITK manual)
    
    
    
    rot = direction_mat.dot(numpy.transpose(rot))           
    t   = direction_mat.dot(numpy.transpose(t  ))          
    
    
    transform.SetRotation(numpy.deg2rad(rot[0]),numpy.deg2rad(rot[1]),numpy.deg2rad(rot[2])) # Setting the rotation of the transform
    transform.SetTranslation(itk.Vector.D3(t))    # Setting the translation of the transform
    transform.SetComputeZYX(True)  # The order of rotation will be ZYX. 
    
    center = direction_mat.dot(inOrigin)+ numpy.multiply(inSpacing,inSize)/2. # Setting the center of rotation as center of 3D object + offset determined by cor. 
    center = direction_mat.dot(center)-t # Convert the image to the local coordinate system. 
    transform.SetCenter(center)                     # Setting the center of rotation. 
    
    if verbose :
        print(transform)
    #% ------------------ Interpolator ------------------------------------
    InterpolatorType = itk.LinearInterpolateImageFunction[InputImageType,itk.D]
    interpolator = InterpolatorType.New()
     #%%----------------- Resample Image Filter -----------------------
     # In this part the resample image filter to map a 3D image to 2D image plane with desired specs is designed
    FilterType = itk.ResampleImageFilter[InputImageType,InputImageType]                     # Defining the resample image filter type. 
    resamplefilter = FilterType.New()                                                       # Pointer to the filter
#    R = Functions.get_transform_direction(transform)
#    T = numpy.transpose(t)
#    
    outOrigin = inOrigin - t #+ R.dot(numpy.transpose(direction_mat.dot(inOrigin)))
#    transform_matrix = Functions.get_vnl_matrix(transform.GetMatrix().GetVnlMatrix())
    #outDirection = transform_matrix.dot(direction_mat)
    outDirection = inDirection
    scaling = 1 # the scaling factor for the image. 
    
    outSize= [scaling*inSize[0],scaling*inSize[1],inSize[2]]
    
    resamplefilter.SetInput(inputImage)                                                     # Setting the input image data 
    resamplefilter.SetDefaultPixelValue(default_pixel_value)                                # Setting the default Pixel value
    resamplefilter.SetInterpolator(interpolator)                                            # Setting the interpolator
    resamplefilter.SetTransform(transform)                                                  # Setting the transform
    resamplefilter.SetSize(outSize)                                                         # Setting the size of the output image. 
    resamplefilter.SetOutputSpacing(inSpacing)                                              # Setting the spacing(resolution) of the output image. 
    # Functions.change_image_direction(resamplefilter.GetOutputDirection(),outDirection,3)
    resamplefilter.SetOutputOrigin(outOrigin)                                               # Setting the output origin of the image
    resamplefilter.SetOutputDirection(outDirection)                                         # Setting the output direction of the image. 
    resamplefilter.Update()                                                                 # Updating the resample image filter.
    
    if verbose:
        print(resamplefilter)
    
    
    #%% ------------------ Writer ------------------------------------
    # The output of the resample filter can then be passed to a writer to
    # save the DRR image to a file.
        
    WriterType=itk.ImageFileWriter[InputImageType]
    writer=WriterType.New()
    writer.SetFileName(output_filename)
    writer.SetInput(resamplefilter.GetOutput())
    
    try:
        print("Writing the transformed Volume at : " + output_filename)
        writer.Update()
        print("Volume Printed Successfully")
    except ValueError: 
        print("ERROR: ExceptionObject caugth! \n")
        print(ValueError)
        sys.exit()
コード例 #37
0
ファイル: Code.py プロジェクト: xiaobo2014/ITKSphinxExamples
import sys
import os

import itk

if len(sys.argv) < 2:
    print("Usage: " + sys.argv[0] +
          " [DicomDirectory [outputFileName [seriesName]]]")
    print("If DicomDirectory is not specified, current directory is used\n")

# current directory by default
dirName = "."
if len(sys.argv) > 1:
    dirName = sys.argv[1]

PixelType = itk.ctype("signed short")
Dimension = 3

ImageType = itk.Image[PixelType, Dimension]

namesGenerator = itk.GDCMSeriesFileNames.New()
namesGenerator.SetUseSeriesDetails(True)
namesGenerator.AddSeriesRestriction("0008|0021")
namesGenerator.SetGlobalWarningDisplay(False)
namesGenerator.SetDirectory(dirName)

seriesUID = namesGenerator.GetSeriesUIDs()

if len(seriesUID) < 1:
    print("No DICOMs in: " + dirName)
    sys.exit(1)
コード例 #38
0
#        since higher values quickly start to undersegment the image.

import sys
import itk

if len(sys.argv) != 5:
    print('Usage: ' + sys.argv[0] +
          ' <InputFileName> <OutputFileName> <Threshold> <Level>')
    sys.exit(1)

inputFileName = sys.argv[1]
outputFileName = sys.argv[2]

Dimension = 2

FloatPixelType = itk.ctype('float')
FloatImageType = itk.Image[FloatPixelType, Dimension]

reader = itk.ImageFileReader[FloatImageType].New()
reader.SetFileName(inputFileName)

gradientMagnitude = \
    itk.GradientMagnitudeImageFilter.New(Input=reader.GetOutput())

watershed = \
    itk.WatershedImageFilter.New(Input=gradientMagnitude.GetOutput())

threshold = float(sys.argv[3])
level = float(sys.argv[4])
watershed.SetThreshold(threshold)
watershed.SetLevel(level)
コード例 #39
0
ファイル: complex.py プロジェクト: Kitware/ITK
def TestComplex(selectedType):
    cType = itk.complex[itk.ctype(selectedType)]
    c = cType(2.0,3.0)
    assert c.real() == 2.0
    assert c.imag() == 3.0
    assert complex(c) == 2.0+3.0j
コード例 #40
0
#   You may obtain a copy of the License at
#
#          http://www.apache.org/licenses/LICENSE-2.0.txt
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# =========================================================================*/

import itk

Dimension = 2
PixelType = itk.ctype("unsigned char")
ImageType = itk.Image[PixelType, Dimension]


def create_fixed_image():
    start = [
        0,
    ] * Dimension
    size = [
        100,
    ] * Dimension

    region = itk.ImageRegion[Dimension](start, size)

    ImageType = itk.Image[PixelType, Dimension]
    image = ImageType.New()
コード例 #41
0
import sys
import itk

if len(sys.argv) != 6:
    print('Usage: ' + sys.argv[0] + ' <InputFileName> <OutputFileName> <Alpha> <Beta> <Radius>')
    sys.exit(1)

inputFileName = sys.argv[1]
outputFileName = sys.argv[2]
alpha = float(sys.argv[3])
beta = float(sys.argv[4])
radiusValue = int(sys.argv[5])

Dimension = 2

PixelType = itk.ctype('unsigned char')
ImageType = itk.Image[PixelType, Dimension]

reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName(inputFileName)

histogramEqualization = \
    itk.AdaptiveHistogramEqualizationImageFilter.New(reader)
histogramEqualization.SetAlpha(alpha)
histogramEqualization.SetBeta(beta)

radius = itk.Size[Dimension]()
radius.Fill(radiusValue);
histogramEqualization.SetRadius(radius)

itk.imwrite(histogramEqualization, outputFileName)
コード例 #42
0
ファイル: extras.py プロジェクト: romangrothausmann/ITK
# test class_
assert itk.class_(reader) == ReaderType
assert itk.class_("dummy") == str

# test template
assert itk.template(ReaderType) == (itk.ImageFileReader, (ImageType,))
assert itk.template(reader) == (itk.ImageFileReader, (ImageType,))
try:
    itk.template(str)
    raise Exception("unknown class should send an exception")
except KeyError:
    pass

# test ctype
assert itk.ctype("unsigned short") == itk.US
assert itk.ctype("        unsigned      \n   short \t  ") == itk.US
assert itk.ctype("signed short") == itk.SS
assert itk.ctype("short") == itk.SS
try:
    itk.ctype("dummy")
    raise Exception("unknown C type should send an exception")
except KeyError:
    pass


# test output
assert itk.output(reader) == reader.GetOutput()
assert itk.output(1) == 1
# test the deprecated image
assert itk.image(reader) == reader.GetOutput()
コード例 #43
0
def Analyze_USRF_Spectra(spectra_filepath, output_path, spectra_start_idx=4,
        spectra_stop_idx=21):

    ComponentType = itk.ctype('float')
    Dimension = 2
    ImageType = itk.VectorImage[ComponentType, Dimension]

    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(spectra_filepath)
    reader.UpdateLargestPossibleRegion()
    spectra_image = reader.GetOutput()
    # lateral x axial x spectral component
    spectra_array = itk.GetArrayFromImage(spectra_image)

    # Look at low noise bandwidth of interest
    spectra_bandwidth = spectra_array[..., spectra_start_idx:spectra_stop_idx]

    # Work with spectra in dB
    spectra = 10 * np.log10(spectra_bandwidth)

    output_path = os.path.join(os.path.dirname(spectra_filepath), output_path)
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    basename = os.path.basename(spectra_filepath).split('_Spectra')[0]

    def save_output(arr, identifier):
        output_filepath = os.path.join(output_path, basename + identifier)
        np.save(output_filepath + '.npy', arr)

    save_output(spectra, '_Spectra')


    # Prep images
    num_lateral = spectra.shape[0]
    num_axial = spectra.shape[1]

    chebyshev_num_features = 7
    chebyshev_image = np.zeros([num_lateral, num_axial, chebyshev_num_features], dtype=np.float32)

    line_num_features = 2
    line_image = np.zeros([num_lateral, num_axial, line_num_features], dtype=np.float32)

    local_slope_points = 4
    local_slope_num_features = spectra.shape[2] / local_slope_points
    local_slope_image = np.zeros([num_lateral, num_axial, local_slope_num_features],
            dtype=np.float32)


    legendre_num_features = 7
    legendre_image = np.zeros([num_lateral, num_axial, legendre_num_features], dtype=np.float32)

    integrated_num_features = 1
    integrated_image = np.zeros([num_lateral, num_axial, integrated_num_features], dtype=np.float32)

    for lateral in np.arange(num_lateral):
        print "Line ", lateral, " of ", num_lateral
        for axial in np.arange(num_axial):
            spectrum = spectra[lateral, axial, :].ravel()

            cheb_coefs = np.polynomial.chebyshev.Chebyshev.fit(
                np.arange(len(spectrum)), spectrum, chebyshev_num_features-1)
            chebyshev_image[lateral, axial, :] = cheb_coefs.coef

            line_coefs = scipy.stats.linregress(
                np.arange(len(spectrum)), spectrum)
            line_image[lateral, axial, 0] = line_coefs.slope
            line_image[lateral, axial, 1] = line_coefs.intercept

            for ii in range(local_slope_num_features):
                coefs = scipy.stats.linregress(
                    np.arange(local_slope_points),
                    spectrum[ii*local_slope_points:(ii+1)*local_slope_points])
                local_slope_image[lateral, axial, ii] = coefs.slope

            legn_coefs = np.polynomial.legendre.legfit(
                np.arange(len(spectrum)), spectrum, legendre_num_features-1)
            legendre_image[lateral, axial, :] = legn_coefs

            intg_coefs = np.sum(spectrum)
            integrated_image[lateral, axial, 0] = intg_coefs

    save_output(chebyshev_image, '_Chebyshev')
    save_output(line_image, '_Line')
    save_output(local_slope_image, '_LocalSlope')
    save_output(legendre_image, '_Legendre')
    save_output(integrated_image, '_Integrated')
コード例 #44
0
# test class_
assert itk.class_(reader) == ReaderType
assert itk.class_("dummy") == str

# test template
assert itk.template(ReaderType) == (itk.ImageFileReader, (ImageType, ))
assert itk.template(reader) == (itk.ImageFileReader, (ImageType, ))
try:
    itk.template(str)
    raise Exception("unknown class should send an exception")
except KeyError:
    pass

# test ctype
assert itk.ctype("unsigned short") == itk.US
assert itk.ctype("        unsigned      \n   short \t  ") == itk.US
assert itk.ctype("signed short") == itk.SS
assert itk.ctype("short") == itk.SS
try:
    itk.ctype("dummy")
    raise Exception("unknown C type should send an exception")
except KeyError:
    pass

# test output
assert itk.output(reader) == reader.GetOutput()
assert itk.output(1) == 1
# test the deprecated image
assert itk.image(reader) == reader.GetOutput()
assert itk.image(1) == 1
コード例 #45
0
#!/usr/bin/env python

# ==========================================================================
#
#   Copyright Insight Software Consortium
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#          http://www.apache.org/licenses/LICENSE-2.0.txt
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ==========================================================================*/

import itk

Dimension = 2
RGBPixelType = itk.RGBPixel[itk.ctype("unsigned char")]

image = itk.Image[RGBPixelType, Dimension].New()
コード例 #46
0
try:
    input_matrix2 = itk.GetArrayFromImage(input_volume)
except:
    print(0)
try:
    input_matrix2 = sitk.GetArrayFromImage(input_volume)
except:
    print(0)
input_matrix_original = input_matrix2

input_volume2 = input_matrix2
blobs2 = np.zeros(input_volume2.shape, dtype=bool)

#do binary threshoulding on the original image

PixelType = itk.ctype('signed short')
Dimension = 3
try:
    thresholdFilter = sitk.BinaryThresholdImageFilter()
    input_volume_thr = thresholdFilter.Execute(input_volume, low, high, 255, 0)
except:
    print(0)
try:
    ImageType_threshold = itk.Image[PixelType, Dimension]
    thresholdFilter = itk.BinaryThresholdImageFilter[
        ImageType_threshold, ImageType_threshold].New()
    # input_volume=thresholdFilter.Execute(input_volume,low,high,0,255)
    thresholdFilter.SetInput(input_volume)

    thresholdFilter.SetLowerThreshold(low)
    thresholdFilter.SetUpperThreshold(high)
コード例 #47
0
def Convert_USRF_Spectra(input_filepath, reference_path, output_path, side_lines=5, fft1D_size=128):

    InputPixelType = itk.ctype('float')
    Dimension = 2
    ImageType = itk.Image[InputPixelType, Dimension]

    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(input_filepath)
    input_RF = reader.GetOutput()
    # Apply missing spacing information
    if 'LinearProbe' in input_filepath:
        change_information = itk.ChangeInformationImageFilter.New(input_RF)
        change_information.SetUseReferenceImage(True)
        change_information.SetChangeSpacing(True)
        output_spacing = [1.0, 1.0]
        size = itk.size(input_RF)
        sos = 1540.
        fs = 30000.
        output_spacing[0] = sos / (2 * fs)
        transducer_width = 30.0
        output_spacing[1] = transducer_width / (size[1] - 1)
        change_information.SetOutputSpacing(output_spacing)
        input_RF = change_information.GetOutput()
    input_RF.UpdateOutputInformation()

    SideLinesPixelType = itk.ctype('unsigned char')
    SideLinesImageType = itk.Image[SideLinesPixelType, Dimension]
    side_lines_image = SideLinesImageType.New()
    side_lines_image.CopyInformation(input_RF)
    side_lines_image.SetRegions(input_RF.GetLargestPossibleRegion())
    side_lines_image.Allocate()
    side_lines_image.FillBuffer(side_lines)

    spectra_window_filter = itk.Spectra1DSupportWindowImageFilter.New(side_lines_image)
    spectra_window_filter.SetFFT1DSize(fft1D_size)
    spectra_window_filter.SetStep(8)
    spectra_window_filter.UpdateLargestPossibleRegion()
    support_window_image = spectra_window_filter.GetOutput()

    SpectraImageType = itk.VectorImage[InputPixelType, Dimension]

    reference_reader = itk.ImageFileReader[SpectraImageType].New()
    basename = os.path.splitext(os.path.basename(input_filepath))[0]
    reference_path = os.path.join(os.path.dirname(input_filepath), reference_path)
    reference_glob = glob.glob(os.path.join(reference_path, basename[:-11] + '*.mha'))
    if len(reference_glob) != 1:
        print('Reference spectra file not found')
        print('Found: ', reference_glob)
        sys.exit(1)
    reference_reader.SetFileName(reference_glob[0])
    reference_reader.UpdateLargestPossibleRegion()

    reference_spectra_image = SpectraImageType.New()
    reference_spectra_image.CopyInformation(support_window_image)
    reference_spectra_image.SetRegions(support_window_image.GetLargestPossibleRegion())
    reference_spectra_image.SetNumberOfComponentsPerPixel(reference_reader.GetOutput().GetNumberOfComponentsPerPixel())
    reference_spectra_image.Allocate()
    reference_index = itk.Index[Dimension]()
    reference_index.Fill(0)
    reference_spectrum = reference_reader.GetOutput().GetPixel(reference_index)
    reference_spectra_image.FillBuffer(reference_spectrum)

    spectra_filter = itk.Spectra1DImageFilter.New(input_RF)
    spectra_filter.SetSupportWindowImage(spectra_window_filter.GetOutput())
    spectra_filter.SetReferenceSpectraImage(reference_spectra_image)
    spectra_filter.UpdateLargestPossibleRegion()

    output_path = os.path.join(os.path.dirname(input_filepath), output_path)
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    identifier = '_Spectra_side_lines_{:02d}_fft1d_size_{:03d}.mha'.format(side_lines, fft1D_size)
    output_filepath = os.path.join(output_path, basename + identifier)
    writer = itk.ImageFileWriter.New(spectra_filter)
    writer.SetFileName(output_filepath)
    writer.Update()
コード例 #48
0
writer.SetFileName( newpath+'/fixed.png' )
writer.SetInput( filter.GetOutput() )
writer.Update()

filter = itk.RescaleIntensityImageFilter[MovingImageType, OutPutImageType].New()
filter.SetOutputMinimum( 0 )
filter.SetOutputMaximum(255)
filter.SetInput(movingImage )

writer.SetFileName( newpath+'/moving.png' )
writer.SetInput( filter.GetOutput() )
writer.Update()


OutputPixelType = itk.ctype('unsigned char')
OutputImageType = itk.Image[OutputPixelType, 2]

caster = itk.CastImageFilter[FixedImageType,
        OutputImageType].New(Input=resampler)

newpath = 'C:/Users/duso/OneDrive - AIMTEC a. s/Documents/ZDO/SEM/X_01'
if not os.path.exists(newpath):
    os.makedirs(newpath)
outputImageFile = 'C:/Users/duso/OneDrive - AIMTEC a. s/Documents/ZDO/SEM/X_01/res.png'
differenceImageAfterFile = 'C:/Users/duso/OneDrive - AIMTEC a. s/Documents/ZDO/SEM/X_01/difAfter.png'
differenceImageBeforeFile = 'C:/Users/duso/OneDrive - AIMTEC a. s/Documents/ZDO/SEM/X_01/difBefore.png'

writer = itk.ImageFileWriter.New(Input=caster, FileName=outputImageFile)
writer.SetFileName(outputImageFile)
writer.Update()
コード例 #49
0
import sys
import os

import itk

if len(sys.argv) < 2:
    print("Usage: " + sys.argv[0] + " [DicomDirectory [outputFileName [seriesName]]]")
    print("If DicomDirectory is not specified, current directory is used\n")

# current directory by default
dirName = "."
if len(sys.argv) > 1:
    dirName = sys.argv[1]

PixelType = itk.ctype("signed short")
Dimension = 3

ImageType = itk.Image[PixelType, Dimension]

namesGenerator = itk.GDCMSeriesFileNames.New()
namesGenerator.SetUseSeriesDetails(True)
namesGenerator.AddSeriesRestriction("0008|0021")
namesGenerator.SetGlobalWarningDisplay(False)
namesGenerator.SetDirectory(dirName)

seriesUID = namesGenerator.GetSeriesUIDs()

if len(seriesUID) < 1:
    print("No DICOMs in: " + dirName)
    sys.exit(1)