Example #1
0
def test_downsample_images():
    DOWNSAMPLE_RATIO = 2.0

    # Import succeeds
    from hasi.align import mesh_to_image, downsample_images

    # Downsample succeeds
    images = downsample_images([target_healthy_image, target_unhealthy_image],
                               DOWNSAMPLE_RATIO)
    assert (len(images) == 2)

    # Downsampled image dimensions adjusted by expected ratio
    assert (itk.size(images[0]) == [
        int(itk.size(target_healthy_image)[dim] / DOWNSAMPLE_RATIO)
        for dim in range(dimension)
    ])
    assert (itk.spacing(images[0]) == [
        itk.spacing(target_healthy_image)[dim] * DOWNSAMPLE_RATIO
        for dim in range(dimension)
    ])
    assert (itk.size(images[1]) == [
        int(itk.size(target_unhealthy_image)[dim] / DOWNSAMPLE_RATIO)
        for dim in range(dimension)
    ])
    assert (itk.spacing(images[1]) == [
        itk.spacing(target_unhealthy_image)[dim] * DOWNSAMPLE_RATIO
        for dim in range(dimension)
    ])
Example #2
0
def test_mesh_to_image():
    # Import succeeds
    from hasi.align import mesh_to_image

    # Mesh-to-image executes without error
    images = mesh_to_image([template_mesh, target_mesh])

    # Images were generated
    assert (all([
        type(image) == itk.Image[mesh_pixel_type, dimension]
        for image in images
    ]))

    # Images occupy the same physical space
    assert (all(
        [itk.spacing(image) == itk.spacing(images[0]) for image in images]))
    assert (all([itk.size(image) == itk.size(images[0]) for image in images]))
    assert (all(
        [itk.origin(image) == itk.origin(images[0]) for image in images]))

    # Mesh-to-image can run with reference image
    image_from_reference = mesh_to_image(target_mesh,
                                         reference_image=images[0])

    # Type and image attributes match previous output
    assert (type(image_from_reference) == type(images[0]))
    assert (itk.spacing(image_from_reference) == itk.spacing(images[0]))
    assert (itk.size(image_from_reference) == itk.size(images[0]))
    assert (itk.origin(image_from_reference) == itk.origin(images[0]))
Example #3
0
def paste_to_common_space(images:list) -> list:
    image_type = type(images[0])
    pixel_type, dimension = itk.template(images[0])[1]

    resized_images = list()

    # Verify spacing is equivalent
    SPACING_TOLERANCE = 1e-7
    assert(all([itk.spacing(images[idx])[dim] - itk.spacing(images[0])[dim] < SPACING_TOLERANCE
                for dim in range(dimension)
                for idx in range(1,len(images))]))

    # Get largest common region
    max_size = itk.size(images[0])
    for image in images:
        max_size = [max(max_size[i], itk.size(image)[i]) for i in range(len(max_size))]

    # Define paste region
    for image in images:
        region = itk.ImageRegion[dimension]()
        region.SetSize(max_size)
        region.SetIndex([0] * dimension)
        new_image = type(images[0]).New(regions=region, spacing=image.GetSpacing())
        new_image.Allocate()

        resized_image = itk.paste_image_filter(source_image=image,
                                               source_region=image.GetLargestPossibleRegion(),
                                               destination_image=new_image,
                                               destination_index=[0] * dimension,
                                               ttype=type(image))
        resized_images.append(resized_image)
    return resized_images
Example #4
0
 def add(self, dose_file):
     lockfile = dose_file + ".lock"
     dose = None
     n_primaries = 0
     t0 = datetime.now()
     logger.debug("lockfile exists" if os.path.
                  exists(lockfile) else "lockfile does not exist")
     lock = SoftFileLock(lockfile)
     try:
         # TODO: the length of the timeout should maybe be configured in the system configuration
         with lock.acquire(timeout=3):
             t1 = datetime.now()
             logger.debug("acquiring lock file took {} seconds".format(
                 (t1 - t0).total_seconds()))
             ##########################
             n_primaries = self.get_nprimaries(dose_file)
             if n_primaries < 1:
                 logger.warn(
                     f"dose file seems to be based on too few primaries ({n_primaries})"
                 )
             elif bool(self.mass) and bool(self.mask):
                 simdose = itk.imread(dose_file)
                 logger.debug(
                     "resampling dose with size {} using mass file of size {} to target size {}"
                     .format(itk.size(simdose), itk.size(self.mass),
                             itk.size(self.mask)))
                 dose = mass_weighted_resampling(simdose, self.mass,
                                                 self.mask)
                 del simdose
             else:
                 dose = itk.imread(dose_file)
                 logger.debug("read dose with size {}".format(
                     itk.size(dose)))
             t2 = datetime.now()
             logger.debug(
                 "acquiring dose data {} file took {} seconds".format(
                     os.path.basename(dose_file),
                     (t2 - t1).total_seconds()))
             if self.wmin > n_primaries:
                 self.wmin = n_primaries
             if self.wmax < n_primaries:
                 self.wmax = n_primaries
     except Timeout:
         logger.warn(
             "failed to acquire lock for {} for 3 seconds, giving up for now"
             .format(dose_file))
         return
     if not bool(dose):
         logger.warn("skipping {}".format(dose_file))
         return
     adose = itk.array_from_image(dose)
     if adose.shape != self.dosesum.shape:
         raise RuntimeError(
             "PROGRAMMING ERROR: dose shape {} differs from expected shape {}"
             .format(adose.shape, self.dosesum.shape))
     self.dosesum += adose  # n_primaries * (adose / n_primaries)
     self.dose2sum += adose**2 / n_primaries  # n_primaries * (adose / n_primaries)**2
     self.weightsum += n_primaries
     self.n += 1
Example #5
0
def enclosing_geometry(img1, img2):
    """
    Does img1 enclose img2?

    This function could be used to test whether img2 can be used as a reference image for resampling img1.
    """
    if equal_geometry(img1, img2):
        return True
    o1 = np.array(itk.origin(img1))
    o2 = np.array(itk.origin(img2))
    s1 = np.array(itk.spacing(img1))
    s2 = np.array(itk.spacing(img2))
    n1 = np.array(itk.size(img1))
    n2 = np.array(itk.size(img2))
    # compute corners
    lower1 = o1 - 0.5 * s1
    lower2 = o2 - 0.5 * s2
    upper1 = o1 + (n1 - 0.5) * s1
    upper2 = o2 + (n2 - 0.5) * s2
    #######################################################################
    # for debugging: percentages of img2 that are inside/outside of img1. #
    #######################################################################
    bb1 = bounding_box(img=img1)
    vol1 = bb1.volume
    bb2 = bounding_box(img=img2)
    vol2 = bb2.volume
    assert (vol2 > 0)
    bb2.intersect(bb1)
    overlap = bb2.volume
    outside = vol2 - bb2.volume
    overlap_percent = overlap * 100. / vol2
    outside_percent = outside * 100. / vol2
    logger.debug(f"vol img2={vol1} vol img2={vol2}")
    logger.debug(
        f"part of img2 that overlaps with img1: {overlap} or {overlap_percent} percent"
    )
    logger.debug(
        f"part of img2 that is outside img1: {outside} or {outside_percent} percent"
    )
    #######################################################################
    # end debugging section                                               #
    #######################################################################
    # now check the lower corner
    if (np.logical_not(np.isclose(lower1, lower2)) * (lower1 > lower2)).any():
        return False
    # now check the upper corner
    if (np.logical_not(np.isclose(upper1, upper2)) * (upper1 < upper2)).any():
        return False
    return True
def ITKUSCurvilinearScanconvert_File(input_filepath,\
          dim =3,\
          scan_angle = np.pi/2.0,\
                                  radius_start = 12.4,\
                                  radius_stop = 117.5,\
                                  sz_output = (1108,725),\
                                  spacing_output = (0.15, 0.15, 0.15)):

    ## Retrive the dimension of inputImage
    #dim                  	   = itkImg.ImageDimension
    frames = 0
    sz_output = (1108, 725)
    origin_output = [0.0, 0.0]

    iType_CurvilinearImg = itk.CurvilinearArraySpecialCoordinatesImage[itk.F,
                                                                       dim]
    iType_SCUSImg = itk.Image[itk.F, dim]

    iFileReaderUSRF = itk.ImageFileReader[iType_CurvilinearImg].New()
    iFileReaderUSRF.SetFileName(input_filepath)
    iFileReaderUSRF.UpdateOutputInformation()
    iimg_curvilinear = iFileReaderUSRF.GetOutput()

    if dim == 3:
        frames = int(itk.size(iimg_curvilinear)[2])
        sz_output = (1108, 725, frames)
        origin_output = [0.0, 0.0, 0.0]
        spacing_output = (0.15, 0.15, 0.15)
    else:
        sz_output = (1108, 725)
        origin_output = [0.0, 0.0]
        spacing_output = (0.15, 0.15)

    isz_curvilinear = iimg_curvilinear.GetLargestPossibleRegion().GetSize()

    ## Computing the parameters of curvilinear sacn-conversion
    lateral_angular_separation = scan_angle / (isz_curvilinear[1] - 1)
    radius_scan = (radius_stop - radius_start) / (isz_curvilinear[0] - 1)

    # sz_output                  = (1108,725, frames)
    # origin_output              = [0.0, 0.0, 0.0]
    origin_output[0] = sz_output[0] * spacing_output[0] / -2.0
    origin_output[1] = radius_start * np.cos(scan_angle / 2)

    iimg_curvilinear.SetLateralAngularSeparation(lateral_angular_separation)
    iimg_curvilinear.SetFirstSampleDistance(radius_start)
    iimg_curvilinear.SetRadiusSampleSize(radius_scan)

    ## Resample Image
    #iType_UCharImg             = itk.Image[itk.UC, dim]
    iFilter_resample = itk.ResampleImageFilter[iType_CurvilinearImg,
                                               iType_SCUSImg].New()
    iFilter_resample.SetInput(iimg_curvilinear)
    iFilter_resample.SetSize(sz_output)
    iFilter_resample.SetOutputSpacing(spacing_output)
    iFilter_resample.SetOutputOrigin(origin_output)
    iFilter_resample.UpdateLargestPossibleRegion()

    ## Return a scan-converted US BMode image
    return iFilter_resample.GetOutput()
