<jupyter_start><jupyter_text>MergeAdjacentImages Notebook This notebook contains a few examples of how to use the `MergeAdjacentImages` application from **TubeTK**. First, we will include Python's `os` package as well as `ITK` (Python wrapping). We also set the TubeTK build directory variable `TUBETK_BUILD_DIR`: If ITK is not installed in your python environment, you need to define the environment variable `ITK_BUILD_DIR` that contains the path to where ITK was built. We need to find the directory in which TubeTK was build. This is required to find the path to the testing data, and may be also required to find the TubeTK library paths if your python environment does not include it.The environment variable `TubeTK_BUILD_DIR` needs to be defined.<jupyter_code>import os
import sys
import numpy
# Path for TubeTK libs
#Values takend from TubeTK launcher

sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/")
sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/Release")

# Setting TubeTK Build Directory

TubeTK_BUILD_DIR=None
if 'TubeTK_BUILD_DIR' in os.environ:
    TubeTK_BUILD_DIR = os.environ['TubeTK_BUILD_DIR']
else:
    print('TubeTK_BUILD_DIR not found!')
    print('  Set environment variable')
    os.environ["TubeTK_BUILD_DIR"] = "C:/src/TubeTK_Python_ITK/TubeTK-build"
    TubeTK_BUILD_DIR = os.environ["TubeTK_BUILD_DIR"]
    #sys.exit( 1 )
    
if not os.path.exists(TubeTK_BUILD_DIR):
    print('TubeTK_BUILD_DIR set by directory not found!')
    print('  TubeTK_BUILD_DIR = ' + TubeTK_BUILD_DIR )
    sys.exit(1) 
try:
    import itk
except:
    ITK_BUILD_DIR = None
    if 'ITK_BUILD_DIR' in os.environ:
        ITK_BUILD_DIR = os.environ['ITK_BUILD_DIR']
    else:
        print('ITK_BUILD_DIR not found!')
        print('  Set environment variable')
        os.environ["ITK_BUILD_DIR"] = "C:/src/TubeTK_Python_R/ITK-build"
        ITK_BUILD_DIR = os.environ["ITK_BUILD_DIR"]
        #sys.exit( 1 )

    if not os.path.exists(ITK_BUILD_DIR):
        print('ITK_BUILD_DIR set by directory not found!')
        print('  ITK_BUIDL_DIR = ' + ITK_BUILD_DIR )
        sys.exit(1)
    # Append ITK libs
    sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/Wrapping/Generators/Python/Release")
    sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/lib/Release")
    sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/lib")
    
    # Append TubeTK libs
    sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/ITKModules/TubeTKITK-build/Wrapping/Generators/Python/Release")
    import itk
from itk import TubeTKITK as itktube

import matplotlib.pyplot as plt
from matplotlib import cm

%matplotlib inline<jupyter_output><empty_output><jupyter_text>Next, we load the first input image and show it's origin, spacing, etc.:<jupyter_code>input_image1 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data\ES0015_Large.mha')
reader0 = itk.ImageFileReader.New(FileName=input_image1)
reader0.Update()
im0=reader0.GetOutput()
print("Origin:")
print im0.GetOrigin()
print("Spacing:")
print im0.GetSpacing()
print("Direction:")
print im0.GetDirection()<jupyter_output>Origin:
itkPointD2 ([200, 200])
Spacing:
itkVectorD2 ([1, 1])
Direction:
<itkMatrixPython.itkMatrixD22; proxy of <Swig Object of type 'itkMatrixD22 *' at 0x000000000C4C1390> ><jupyter_text>We get the `numpy` array for the image and visualize it:<jupyter_code>ImageType=itk.Image[itk.F,2]
im_np0 = itk.PyBuffer[ImageType].GetArrayFromImage(im0)
plt.imshow(im_np0, cm.gray)<jupyter_output><empty_output><jupyter_text>Let's do the same for the second image:<jupyter_code>input_image0 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data\ES0015_Large_Wo_offset.mha')
print("Image file path:%s"%input_image0)
reader1 = itk.ImageFileReader.New(FileName=input_image0)
reader1.Update()
im1=reader1.GetOutput()
print im1.GetOrigin()
print im1.GetSpacing()
print im1.GetDirection()
im_np1 = itk.PyBuffer[ImageType].GetArrayFromImage(im1)
plt.imshow(im_np1, cm.gray)<jupyter_output><empty_output><jupyter_text>Let's check if the spacing and direction are compatible:<jupyter_code>im0.GetSpacing() == im1.GetSpacing() and im0.GetDirection() == im1.GetDirection()<jupyter_output><empty_output><jupyter_text>We see that `im0` and `im1` are in fact compatible, but the origin of `im0` is at (200, 200).  Merging - Example 1 In this example, we just want to merge our two images (**without registration**). Let's build the command-line arguments (The output image will be written to `/tmp/merged.mha`).<jupyter_code>output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary\Python.MergeAdjacentImages-Ex1.mha')
cmd = [os.path.join(TubeTK_BUILD_DIR, 'bin\Release\MergeAdjacentImages'),
       '-i', '0', # Number of iterations ... here i=0, which means no registration,
       input_image0, # First image to merge
       input_image1, # Second image to merge
       output_image
      ]<jupyter_output><empty_output><jupyter_text>Let's execute that command (via the `subprocess` module):<jupyter_code>import subprocess