Example #7
0
    def test_itk_registration(self):
        import os
        os.environ["FOOTSTEPS_NAME"] = "test"
        import footsteps

        icon_registration.test_utils.download_test_data()

        model = icon_registration.pretrained_models.OAI_knees_registration_model(
            pretrained=True)

        image_A = itk.imread(
            str(icon_registration.test_utils.TEST_DATA_DIR /
                "knees_diverse_sizes" /
                #"9126260_20060921_SAG_3D_DESS_LEFT_11309302_image.nii.gz")
                "9487462_20081003_SAG_3D_DESS_RIGHT_11495603_image.nii.gz"))

        image_B = itk.imread(
            str(icon_registration.test_utils.TEST_DATA_DIR /
                "knees_diverse_sizes" /
                "9225063_20090413_SAG_3D_DESS_RIGHT_12784112_image.nii.gz"))
        print(image_A.GetLargestPossibleRegion().GetSize())
        print(image_B.GetLargestPossibleRegion().GetSize())
        print(image_A.GetSpacing())
        print(image_B.GetSpacing())

        phi_AB, phi_BA = icon_registration.itk_wrapper.register_pair(
            model, image_A, image_B)

        assert (isinstance(phi_AB, itk.CompositeTransform))
        interpolator = itk.LinearInterpolateImageFunction.New(image_A)

        warped_image_A = itk.resample_image_filter(
            image_A,
            transform=phi_AB,
            interpolator=interpolator,
            size=itk.size(image_B),
            output_spacing=itk.spacing(image_B),
            output_direction=image_B.GetDirection(),
            output_origin=image_B.GetOrigin())

        plt.imshow(
            np.array(itk.checker_board_image_filter(warped_image_A,
                                                    image_B))[40])
        plt.colorbar()
        plt.savefig(footsteps.output_dir + "grid.png")
        plt.clf()
        plt.imshow(np.array(warped_image_A)[40])
        plt.savefig(footsteps.output_dir + "warped.png")
        plt.clf()

        reference = np.load(icon_registration.test_utils.TEST_DATA_DIR /
                            "warped.npy")

        np.save(footsteps.output_dir + "warped.npy",
                itk.array_from_image(warped_image_A)[40])

        self.assertLess(
            np.mean(
                np.abs(reference - itk.array_from_image(warped_image_A)[40])),
            1e-6)
def ITKUSCurvilinearScanconvert_File(input_filepath,\
									 dim =3,\
									 scan_angle = np.pi/2.0,\
	                                 radius_start = 12.4,\
	                                 radius_stop = 117.5,\
	                                 sz_output = (1108,725),\
	                                 spacing_output = (0.15, 0.15, 0.15)):
	
	## Retrive the dimension of inputImage
	#dim                  	   = itkImg.ImageDimension
	frames                     = 0 
	sz_output                  = (1108,725)
	origin_output              = [0.0, 0.0]
	

	iType_CurvilinearImg 	   = itk.CurvilinearArraySpecialCoordinatesImage[itk.F, dim]
	iType_SCUSImg              = itk.Image[itk.F, dim]

	iFileReaderUSRF            = itk.ImageFileReader[iType_CurvilinearImg].New()
	iFileReaderUSRF.SetFileName(input_filepath)
	iFileReaderUSRF.UpdateOutputInformation()
	iimg_curvilinear           = iFileReaderUSRF.GetOutput()

	
	if dim == 3:
		frames                 = int(itk.size(iimg_curvilinear)[2])
		sz_output              = (1108,725, frames)
		origin_output          = [0.0, 0.0, 0.0]
		spacing_output         = (0.15, 0.15, 0.15)
	else:
		sz_output              = (1108,725)
		origin_output          = [0.0, 0.0]
		spacing_output         = (0.15, 0.15)

	isz_curvilinear            = iimg_curvilinear.GetLargestPossibleRegion().GetSize()

	## Computing the parameters of curvilinear sacn-conversion
	lateral_angular_separation = scan_angle / (isz_curvilinear[1]-1) 
	radius_scan                = (radius_stop - radius_start) / (isz_curvilinear[0]-1)
	
	# sz_output                  = (1108,725, frames)
	# origin_output              = [0.0, 0.0, 0.0]
	origin_output[0]           = sz_output[0] * spacing_output[0]/ -2.0
	origin_output[1]           = radius_start * np.cos(scan_angle/2)

	iimg_curvilinear.SetLateralAngularSeparation(lateral_angular_separation)
	iimg_curvilinear.SetFirstSampleDistance(radius_start)
	iimg_curvilinear.SetRadiusSampleSize(radius_scan)

	## Resample Image
	#iType_UCharImg             = itk.Image[itk.UC, dim]
	iFilter_resample           = itk.ResampleImageFilter[iType_CurvilinearImg, iType_SCUSImg].New()
	iFilter_resample.SetInput(iimg_curvilinear)
	iFilter_resample.SetSize(sz_output)
	iFilter_resample.SetOutputSpacing(spacing_output)
	iFilter_resample.SetOutputOrigin(origin_output)
	iFilter_resample.UpdateLargestPossibleRegion()

	## Return a scan-converted US BMode image
	return iFilter_resample.GetOutput()
Example #9
0
def test_paste_to_common_space():
    # Import succeeds
    from hasi.align import mesh_to_image, paste_to_common_space

    # Paste succeeds
    resized_images = paste_to_common_space(
        [target_healthy_image, target_unhealthy_image])
    assert (len(resized_images) == 2)

    # Verify common space
    TOLERANCE = 1e-6
    assert (itk.size(resized_images[0]) == itk.size(resized_images[1]))
    assert (all([
        itk.spacing(resized_images[0])[dim] -
        itk.spacing(resized_images[1])[dim] < TOLERANCE
        for dim in range(dimension)
    ]))
Example #10
0
    def _get_spatial_shape(self, img: Image) -> Sequence:
        """
        Get the spatial shape of image data, it doesn't contain the channel dim.

        Args:
            img: a ITK image object loaded from a image file.

        """
        return list(itk.size(img))
Example #11
0
    def _get_spatial_shape(self, img) -> np.ndarray:
        """
        Get the spatial shape of image data, it doesn't contain the channel dim.

        Args:
            img: a ITK image object loaded from a image file.

        """
        shape = list(itk.size(img))
        shape.reverse()
        return np.asarray(shape)
Example #12
0
    def _get_spatial_shape(self, img):
        """
        Get the spatial shape of image data, it doesn't contain the channel dim.

        Args:
            img: a ITK image object loaded from a image file.

        """
        # the img data should have no channel dim or the last dim is channel
        shape = list(itk.size(img))
        shape.reverse()
        return np.asarray(shape)
Example #13
0
def attenuation_local(prim_per_proj, proj_path):
    if not os.path.exists(proj_path):
        os.makedirs(proj_path)
    interp_secfolder = 'interpolated_secondaries'
    if not os.path.exists(interp_secfolder):
        os.makedirs(interp_secfolder)

    #IMC=PMC×#primaries_per_projection×(512/128)^2+SMC
    size_primary = 512
    size_scatter = 64
    factor = prim_per_proj * pow(size_primary / size_scatter, 2)

    # get all the primary projections
    primary_files = sorted(glob.glob('./output/primary*.mha'))
    interpolate_secondaries(secondary_folder, interp_secfolder, 4,
                            len(primary_files))

    for projnum, primary_filename in enumerate(primary_files):
        # load the primary, secondary, and flatfield
        primary = itk.imread(primary_filename)
        flatfield = itk.imread(primary_filename.replace(
            "primary", "flatfield"))

        #not needed anymore - secondaries only have half the projections, so the secondary projection number = projnum/2
        #second_projnum = projnum // 4
        #secondary = itk.imread(f'./output/secondary{second_projnum:04d}.mha')
        secondary = itk.imread(
            f'{interp_secfolder}/secondary{projnum:04d}.mha')
        resizedsecondary = gt.applyTransformation(
            input=secondary,
            newsize=itk.size(primary),
            neworigin=itk.origin(primary),
            adaptive=True,
            force_resample=True)

        flatfield = itk.MultiplyImageFilter(flatfield, factor)

        prim_second = itk.AddImageFilter(
            itk.MultiplyImageFilter(primary, factor), resizedsecondary)
        #flatfield_sq = itk.MultiplyImageFilter(flatfield,flatfield)

        S = itk.DivideImageFilter(prim_second, flatfield)
        S = itk.MultiplyImageFilter(S, itk.MedianImageFilter(flatfield))
        attenuation = itk.LogImageFilter(S)
        #attenuation = itk.LogImageFilter(itk.DivideImageFilter(prim_second,flatfield))

        attenuation = itk.MultiplyImageFilter(attenuation, -1)

        itk.imwrite(
            attenuation,
            primary_filename.replace('./output/primary',
                                     f'{proj_path}/attenuation_sec'))
Example #14
0
def downsample_images(images:list, ratio:float) -> list:
    assert(ratio > 1.0)

    downsampled_image_list = list()
    for image in images:
        new_spacing = [spacing * ratio for spacing in itk.spacing(image)]
        new_size = [int(size / ratio) for size in itk.size(image)]
        downsampled_image = itk.resample_image_filter(image,
                                                      size=new_size,
                                                      output_origin=itk.origin(image),
                                                      output_spacing=new_spacing)
        downsampled_image_list.append(downsampled_image)
    return downsampled_image_list
Example #15
0
def compute_real_width_and_height(image, width, height):
    image_size = itk.size(image)
    if width is None and height is None:
        width = DEFAULT_WIDTH
        height = DEFAULT_HEIGHT
    elif width is None:
        width = int(math.ceil(image_size[0] / image_size[1] * height))
    elif height is None:
        height = int(math.ceil(image_size[1] / image_size[0] * width))
    if not height >= 1 or not width >= 1:
        raise Exception(
            "`height` and `width` must be greater than or equal to 1")
    return width, height
Example #16
0
    def create_backend_obj(
        cls,
        data_array: NdarrayOrTensor,
        channel_dim: Optional[int] = 0,
        affine: Optional[NdarrayOrTensor] = None,
        dtype: DtypeLike = np.float32,
        affine_lps_to_ras: bool = True,
        **kwargs,
    ):
        """
        Create an ITK object from ``data_array``. This method assumes a 'channel-last' ``data_array``.

        Args:
            data_array: input data array.
            channel_dim: channel dimension of the data array. This is used to create a Vector Image if it is not ``None``.
            affine: affine matrix of the data array. This is used to compute `spacing`, `direction` and `origin`.
            dtype: output data type.
            affine_lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to ``True``.
                Set to ``True`` to be consistent with ``NibabelWriter``,
                otherwise the affine matrix is assumed already in the ITK convention.
            kwargs: keyword arguments. Current `itk.GetImageFromArray` will read ``ttype`` from this dictionary.

        see also:

            - https://github.com/InsightSoftwareConsortium/ITK/blob/v5.2.1/Wrapping/Generators/Python/itk/support/extras.py#L389
        """
        data_array = super().create_backend_obj(data_array)
        _is_vec = channel_dim is not None
        if _is_vec:
            data_array = np.moveaxis(data_array, -1,
                                     0)  # from channel last to channel first
        data_array = data_array.T.astype(dtype, copy=True, order="C")
        itk_obj = itk.GetImageFromArray(data_array,
                                        is_vector=_is_vec,
                                        ttype=kwargs.pop("ttype", None))

        d = len(itk.size(itk_obj))
        if affine is None:
            affine = np.eye(d + 1, dtype=np.float64)
        _affine = convert_data_type(affine, np.ndarray)[0]
        if affine_lps_to_ras:
            _affine = orientation_ras_lps(to_affine_nd(d, _affine))
        spacing = affine_to_spacing(_affine, r=d)
        _direction: np.ndarray = np.diag(1 / spacing)
        _direction = _affine[:d, :d] @ _direction
        itk_obj.SetSpacing(spacing.tolist())
        itk_obj.SetOrigin(_affine[:d, -1].tolist())
        itk_obj.SetDirection(itk.GetMatrixFromArray(_direction))
        return itk_obj
Example #17
0
def vtk_image_from_image(image):
    """Convert an itk.Image to a vtk.vtkImageData."""
    import itk
    import vtk
    from vtk.util.numpy_support import numpy_to_vtk

    array = itk.array_view_from_image(image)

    vtk_image = vtk.vtkImageData()
    data_array = numpy_to_vtk(array.reshape(-1))
    data_array.SetNumberOfComponents(image.GetNumberOfComponentsPerPixel())
    data_array.SetName('Scalars')
    # Always set Scalars for (future?) multi-component volume rendering
    vtk_image.GetPointData().SetScalars(data_array)
    dim = image.GetImageDimension()
    spacing = [
        1.0,
    ] * 3
    spacing[:dim] = image.GetSpacing()
    vtk_image.SetSpacing(spacing)
    origin = [
        0.0,
    ] * 3
    origin[:dim] = image.GetOrigin()
    vtk_image.SetOrigin(origin)
    dims = [
        1,
    ] * 3
    dims[:dim] = itk.size(image)
    vtk_image.SetDimensions(dims)
    # Todo: Add Direction with VTK 9
    if image.GetImageDimension() == 3:
        PixelType = itk.template(image)[1][0]
        if PixelType == itk.Vector:
            vtk_image.GetPointData().SetVectors(data_array)
        elif PixelType == itk.CovariantVector:
            vtk_image.GetPointData().SetVectors(data_array)
        elif PixelType == itk.SymmetricSecondRankTensor:
            vtk_image.GetPointData().SetTensors(data_array)
        elif PixelType == itk.DiffusionTensor3D:
            vtk_image.GetPointData().SetTensors(data_array)
    return vtk_image
Example #18
0
def smooth_and_resample(image, width, height):
    # Set input image origin to 0,0 as we do not want to worry about it.
    image.SetOrigin([0, 0])

    original_size = itk.size(image)
    original_spacing = image.GetSpacing()

    # We need to create a new Python variable to compute
    # the new size as `size_im` that was returned above is
    # actually a reference that points to the value that is
    # contained in the image.
    new_size = itk.Size[OUTPUT_IMAGE_DIMENSION]()
    new_size[0] = width
    new_size[1] = height
    SpacingType = itk.Vector[itk.D, OUTPUT_IMAGE_DIMENSION]
    scale = SpacingType()
    new_spacing = SpacingType()
    for ii in range(OUTPUT_IMAGE_DIMENSION):
        scale[ii] = float(original_size[ii]) / float(new_size[ii])
        new_spacing[ii] = scale[ii] * original_spacing[ii]

    # Make output image isotropic since jpeg does not have spacing information.
    # We keep the largest spacing, to avoid cutting the image along one
    # direction.
    if new_spacing[0] > new_spacing[1]:
        new_spacing[1] = new_spacing[0]
    else:
        new_spacing[0] = new_spacing[1]

    sigma = SpacingType()
    for ii in [0, 1]:
        sigma[ii] = 2 * new_spacing[ii] / math.pi
    variance = sigma * sigma

    gaussian_image = itk.DiscreteGaussianImageFilter(image,
                                                     UseImageSpacing=True,
                                                     Variance=variance)
    resampled_image = itk.ResampleImageFilter(gaussian_image,
                                              Size=new_size,
                                              OutputSpacing=new_spacing)
    return resampled_image
Example #19
0
def xarray_from_image(l_image):
    """Convert an itk.Image to an xarray.DataArray.

    Origin and spacing metadata is preserved in the xarray's coords. The
    Direction is set in the `direction` attribute.
    Dims are labeled as `x`, `y`, `z`, and `c`.

    This interface is and behavior is experimental and is subject to possible
    future changes."""
    import xarray as xr
    import itk
    import numpy as np

    array_view = itk.array_view_from_image(l_image)
    l_spacing = itk.spacing(l_image)
    l_origin = itk.origin(l_image)
    l_size = itk.size(l_image)
    direction = np.flip(itk.array_from_matrix(l_image.GetDirection()))
    spatial_dimension = l_image.GetImageDimension()

    spatial_dims = ("x", "y", "z")
    coords = {}
    for l_index, dim in enumerate(spatial_dims[:spatial_dimension]):
        coords[dim] = np.linspace(
            l_origin[l_index],
            l_origin[l_index] + (l_size[l_index] - 1) * l_spacing[l_index],
            l_size[l_index],
            dtype=np.float64,
        )

    dims = list(reversed(spatial_dims[:spatial_dimension]))
    components = l_image.GetNumberOfComponentsPerPixel()
    if components > 1:
        dims.append("c")
        coords["c"] = np.arange(components, dtype=np.uint64)

    data_array = xr.DataArray(array_view,
                              dims=dims,
                              coords=coords,
                              attrs={"direction": direction})
    return data_array
Example #20
0
    medianCENP, Sigma=0.05)
sizeCENP = itk.PhysicalSizeOpeningImageFilter.IUC3IUC3.New(
    gaussianCENP, Lambda=0.36)
subCENP = itk.SubtractImageFilter.IUC3IUC3IUC3.New(gaussianCENP, sizeCENP)
size2CENP = itk.PhysicalSizeOpeningImageFilter.IUC3IUC3.New(
    subCENP, Lambda=0.02)
maskCENP = itk.LabelMapMaskImageFilter.LM3IUC3.New(
    lmNuclei, size2CENP, Label=0)
thCENP = itk.BinaryThresholdImageFilter.IUC3IUC3.New(
    maskCENP, LowerThreshold=35)
statsCENP = itk.BinaryImageToStatisticsLabelMapFilter.IUC3IUC3LM3.New(
    thCENP, subCENP)

# create a new image to store the CENP centers, so they can be easily reused to check the distribution
cenpSpotsImg = itk.Image.UC3.New(
    Regions=itk.size(readerNuclei), Spacing=itk.spacing(readerNuclei))
cenpSpotsImg.Allocate()
cenpSpotsImg.FillBuffer(0)