subprocess.call(cmd)<jupyter_output><empty_output><jupyter_text>... and check if the output image `/tmp/merged.mha` was actually written to disk:<jupyter_code>print os.path.exists(output_image)<jupyter_output>True<jupyter_text>We are now ready to visualize the result:<jupyter_code>output_reader = itk.ImageFileReader.New(FileName=output_image)
output_reader.Update()
out_im=output_reader.GetOutput()
print out_im.GetOrigin()
print out_im.GetSpacing()
print out_im.GetLargestPossibleRegion().GetSize()
plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(out_im), cm.gray)<jupyter_output><empty_output><jupyter_text>We see that the output image is larger by 212 pixel in both dimensions, since the second image's origin was at (200, 200) and theimage size of both images was 512 times 512 pixel.  Merging - Example 2 We can also add some padding (e.g., 50 pixel on each side). For that we modify `cmd` as follows:<jupyter_code>output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary/Python.MergeAdjacentImages-Ex2.mha')

cmd1 = [os.path.join(TubeTK_BUILD_DIR, 'bin/Release/MergeAdjacentImages'),
       '-i','0', # Number of iterations ... here i=0, which means no registration,
       '-b','50,50', # This adds a white border around the second image (50 pixel each side)
       input_image0,
       input_image1,
       output_image
      ]
subprocess.call(cmd1)
reader=itk.ImageFileReader.New(FileName=output_image)
reader.Update()
plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(reader.GetOutput()), cm.gray)<jupyter_output>[2000D[KitkImageFileReaderIF2: 0.000000[2000D[KitkImageFileReaderIF2: 1.000000[2000D[K<jupyter_text>Merging - Example 3 Let's do the same example **WITH** rigid registration.<jupyter_code>output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary/Python.MergeAdjacentImages-Ex3.mha')

cmd = [os.path.join(TubeTK_BUILD_DIR, 'bin/Release/MergeAdjacentImages'),
       input_image1,
       input_image0,
       output_image
      ]
subprocess.call(cmd)
reader=itk.ImageFileReader.New(FileName=output_image)
reader.Update()
plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(reader.GetOutput()), cm.gray)<jupyter_output>[2000D[KitkImageFileReaderIF2: 0.000000[2000D[KitkImageFileReaderIF2: 1.000000[2000D[K
{'fraction_non_alphanumeric': 0.1127091688563131, 'fraction_numerical': 0.024477942193334254, 'mean_word_length': 5.468694096601073, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '90465', 'license': 'Apache-2.0', 'n_tokens_mistral': 2712, 'n_tokens_neox': 2513, 'n_words': 566, 'path': 'docs/examples/MergeAdjacentImages/MergeAdjacentImages.ipynb', 'repo_name': 'jsdelivrbot/ITKTubeTK', 'size': '7231'}