if opts.visualValidation:
    # create a new image to store the CENP segmentation
    cenpImg = itk.LabelMap._3.New(
        Regions=itk.size(readerNuclei), Spacing=itk.spacing(readerNuclei))
    fullCENP = itk.LabelMapToBinaryImageFilter.LM3IUC3.New(cenpImg)
    dilateCENP = itk.BinaryDilateImageFilter.IUC3IUC3SE3.New(
        fullCENP, Kernel=itk.strel(3, [10, 10, 3]))
    borderCENP = itk.BinaryBorderImageFilter.IUC3IUC3.New(dilateCENP)
    outsideMask = itk.BinaryThresholdImageFilter.IUC3IUC3.New(
        lm2iNuclei, UpperThreshold=0)
    relabelCENP = itk.NaryRelabelImageFilter.IUC3IUC3.New(
        outsideMask, borderCENP)
Example #21
0
def ConvertRF2BMode(inputFilePath, outputFilePath):

    ## Check
    print inputFilePath
    print outputFilePath
    ## Initialize
    Dimension = 3

    ## Load RF data
    InputPixelType = itk.F
    ImageType = itk.Image[InputPixelType, Dimension]
    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(inputFilePath)
    # reader.Update()


    ## Generate Pre-Scanconversion Data from the RF file
    PreSc_BMode_Filter = itk.BModeImageFilter[ImageType, ImageType].New()
    PreSc_BMode_Filter.SetInput(reader.GetOutput())
    PreSc_BMode_Filter.SetDirection(1)
    # PreSc_BMode_Filter.Update()
    PreSc_BMode = PreSc_BMode_Filter.GetOutput()


    InputRF_Size = itk.size(PreSc_BMode)
    print '----------------'
    print InputRF_Size[0]
    print InputRF_Size[1]
    print InputRF_Size[2]

    RF_Sz_Z = InputRF_Size[2]

    # output_size = (1108, 725, RF_Sz_Z)
    #
    # print "---- Before ----"
    # print "The type of RF_Sz_Z: %s" % type(RF_Sz_Z)
    # print "The type of output_size: %s" % type(output_size)
    #
    # print "---- After -----"
    # RF_Sz_Z_Int = int(RF_Sz_Z)
    # output_size_Int = (1108, 725, RF_Sz_Z_Int)
    # print "The type of RF_Sz_Z_Int: %s" % type(RF_Sz_Z_Int)
    # print "The type of output_size_Int: %s" % type(output_size_Int)


    ## Scanconversion
    #01. Rescale the image's intensity
    CurvilinearImageType = itk.CurvilinearArraySpecialCoordinatesImage[itk.UC, Dimension]
    rescale_filter = itk.RescaleIntensityImageFilter[ImageType, CurvilinearImageType].New()
    #rescale_filter.SetInput(PreSc_BMode)#(bmode_filter.GetOutput())
    rescale_filter.SetInput(PreSc_BMode_Filter.GetOutput())
    rescale_filter.UpdateLargestPossibleRegion()
    curvilinear = rescale_filter.GetOutput()

    # writer = itk.ImageFileWriter[CurvilinearImageType].New()
    # writer.SetFileName(outputFilePath)
    # writer.SetInput(curvilinear)
    # writer.Update()


    #02. Scanconversion
    curvilinear_size = curvilinear.GetLargestPossibleRegion().GetSize()

    #lateral_angular_separation = (np.pi / 2.0 + np.pi / 4.0) / (curvilinear_size[1] - 1)
    lateral_angular_separation = (np.pi / 2.0 ) / (curvilinear_size[1] - 1)
    radius_start = 12.4
    radius_stop = 117.5

    curvilinear.SetLateralAngularSeparation(lateral_angular_separation)
    curvilinear.SetFirstSampleDistance(radius_start)
    curvilinear.SetRadiusSampleSize((radius_stop - radius_start) / (curvilinear_size[0] - 1))

    #output_size = (800, 800)
    #output_size = (1108, 725)
    output_size = (int(1108), int(725), int(RF_Sz_Z))

    print output_size

    output_spacing = (float(0.15), float(0.15), float(0.15))
    output_origin = [float(0.0), float(0.0), float(0.0)]
    output_origin[0] = float(output_size[0] * output_spacing[0] / -2.0)
    output_origin[1] = float(radius_start * np.cos(np.pi / 4.0))

    UCharImageType = itk.Image[itk.UC, Dimension]
    resample_filter = itk.ResampleImageFilter[CurvilinearImageType, UCharImageType].New()
    resample_filter.SetInput(curvilinear)
    resample_filter.SetSize(output_size)
    resample_filter.SetOutputSpacing(output_spacing)
    resample_filter.SetOutputOrigin(output_origin)
    resample_filter.UpdateLargestPossibleRegion()

    bmode_image2 = resample_filter.GetOutput()
    bmode_image2.DisconnectPipeline()

    writer = itk.ImageFileWriter[UCharImageType].New()
    writer.SetFileName(outputFilePath)
    writer.SetInput(bmode_image2)
    writer.Update()


    print '------------------------'
    print 'Done'
Example #22
0
#
#  Example on the use of the MeanImageFilter
#

import itk
from sys import argv

dim = 2
PixelType = itk.F
ImageType = itk.Image[PixelType, dim]

reader = itk.ImageFileReader[ImageType].New( FileName=argv[1] )

fftFilter = itk.FFTWRealToComplexConjugateImageFilter[PixelType, dim].New(reader)
fftFilter2 = itk.FFTWComplexConjugateToRealImageFilter[PixelType, dim].New(fftFilter)

cast = itk.CastImageFilter[ImageType, itk.Image[itk.UC, dim]].New( fftFilter2 )
itk.write(cast, argv[2])

print itk.size(fftFilter).GetElement(0), itk.size(fftFilter).GetElement(1)
Example #23
0
input_image_file = sys.argv[1]
spacing_fraction = float(sys.argv[2])
sigma_fraction = float(sys.argv[3])
output_image_file_label_image_interpolator = sys.argv[4]
output_image_file_nearest_neighbor_interpolator = sys.argv[5]

input_image = itk.imread(input_image_file)

resize_filter = itk.ResampleImageFilter.New(input_image)

input_spacing = itk.spacing(input_image)
output_spacing = [s * spacing_fraction for s in input_spacing]
resize_filter.SetOutputSpacing(output_spacing)

input_size = itk.size(input_image)
output_size = [
    int(s * input_spacing[dim] / spacing_fraction) for dim, s in enumerate(input_size)
]
resize_filter.SetSize(output_size)

gaussian_interpolator = itk.LabelImageGaussianInterpolateImageFunction.New(input_image)
sigma = [s * sigma_fraction for s in output_spacing]
gaussian_interpolator.SetSigma(sigma)
gaussian_interpolator.SetAlpha(3.0)
resize_filter.SetInterpolator(gaussian_interpolator)

itk.imwrite(resize_filter, output_image_file_label_image_interpolator)

nearest_neighbor_interpolator = itk.NearestNeighborInterpolateImageFunction.New(
    input_image
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()
Example #25
0
def process(in_dir, out_dir, width, height, slices):

    if not slices >= 2:
        raise Exception("`slices` must me greater or equal to 1.")
    # Create output directory if necessary.
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    file_names = get_filenames(in_dir)
    dicom_reader = ImageSeriesReader(FileNames=file_names)
    dicom_reader.MetaDataDictionaryArrayUpdateOn()
    dicom_reader.Update()
    meta_dict = dicom_reader.GetMetaDataDictionaryArray()[0]

    image = dicom_reader.GetOutput()

    # Rescaling is performed on the entire input image instead of on a
    # per-slice basis to allow rescaling the image based on its global
    # minimum and maximum if `width` and `center` tags are not defined
    # in the DICOM. The output of this function is scaled between 0 and 255.
    rescaled_image = rescale_dicom_image_intensity(image, meta_dict)

    width, height = compute_real_width_and_height(rescaled_image, width,
                                                  height)

    image_dimension = rescaled_image.GetImageDimension()
    # Verifies that input image is 3D. This allows to simplify the logic after.
    if image_dimension != INPUT_IMAGE_DIMENSION:
        raise Exception("Input must be a %dD image. %d dimensions found." %
                        (INPUT_IMAGE_DIMENSION, image_dimension))

    # Process each slice independently. This allows to only resample and
    # rescale the slices that will be saved at the end. NOTE: One could have
    # created a pipeline with `itk.pipeline()` which would only be run in the
    # end and only process requested regions, e.g. slice by slice. This method
    # would be useful if one wanted to resample the image in 3D instead of
    # processing each slice independently but is not necessary for now.
    image_size = itk.size(rescaled_image)

    size_sampling_dim = image_size[SLICING_DIMENSION]

    region = itk.ImageRegion[INPUT_IMAGE_DIMENSION]()
    new_size = itk.Size[INPUT_IMAGE_DIMENSION]()
    image_index = itk.Index[INPUT_IMAGE_DIMENSION]()

    for ii in range(INPUT_IMAGE_DIMENSION - 1):
        new_size[ii] = image_size[ii]
    new_size[INPUT_IMAGE_DIMENSION - 1] = 0

    region.SetSize(new_size)
    CollapsedImageType = itk.Image[itk.template(rescaled_image)[1][0],
                                   OUTPUT_IMAGE_DIMENSION]

    list_indices = []
    for ii in range(slices):
        slice_index = int((size_sampling_dim - 1) * ii / (slices - 1))
        image_index[SLICING_DIMENSION] = slice_index
        list_indices.append(slice_index)

        region.SetIndex(image_index)
        slice_image_filter = itk.ExtractImageFilter[
            rescaled_image, CollapsedImageType].New(rescaled_image,
                                                    ExtractionRegion=region)
        slice_image_filter.SetDirectionCollapseToIdentity()
        slice_image_filter.Update()

        resampled_image = smooth_and_resample(slice_image_filter.GetOutput(),
                                              width, height)
        save_as_jpeg(resampled_image, out_dir, slice_index)
    # Generate JSON file
    generate_json(out_dir, list_indices)

import itk
from sys import argv

dim = 2
PType = itk.US
IType = itk.Image[PType, dim]

reader = itk.ImageFileReader[IType].New(FileName=argv[1])
inputImage = reader.GetOutput()
# it is not required to update the filter: itk.size() update it
# to get the information it needs
size = itk.size(inputImage)

scale = itk.ScaleTransform[itk.D, dim].New(Parameters=[eval( argv[3] ), eval( argv[3] )])
# sequence typemap is not supported yet for itk::Point
centralPoint = itk.Point[itk.D, dim]()
centralPoint[0] = size[0] / 2.
centralPoint[1] = size[1] / 2.
scale.SetCenter( centralPoint )

interpolator = itkLinearInterpolateImageFunction[PType, dime, itk.D].New()

resampler = itkResampleImageFilter[IType, IType].New(reader)
resampler.SetTransform( scale.GetPointer() )
resampler.SetInterpolator( interpolator.GetPointer() )
resampler.SetSize( size )
resampler.SetOutputSpacing( inputImage.GetSpacing() )

writer = itk.ImageFileWriter[IType].New(resampler, FileName=argv[2])
Example #27
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()
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()
Example #29
0
lmNuclei = li2lm
lmNuclei()

# keep only one nucleus in the pre-filtered cenp image
mask = itk.LabelMapMaskImageFilter.LM3IUS3.New(lmNuclei, sub, Crop=True, CropBorder=1, Label=3)
# search a nice threshold - it will be based on the values of the brightests regions (spots)
rmax = itk.RegionalMaximaImageFilter.IUS3IUS3.New(mask, FullyConnected=True)
rmaxbi2lm = itk.BinaryImageToStatisticsLabelMapFilter.IUS3IUS3LM3.New(rmax, mask, FullyConnected=True)
rmaxRelabel = itk.StatisticsRelabelLabelMapFilter.LM3.New(rmaxbi2lm, Attribute="Maximum")
# and locate the spots
th = itk.BinaryThresholdImageFilter.IUS3IUC3.New(mask)
# convert them to a label map representation
bi2lm = itk.BinaryImageToStatisticsLabelMapFilter.IUC3IUS3LM3.New(th, sub, FullyConnected=True) 

# visualisation
result = itk.LabelMap._3.New(Regions=itk.size(cenp))

# border = itk.LabelContourImageFilter.IUC3IUC3.New(auto_progress=False)#, FullyConnected=True)
# obo3 = itk.ObjectByObjectLabelMapFilter.LM3.New(li2lm, Filter=border, PadSize=6)
border = itk.LabelContourImageFilter.IUC2IUC2.New(auto_progress=False)#, FullyConnected=True)
slice = itk.SliceBySliceImageFilter.IUC3IUC3.New(nuclei, Filter=border)
obo3 = itk.LabelImageToLabelMapFilter.IUC3LM3.New(slice) 
obo3()

dilate2 = itk.BinaryDilateImageFilter.IUC3IUC3SE3.New(Kernel=itk.strel(3,[3,3,1]), auto_progress=False)
dilate3 = itk.BinaryDilateImageFilter.IUC3IUC3SE3.New(dilate2, Kernel=itk.FlatStructuringElement._3.Cross(1), auto_progress=False)
border2 = itk.SubtractImageFilter.IUC3IUC3IUC3.New(dilate3, dilate2, auto_progress=False)
obo2 = itk.ObjectByObjectLabelMapFilter.LM3.New(bi2lm, InputFilter=dilate2, OutputFilter=border2, PadSize=6)

crop = itk.AutoCropLabelMapFilter.LM3.New(result, CropBorder=[30,30,10])
window = itk.IntensityWindowingImageFilter.IUS3IUS3.New(cenp, OutputMinimum=0, OutputMaximum=255)
if argv[2] == "Ball":
    print "Ball"
    strel = itk.FlatStructuringElement[2].Ball(int(argv[3]))
elif argv[2] == "Box":
    print "Box"
    strel = itk.FlatStructuringElement[2].Box(int(argv[3]))
elif argv[2] == "FromImage":
    print "FromImage"
    reader = itk.ImageFileReader.IUC2.New(FileName=argv[3])
    strel = itk.FlatStructuringElement[2].FromImageUC(reader.GetOutput())
else:
    print "invalid arguement: " + argv[2]
    exit(1)

img = strel.GetImageUC()
size = itk.size(img)
for y in range(0, size.GetElement(1)):
    for x in range(0, size.GetElement(0)):
        if img.GetPixel([x, y]):
            print "X",
        else:
            print " ",
    print "\n",

itk.write(img, argv[1])

# writer = itk.ImageFileWriter.IUC2.New(FileName=argv[1], Input=img )
# itk.echo(writer)
# writer.Update()
Example #31
0
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

# test size
s = itk.size(reader)
assert s[0] == s[1] == 256
s = itk.size(reader.GetOutput())
assert s[0] == s[1] == 256

# test physical size
s = itk.physical_size(reader)
assert s[0] == s[1] == 256.0
s = itk.physical_size(reader.GetOutput())
assert s[0] == s[1] == 256.0

# test spacing
s = itk.spacing(reader)
assert s[0] == s[1] == 1.0
s = itk.spacing(reader.GetOutput())
assert s[0] == s[1] == 1.0
def ConvertRF2BMode(inputFilePath, outputFilePath):

    ## Check
    print inputFilePath
    print outputFilePath
    ## Initialize
    Dimension = 3

    ## Load RF data
    InputPixelType = itk.F
    ImageType = itk.Image[InputPixelType, Dimension]
    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName(inputFilePath)
    # reader.Update()

    ## Generate Pre-Scanconversion Data from the RF file
    PreSc_BMode_Filter = itk.BModeImageFilter[ImageType, ImageType].New()
    PreSc_BMode_Filter.SetInput(reader.GetOutput())
    PreSc_BMode_Filter.SetDirection(1)
    # PreSc_BMode_Filter.Update()
    PreSc_BMode = PreSc_BMode_Filter.GetOutput()

    InputRF_Size = itk.size(PreSc_BMode)
    print '----------------'
    print InputRF_Size[0]
    print InputRF_Size[1]
    print InputRF_Size[2]

    RF_Sz_Z = InputRF_Size[2]

    # output_size = (1108, 725, RF_Sz_Z)
    #
    # print "---- Before ----"
    # print "The type of RF_Sz_Z: %s" % type(RF_Sz_Z)
    # print "The type of output_size: %s" % type(output_size)
    #
    # print "---- After -----"
    # RF_Sz_Z_Int = int(RF_Sz_Z)
    # output_size_Int = (1108, 725, RF_Sz_Z_Int)
    # print "The type of RF_Sz_Z_Int: %s" % type(RF_Sz_Z_Int)
    # print "The type of output_size_Int: %s" % type(output_size_Int)

    ## Scanconversion
    #01. Rescale the image's intensity
    CurvilinearImageType = itk.CurvilinearArraySpecialCoordinatesImage[
        itk.UC, Dimension]
    rescale_filter = itk.RescaleIntensityImageFilter[
        ImageType, CurvilinearImageType].New()
    #rescale_filter.SetInput(PreSc_BMode)#(bmode_filter.GetOutput())
    rescale_filter.SetInput(PreSc_BMode_Filter.GetOutput())
    rescale_filter.UpdateLargestPossibleRegion()
    curvilinear = rescale_filter.GetOutput()

    # writer = itk.ImageFileWriter[CurvilinearImageType].New()
    # writer.SetFileName(outputFilePath)
    # writer.SetInput(curvilinear)
    # writer.Update()

    #02. Scanconversion
    curvilinear_size = curvilinear.GetLargestPossibleRegion().GetSize()

    #lateral_angular_separation = (np.pi / 2.0 + np.pi / 4.0) / (curvilinear_size[1] - 1)
    lateral_angular_separation = (np.pi / 2.0) / (curvilinear_size[1] - 1)
    radius_start = 12.4
    radius_stop = 117.5

    curvilinear.SetLateralAngularSeparation(lateral_angular_separation)
    curvilinear.SetFirstSampleDistance(radius_start)
    curvilinear.SetRadiusSampleSize(
        (radius_stop - radius_start) / (curvilinear_size[0] - 1))

    #output_size = (800, 800)
    #output_size = (1108, 725)
    output_size = (int(1108), int(725), int(RF_Sz_Z))

    print output_size

    output_spacing = (float(0.15), float(0.15), float(0.15))
    output_origin = [float(0.0), float(0.0), float(0.0)]
    output_origin[0] = float(output_size[0] * output_spacing[0] / -2.0)
    output_origin[1] = float(radius_start * np.cos(np.pi / 4.0))

    UCharImageType = itk.Image[itk.UC, Dimension]
    resample_filter = itk.ResampleImageFilter[CurvilinearImageType,
                                              UCharImageType].New()
    resample_filter.SetInput(curvilinear)
    resample_filter.SetSize(output_size)
    resample_filter.SetOutputSpacing(output_spacing)
    resample_filter.SetOutputOrigin(output_origin)
    resample_filter.UpdateLargestPossibleRegion()

    bmode_image2 = resample_filter.GetOutput()
    bmode_image2.DisconnectPipeline()

    writer = itk.ImageFileWriter[UCharImageType].New()
    writer.SetFileName(outputFilePath)
    writer.SetInput(bmode_image2)
    writer.Update()

    print '------------------------'
    print 'Done'
Example #33
0
PIXWIDTH %(pixelWidth)s;
PIXHEIGHT %(pixelHeight)s;
RELPOSITION %(sliceSpacing)s;
"""
# and a line per slice
sliceDescriptorTpl = "SLICE %(sliceName)s %(fileName)s;\n"

# lets convert all the files
for f in sys.argv[2:] :
	# display the file name, to know on what we are working
	log( f )
	
	# change the file name
	reader.SetFileName( f )
	
	numberOfSlices = itk.size( reader )[2]
	spacing = itk.spacing( reader )
	lsmName = f[:-4]
	
	descriptorDir = "%s/%s/sdf" % ( destDir, lsmName )
	mkdir( descriptorDir )
		
	# set the number of slices for the name generator
	names.SetEndIndex( numberOfSlices - 1 )
	
	# now iterate over all the channel
	for c in range( 0, reader.GetNumberOfChannels() ) :
		channelName = reader.SetChannel( c )
		
		# again, print the channel name  to know what is done currently
		log( channelName )
Example #34
0
def checkerboard(image1,
                 image2,
                 pattern=3,
                 invert=False,
                 **viewer_kwargs):  # noqa: C901
    """Compare two images with a checkerboard pattern.

    This is particularly useful for examining registration results.

    Parameters
    ----------
    image1 : array_like, itk.Image, or vtk.vtkImageData
        First image to use in the checkerboard.

    image2 : array_like, itk.Image, or vtk.vtkImageData
        Second image to use in the checkerboard.

    pattern : int, optional, default: 3
        Size of the checkerboard pattern.

    invert : bool, optional, default: False
        Swap inputs.

    viewer_kwargs : optional
        Keyword arguments for the viewer. See help(itkwidgets.view).

    """

    itk_image1 = to_itk_image(image1)
    itk_image2 = to_itk_image(image2)
    input1 = itk_image1
    input2 = itk_image2

    region_image1 = itk_image1.GetLargestPossibleRegion()
    region_image2 = itk_image2.GetLargestPossibleRegion()
    same_physical_space = \
        np.allclose(np.array(itk_image1.GetOrigin()), np.array(itk_image2.GetOrigin())) and \
        np.allclose(np.array(itk_image1.GetSpacing()), np.array(itk_image2.GetSpacing())) and \
        itk_image1.GetDirection() == itk_image2.GetDirection() and \
        np.allclose(np.array(region_image1.GetIndex()), np.array(region_image2.GetIndex())) and \
        np.allclose(
            np.array(
                region_image1.GetSize()), np.array(
                region_image2.GetSize()))
    if not same_physical_space:
        upsample_image2 = True
        if itk_image1.GetSpacing() != itk_image2.GetSpacing():
            min1 = min(itk_image1.GetSpacing())
            min2 = min(itk_image2.GetSpacing())
            if min2 < min1:
                upsample_image2 = False
        else:
            size1 = max(itk.size(itk_image1))
            size2 = max(itk.size(itk_image1))
            if size2 > size1:
                upsample_image2 = False

        if upsample_image2:
            resampler = itk.ResampleImageFilter.New(itk_image2)
            resampler.UseReferenceImageOn()
            resampler.SetReferenceImage(itk_image1)
            resampler.Update()
            input2 = resampler.GetOutput()
        else:
            resampler = itk.ResampleImageFilter.New(itk_image1)
            resampler.UseReferenceImageOn()
            resampler.SetReferenceImage(itk_image2)
            resampler.Update()
            input1 = resampler.GetOutput()

    checkerboard_filter = itk.CheckerBoardImageFilter.New(input1, input2)

    dimension = itk_image1.GetImageDimension()
    checker_pattern = [pattern] * dimension
    checkerboard_filter.SetCheckerPattern(checker_pattern)
    checkerboard_filter_inverse = itk.CheckerBoardImageFilter.New(
        input2, input1)

    if invert:
        checkerboard_filter_inverse.Update()
        checkerboard = checkerboard_filter_inverse.GetOutput()
    else:
        checkerboard_filter.Update()
        checkerboard = checkerboard_filter.GetOutput()

    if 'annotations' not in viewer_kwargs:
        viewer_kwargs['annotations'] = False
    if 'interpolation' not in viewer_kwargs:
        viewer_kwargs['interpolation'] = False
    if 'ui_collapsed' not in viewer_kwargs:
        viewer_kwargs['ui_collapsed'] = True
    viewer = Viewer(image=checkerboard, **viewer_kwargs)

    # Heuristic to specify the max pattern size
    max_size1 = int(min(itk.size(itk_image1)) / 8)
    max_size1 = max(max_size1, pattern * 2)
    max_size2 = int(min(itk.size(itk_image2)) / 8)
    max_size2 = max(max_size2, pattern * 2)
    max_size = max(max_size1, max_size2)

    pattern_slider = widgets.IntSlider(value=pattern,
                                       min=2,
                                       max=max_size,
                                       step=1,
                                       description='Pattern size:')
    invert_checkbox = widgets.Checkbox(value=invert, description='Invert')

    def update_checkerboard(change):
        checker_pattern = [pattern_slider.value] * dimension
        checkerboard_filter.SetCheckerPattern(checker_pattern)
        checkerboard_filter_inverse.SetCheckerPattern(checker_pattern)
        if invert_checkbox.value:
            checkerboard_filter_inverse.Update()
            viewer.image = checkerboard_filter_inverse.GetOutput()
        else:
            checkerboard_filter.Update()
            viewer.image = checkerboard_filter.GetOutput()

    pattern_slider.observe(update_checkerboard, ['value'])
    invert_checkbox.observe(update_checkerboard, ['value'])

    widget = widgets.VBox(
        [viewer, widgets.HBox([pattern_slider, invert_checkbox])])

    return widget
Example #35
0
def copy_images(images_training, images_test, task_id, task_name_3D,
                trainingimage_ch0_name, trainingimage_ch1_name,
                testimage_ch0_name, testimage_ch1_name, ROI_list,
                ROI_list_alternatenames, label_dict):

    image_identifier_3D = 'CBCT_3D'

    # copy the 3D cbct images to imagesTr in .nii.gz format
    global taskfolder_3D
    taskfolder_3D = f'{nnUNet_raw_data}/Task{task_id:03d}_{task_name_3D}'
    json_filename_3D = f'{taskfolder_3D}/dataset.json'
    imagesTr_foldername_3D = f'{taskfolder_3D}/imagesTr/'
    imagesTs_foldername_3D = f'{taskfolder_3D}/imagesTs/'
    labelsTr_foldername_3D = f'{taskfolder_3D}/labelsTr/'
    labelsTs_foldername_3D = f'{taskfolder_3D}/labelsTs/'

    maybe_mkdir_p(imagesTr_foldername_3D)
    maybe_mkdir_p(imagesTs_foldername_3D)
    maybe_mkdir_p(labelsTr_foldername_3D)
    maybe_mkdir_p(labelsTs_foldername_3D)
    open(f"{taskfolder_3D}/errorlog.txt", "w").close()

    train_patient_names = []
    test_patient_names = []
    patient_ind = 0
    for patient_folder in sorted(glob.glob(f'{images_training}/*')):
        print(patient_folder)

        with open(f'{taskfolder_3D}/errorlog.txt', 'a') as f:
            f.write(str(patient_ind) + " - " + patient_folder + ": \n")

        casename_3D = f'{image_identifier_3D}_{patient_ind:04d}'
        train_patient_names.append(casename_3D)

        # channel 1 = simu CBCT
        if 'CLB' in patient_folder:
            if (apply_matching == False) & ('correctedN4'
                                            in trainingimage_ch1_name):
                cbct_image_path = f'{patient_folder}/{realCBCT_N4imagename}'
            elif (apply_matching == False) & ('swn_normalized'
                                              in trainingimage_ch1_name):
                cbct_image_path = f'{patient_folder}/{realCBCT_SWNimagename}'
            else:
                cbct_image_path = glob.glob(f'{patient_folder}/cbct*.mhd')[0]
        else:
            cbct_image_path = f'{patient_folder}/{trainingimage_ch1_name}'

        # reduce image size and save in the 3D task folder
        cbct_3D_filename = f'{imagesTr_foldername_3D}/{casename_3D}_0001.nii.gz'

        #if (apply_matching == False) & ('correctedN4' in trainingimage_name): # no need to resize, already 2 mm spacing
        #    #shutil.copy(cbct_image_path, imagesTr_foldername_3D)
        #    #os.rename(f'{imagesTr_foldername_3D}/{trainingimage_name}', cbct_3D_filename)
        #    convert_command= f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
        #else:
        #    convert_command= f'gt_affine_transform -i {cbct_image_path} --newspacing=2,2,2 -o {cbct_3D_filename} -fr -a'

        if spacing2mm == True:
            convert_command = f'gt_affine_transform -i {cbct_image_path} --newspacing=2,2,2 -o {cbct_3D_filename} -fr -a'
            os.system(convert_command)
        else:
            convert_command = f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
            os.system(convert_command)

        # load the simu CBCT image to get the size
        cbct_image = itk.imread(cbct_3D_filename)
        cbct_origin = cbct_image.GetOrigin()

        # channel 0 = real CT
        if 'CLB' in patient_folder:
            if (apply_matching == False) & ('correctedN4'
                                            in trainingimage_ch0_name):
                ct_image_path = f'{patient_folder}/{realCBCT_N4imagename}'
            elif (apply_matching == False) & ('swn_normalized'
                                              in trainingimage_ch0_name):
                ct_image_path = f'{patient_folder}/{realCBCT_SWNimagename}'
            else:
                ct_image_path = glob.glob(f'{patient_folder}/cbct*.mhd')[0]
        else:
            ct_image_path = f'{patient_folder}/{trainingimage_ch0_name}'

        # reduce image size and save in the 3D task folder
        ct_3D_filename = f'{imagesTr_foldername_3D}/{casename_3D}_0000.nii.gz'

        ct_image = itk.imread(ct_image_path)
        # resize the image to same size as the simulated cbct
        if itk.size(cbct_image) == itk.size(ct_image):
            if spacing2mm == True:
                convert_command = f'gt_affine_transform -i {ct_image_path} --newspacing=2,2,2 -o {ct_3D_filename} -fr -a'
                os.system(convert_command)
            else:
                convert_command = f'gt_image_convert {ct_image_path} -o {ct_3D_filename}'
                os.system(convert_command)

        else:
            ct_image = gt.applyTransformation(input=ct_image,
                                              like=cbct_image,
                                              force_resample=True,
                                              pad=-1024)
            itk.imwrite(ct_image, ct_3D_filename)

        # copy and register label (ROI) with the cbct
        ROI_dir = f'{patient_folder}/ROI'
        allRoisImage = create_segmentation_map(ROI_list,
                                               ROI_list_alternatenames,
                                               ROI_dir, cbct_3D_filename, '')
        label_3D_filename = f'{labelsTr_foldername_3D}/{casename_3D}.nii.gz'
        if cropimages == True:
            crop_training_images(cbct_3D_filename, ct_3D_filename,
                                 label_3D_filename, allRoisImage)
        else:
            itk.imwrite(allRoisImage, label_3D_filename)

        patient_ind = patient_ind + 1

    #patient_ind = patient_ind + 1

    for patient_folder in sorted(glob.glob(f'{images_test}/*')):

        # if rennes images, the name of the cbct is different and there are more than one cbct per patient
        if 'Rennes' in patient_folder:
            cbctimage_prefix = 'cbct'
            ctimage_prefix = 'pseudo_rec'

            if (apply_matching == False) & ('correctedN4'
                                            in testimage_ch0_name):

                for cbct_image_path in sorted(
                        glob.glob(
                            f'{patient_folder}/{cbctimage_prefix}*_N4folder/{realCBCT_N4imagename}'
                        )):
                    cbct_id = os.path.dirname(cbct_image_path).replace(
                        f'{patient_folder}/{cbctimage_prefix}',
                        '').replace('_N4folder', '')
                    with open(f'{taskfolder_3D}/errorlog.txt', 'a') as f:
                        f.write(
                            str(patient_ind) + " - " + patient_folder +
                            " - cbct id " + cbct_id + " : \n")
                    print(patient_folder)

                    casename_3D = f'{image_identifier_3D}_{patient_ind:04d}'
                    test_patient_names.append(casename_3D)

                    # channel 1 = real CBCT
                    # save in 3D_outputfolder
                    cbct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0001.nii.gz'

                    #convert_command= f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                    #os.system(convert_command)

                    if spacing2mm == True:
                        convert_command = f'gt_affine_transform -i {cbct_image_path} --newspacing=2,2,2 -o {cbct_3D_filename} -fr -a'
                        os.system(convert_command)
                    else:
                        convert_command = f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                        os.system(convert_command)

                    # load the real CBCT image to get the size
                    cbct_image = itk.imread(cbct_3D_filename)
                    cbct_origin = cbct_image.GetOrigin()

                    # channel 0 = pseudo CT
                    ct_image_path = cbct_image_path.replace(
                        'realCBCT', 'pseudoCT')

                    # save in the 3D task folder
                    ct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0000.nii.gz'

                    ct_image = itk.imread(ct_image_path)
                    # resize the image to same size as the real cbct
                    ct_image = gt.applyTransformation(input=ct_image,
                                                      like=cbct_image,
                                                      force_resample=True,
                                                      pad=-1024)
                    itk.imwrite(ct_image, ct_3D_filename)

                    # copy and register label (ROI) with the cbct
                    ROI_dir = f'{patient_folder}/ROI'
                    allRoisImage = create_segmentation_map(
                        ROI_list, ROI_list_alternatenames, ROI_dir,
                        cbct_3D_filename, cbct_id)
                    label_3D_filename = f'{labelsTs_foldername_3D}/{casename_3D}.nii.gz'
                    itk.imwrite(allRoisImage, label_3D_filename)

                    patient_ind = patient_ind + 1

            elif (apply_matching == False) & ('swn_normalized'
                                              in testimage_ch0_name):

                for cbct_image_path in sorted(
                        glob.glob(
                            f'{patient_folder}/{cbctimage_prefix}*_SWNfolder/{realCBCT_SWNimagename}'
                        )):
                    cbct_id = os.path.dirname(cbct_image_path).replace(
                        f'{patient_folder}/{cbctimage_prefix}',
                        '').replace('_SWNfolder', '')
                    with open(f'{taskfolder_3D}/errorlog.txt', 'a') as f:
                        f.write(
                            str(patient_ind) + " - " + patient_folder +
                            " - cbct id " + cbct_id + " : \n")
                    print(patient_folder)

                    casename_3D = f'{image_identifier_3D}_{patient_ind:04d}'
                    test_patient_names.append(casename_3D)

                    # channel 1 = real CBCT
                    # save in 3D_outputfolder
                    cbct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0001.nii.gz'

                    #convert_command= f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                    #os.system(convert_command)

                    if spacing2mm == True:
                        convert_command = f'gt_affine_transform -i {cbct_image_path} --newspacing=2,2,2 -o {cbct_3D_filename} -fr -a'
                        os.system(convert_command)
                    else:
                        convert_command = f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                        os.system(convert_command)

                    # load the real CBCT image to get the size
                    cbct_image = itk.imread(cbct_3D_filename)
                    cbct_origin = cbct_image.GetOrigin()

                    # channel 0 = pseudo CT
                    ct_image_path = cbct_image_path.replace(
                        'realCBCT', 'pseudoCT')

                    # save in the 3D task folder
                    ct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0000.nii.gz'

                    ct_image = itk.imread(ct_image_path)
                    # resize the image to same size as the real cbct
                    ct_image = gt.applyTransformation(input=ct_image,
                                                      like=cbct_image,
                                                      force_resample=True,
                                                      pad=-1024)
                    itk.imwrite(ct_image, ct_3D_filename)

                    # copy and register label (ROI) with the cbct
                    ROI_dir = f'{patient_folder}/ROI'
                    allRoisImage = create_segmentation_map(
                        ROI_list, ROI_list_alternatenames, ROI_dir,
                        cbct_3D_filename, cbct_id)
                    label_3D_filename = f'{labelsTs_foldername_3D}/{casename_3D}.nii.gz'
                    itk.imwrite(allRoisImage, label_3D_filename)

                    patient_ind = patient_ind + 1

            else:

                for cbct_image_path in sorted(
                        glob.glob(
                            f'{patient_folder}/{cbctimage_prefix}*.nii.gz')):
                    cbct_id = os.path.basename(cbct_image_path).replace(
                        f'{cbctimage_prefix}', '').replace('.nii.gz', '')

                    with open(f'{taskfolder_3D}/errorlog.txt', 'a') as f:
                        f.write(
                            str(patient_ind) + " - " + patient_folder +
                            " - cbct id " + cbct_id + " : \n")
                    print(patient_folder)

                    casename_3D = f'{image_identifier_3D}_{patient_ind:04d}'
                    test_patient_names.append(casename_3D)

                    # channel 1 = real CBCT
                    # convert to float
                    convert_command = f'clitkImageConvert -i {cbct_image_path} -o {cbct_image_path} -t float'
                    os.system(convert_command)

                    # save in 3D_outputfolder
                    cbct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0001.nii.gz'

                    #convert_command= f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                    #os.system(convert_command)

                    if spacing2mm == True:
                        convert_command = f'gt_affine_transform -i {cbct_image_path} --newspacing=2,2,2 -o {cbct_3D_filename} -fr -a'
                        os.system(convert_command)
                    else:
                        convert_command = f'gt_image_convert {cbct_image_path} -o {cbct_3D_filename}'
                        os.system(convert_command)

                    # channel 0 = pseudo CT
                    ct_image_path = f'{patient_folder}/{ctimage_prefix}{cbct_id}.nii.gz'

                    # convert to float
                    convert_command = f'clitkImageConvert -i {ct_image_path} -o {ct_image_path} -t float'
                    os.system(convert_command)

                    # save in the 3D task folder
                    ct_3D_filename = f'{imagesTs_foldername_3D}/{casename_3D}_0000.nii.gz'

                    # resize the image to same size as the real cbct
                    elastix_command = f'elastix -f {cbct_image_path} -m {ct_image_path} -p {elastix_param_file} -out {elastix_folder}'
                    os.system(elastix_command)

                    registered_ct_path = f'{elastix_folder}/result.0.mhd'

                    if spacing2mm == True:
                        convert_command = f'gt_affine_transform -i {registered_ct_path} --newspacing=2,2,2 -o {ct_3D_filename} -fr -a'
                        os.system(convert_command)
                    else:
                        convert_command = f'gt_image_convert {registered_ct_path} -o {ct_3D_filename}'
                        os.system(convert_command)

                    # copy and register label (ROI) with the cbct
                    ROI_dir = f'{patient_folder}/ROI'
                    allRoisImage = create_segmentation_map(
                        ROI_list, ROI_list_alternatenames, ROI_dir,
                        cbct_3D_filename, cbct_id)
                    label_3D_filename = f'{labelsTs_foldername_3D}/{casename_3D}.nii.gz'
                    itk.imwrite(allRoisImage, label_3D_filename)

                    patient_ind = patient_ind + 1

    # dataset.json 3D
    json_dict = {}
    json_dict['name'] = task_name_3D
    json_dict['description'] = ""
    json_dict['tensorImageSize'] = "4D"
    json_dict['reference'] = "saphir"
    json_dict['licence'] = ""
    json_dict['release'] = "0.0"
    json_dict['modality'] = {
        "0": "CT",
        "1": "CT",
    }

    json_dict['labels'] = label_dict

    json_dict['numTraining'] = len(train_patient_names)
    json_dict['numTest'] = len(test_patient_names)
    json_dict['training'] = [{
        'image': "./imagesTr/%s.nii.gz" % i,
        "label": "./labelsTr/%s.nii.gz" % i
    } for i in train_patient_names]
    json_dict['test'] = [
        "./imagesTs/%s.nii.gz" % i for i in test_patient_names
    ]
    save_json(json_dict, json_filename_3D)
Example #36
0
if opts.visualValidation:
  overlayNuclei = itk.LabelOverlayImageFilter.IUC3IUC3IRGBUC3.New(readerNuclei, lm2iNuclei)


readerCENP = itk.lsm(channel=1, fileName=inputImageName)
medianCENP = itk.MedianImageFilter.IUC3IUC3.New(readerCENP)
gaussianCENP = itk.SmoothingRecursiveGaussianImageFilter.IUC3IUC3.New(medianCENP, Sigma=0.05)
sizeCENP = itk.PhysicalSizeOpeningImageFilter.IUC3IUC3.New(gaussianCENP, Lambda=0.36)
subCENP = itk.SubtractImageFilter.IUC3IUC3IUC3.New(gaussianCENP, sizeCENP)
size2CENP = itk.PhysicalSizeOpeningImageFilter.IUC3IUC3.New(subCENP, Lambda=0.02)
maskCENP = itk.LabelMapMaskImageFilter.LM3IUC3.New(lmNuclei, size2CENP, Label=0)
thCENP = itk.BinaryThresholdImageFilter.IUC3IUC3.New(maskCENP, LowerThreshold=35)
statsCENP = itk.BinaryImageToStatisticsLabelMapFilter.IUC3IUC3LM3.New(thCENP, subCENP)

# create a new image to store the CENP centers, so they can be easily reused to check the distribution
cenpSpotsImg = itk.Image.UC3.New(Regions=itk.size(readerNuclei), Spacing=itk.spacing(readerNuclei))
cenpSpotsImg.Allocate()
cenpSpotsImg.FillBuffer(0)

if opts.visualValidation:
  # create a new image to store the CENP segmentation
  cenpImg = itk.LabelMap._3.New(Regions=itk.size(readerNuclei), Spacing=itk.spacing(readerNuclei))
  fullCENP = itk.LabelMapToBinaryImageFilter.LM3IUC3.New(cenpImg)
  dilateCENP = itk.BinaryDilateImageFilter.IUC3IUC3SE3.New(fullCENP, Kernel=itk.strel(3, [10, 10, 3]))
  borderCENP = itk.BinaryBorderImageFilter.IUC3IUC3.New(dilateCENP)
  outsideMask = itk.BinaryThresholdImageFilter.IUC3IUC3.New(lm2iNuclei, UpperThreshold=0)
  relabelCENP = itk.NaryRelabelImageFilter.IUC3IUC3.New(outsideMask, borderCENP)
  overlayCENP = itk.LabelOverlayImageFilter.IUC3IUC3IRGBUC3.New(readerCENP, relabelCENP)


if 'blasto' in inputImageName:
Example #37
0
assert itk.image(1) == 1


# test strel
# should work with the image type, an image instance or a filter
# and should work with a list, a tuple, an int or an itk.Size
for s in [2, (2, 2), [2, 2], itk.Size[2](2)] :
  st = itk.strel(dim, s)
  
  (tpl, param) = itk.template(st)
  assert tpl == itk.FlatStructuringElement
  assert param[0] == dim
  assert st.GetRadius().GetElement(0) == st.GetRadius().GetElement(1) == 2

# test size
s = itk.size(reader)
assert s.GetElement(0) == s.GetElement(1) == 256
s = itk.size(reader.GetOutput())
assert s.GetElement(0) == s.GetElement(1) == 256
s = itk.size(reader.GetOutput().GetPointer())
assert s.GetElement(0) == s.GetElement(1) == 256


# test range
assert itk.range(reader) == (0, 255)
assert itk.range(reader.GetOutput()) == (0, 255)
assert itk.range(reader.GetOutput().GetPointer()) == (0, 255)


# test write
itk.write(reader, sys.argv[2])
Example #38
0
if argv[2] == "Ball":
    print "Ball"
    strel = itk.FlatStructuringElement[2].Ball( int( argv[3] ) )
elif argv[2] == "Box":
    print "Box"
    strel = itk.FlatStructuringElement[2].Box( int( argv[3] ) )
elif argv[2] == "FromImage":
    print "FromImage"
    reader = itk.ImageFileReader.IUC2.New( FileName=argv[3] )
    strel = itk.FlatStructuringElement[2].FromImageUC( reader.GetOutput() )
else:
    print "invalid arguement: " + argv[2]
    exit(1)

img = strel.GetImageUC()
size = itk.size( img )
for y in range(0, size.GetElement(1)):
    for x in range(0, size.GetElement(0)):
        if img.GetPixel( [x, y] ):
            print "X",
        else:
            print " ",
    print "\n",

itk.write( img, argv[1] )

# writer = itk.ImageFileWriter.IUC2.New(FileName=argv[1], Input=img )
# itk.echo(writer)
# writer.Update()
Example #39
0
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

# test size
s = itk.size(reader)
assert s[0] == s[1] == 256
s = itk.size(reader.GetOutput())
assert s[0] == s[1] == 256

# test physical size
s = itk.physical_size(reader)
assert s[0] == s[1] == 256.0
s = itk.physical_size(reader.GetOutput())
assert s[0] == s[1] == 256.0

# test spacing
s = itk.spacing(reader)
assert s[0] == s[1] == 1.0
s = itk.spacing(reader.GetOutput())
assert s[0] == s[1] == 1.0
Example #40
0
import itk
import argparse

parser = argparse.ArgumentParser(description="Get Image Size.")
parser.add_argument("input_image")
args = parser.parse_args()

image = itk.imread(args.input_image, itk.UC)

region = image.GetLargestPossibleRegion()
size = region.GetSize()

print(size)

# Equivalently
size = itk.size(image)

print(size)

# Corresponds to the NumPy ndarray shape. Note that the ordering is reversed.
print(np.asarray(image).shape)

# An example image had w = 200 and h = 100
# (it is wider than it is tall). The above output
# 200 x 100
# so w = GetSize()[0]
# and h = GetSize()[1]

# A pixel inside the region
indexInside = itk.Index[2]()
indexInside[0] = 150
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()
import itk

Dimension = 2
PixelType = itk.UC

ImageType = itk.Image[PixelType, Dimension]

image_size = [10, 10]

image = ImageType.New()
image.SetRegions(image_size)
image.Allocate()

duplicate_image = itk.image_duplicator(image)

print(duplicate_image)

def itkSizeToList(size):
  l = []
  for i in range(size.GetSizeDimension()):
    l.append(size[i])
  return l

assert itkSizeToList(itk.size(duplicate_image)) == image_size
Example #43
0
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

# test size
s = itk.size(reader)
assert s[0] == s[1] == 256
s = itk.size(reader.GetOutput())
assert s[0] == s[1] == 256

# test physical size
s = itk.physical_size(reader)
assert s[0] == s[1] == 256.0
s = itk.physical_size(reader.GetOutput())
assert s[0] == s[1] == 256.0

# test spacing
s = itk.spacing(reader)
assert s[0] == s[1] == 1.0
s = itk.spacing(reader.GetOutput())
assert s[0] == s[1] == 1.0
Example #44
0
# binarize the image
th = itk.BinaryThresholdImageFilter.IUS2IUS2.New(proj1D, InsideValue=1)
# and count the pixels to get the resolution on the z axis
labelShape = itk.LabelShapeImageFilter.IUS2.New(th)
# count the object to display a warning
label = itk.ConnectedComponentImageFilter.IUS2IUS2.New(th)
relabel = itk.RelabelComponentImageFilter.IUS2IUS2.New(label)


for f in sys.argv[1:]:
    reader.SetFileName(f)
    projz.UpdateLargestPossibleRegion()
    m, M = itk.range(projz)
    watershed.SetLevel(m + (M - m) / 2)
    upperdim.SetNewDimensionSapcing(itk.spacing(reader)[2])
    upperdim.SetNewDimensionSize(itk.size(reader)[2])
    upperdim.UpdateLargestPossibleRegion()  # to get a valid number of labels

    # store the results so we can compute the mean and the meadian for
    # all the beads in the image
    results = []

    for l in range(1, wrelabel.GetNumberOfObjects() + 1):
        selectedLabel.SetUpperThreshold(l)
        selectedLabel.SetLowerThreshold(l)
        proj1D.UpdateLargestPossibleRegion()
        m, M = itk.range(proj1D)
        th.SetLowerThreshold((M - m) / 2)

        labelShape.UpdateLargestPossibleRegion()
        relabel.UpdateLargestPossibleRegion()