<jupyter_start><jupyter_text>Using ITK in Python Pipelines  Learning Objectives* Learn how to write simple Python code with ITK  NumPy and scikit-learn interactions* ITK is great at reading and processing images* Some algorithms are not available in ITK* NumPy is great at processing arrays in simple ways* NumPy arrays can be read by many other Python packages    * matplotlib    * scikit-learn<jupyter_code>import itk
from itkwidgets import view

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
im=itk.imread("data/KitwareITK.jpg")
view(im)
arr=itk.array_from_image(im)
print(arr[1,1])<jupyter_output>[51 56 60]<jupyter_text>Let go the other way around: NumPy array to an ITK image. First, we create an array with some values.<jupyter_code>def make_gaussian(size, fwhm = 3, center=None):
    """ Make a square gaussian kernel.

    size is the length of a side of the square
    fwhm is full-width-half-maximum, which
    can be thought of as an effective radius.
    """

    x = np.arange(0, size, 1, np.float32)
    y = x[:,np.newaxis]

    if center is None:
        x0 = y0 = size // 2
    else:
        x0 = center[0]
        y0 = center[1]

    return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)


arr = make_gaussian(11)<jupyter_output><empty_output><jupyter_text>Let's look at the array. We use matplotlib to do this.<jupyter_code>plt.gray()
plt.imshow(arr)
plt.axis('off')
im = itk.image_view_from_array(arr)
view(im,cmap='Grayscale')<jupyter_output><empty_output><jupyter_text>Exercises  Exercise 1: Visualize an image* Read an image with ITK* Apply a filter* Show both original image and filtered images with matplotlib<jupyter_code># %load solutions/4_ITK_and_NumPy_answers_Exercise1.py<jupyter_output><empty_output><jupyter_text>scikit-learn * scikit-learn is a machine learning package in Python.* It is used to illustrate solving a problem using ITK and NumPy arrays.<jupyter_code>import sklearn<jupyter_output><empty_output><jupyter_text>First, we load 10 2D-images of circles with different radii and center position to which some noise has been added, and their corresponding ground truth segmentations.<jupyter_code>l_label=[]
l_im=[]

for i in range(0,10):
    imageName='data/sklearn/im%d.nrrd'%i
    im=itk.imread(imageName,itk.F)
    arr = itk.array_from_image(im)
    l_im.append(arr)
    
    labelName='data/sklearn/im%d_label.nrrd'%i
    im=itk.imread(labelName,itk.UC)
    arr = itk.array_from_image(im)
    l_label.append(arr)
    
size=itk.size(im)
print(size)

plt.subplot(1, 2, 1)
plt.imshow(l_im[0])
plt.title("Image")

plt.subplot(1, 2, 2)
plt.imshow(l_label[0])
plt.title("Segmentation")<jupyter_output>itkSize2 ([50, 50])<jupyter_text>The goal is to find the segmentation based on the input image. We create arrays of data:* X - the input samples* Y - the target values<jupyter_code>X0=l_im[0].flatten()
X=X0

Y=l_label[0].flatten()

for i in range(1,10):
    X=np.concatenate((X, l_im[i].flatten()))
    Y=np.concatenate((Y, l_label[i].flatten()))<jupyter_output><empty_output><jupyter_text>* We use a supervised learning methods based on applying Bayes’ theorem.* The only information provided to the algorithm is the image intensity value.<jupyter_code>from sklearn.naive_bayes import GaussianNB

clf = GaussianNB()
clf.fit(X.reshape(-1,1), Y)

result=clf.predict(X0.reshape(-1,1)).reshape(size[0],size[1])
plt.imshow(result)<jupyter_output><empty_output><jupyter_text>To improve our segmentation, we filter the input image with a median image filter and add this information as a second sample vector.<jupyter_code>l_median=[]
for i in range(0,10):
    imageName='data/sklearn/im%d.nrrd'%i
    im=itk.imread(imageName,itk.F)
    
    median=itk.median_image_filter(im, radius=3)
    
    arr = itk.array_from_image(median)
    l_median.append(arr)

M0=l_median[0].flatten()
M=M0
X0=np.concatenate((X0.reshape(-1,1),M0.reshape(-1,1)), axis=1)
for i in range(1,10):
    M=np.concatenate((M, l_median[i].flatten()))

X = np.concatenate((X.reshape(-1,1),M.reshape(-1,1)), axis=1)
clf.fit(X, Y)
result=clf.predict(X0).reshape(50,50)
plt.imshow(result)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12301396244583535, 'fraction_numerical': 0.022388059701492536, 'mean_word_length': 5.030478955007257, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '662568', 'license': 'Apache-2.0', 'n_tokens_mistral': 1617, 'n_tokens_neox': 1551, 'n_words': 385, 'path': '2_ITK_in_Python.ipynb', 'repo_name': 'vicory/CourseInBiomedicalImageAnalysisVisualizationAndArtificialIntelligence', 'size': '4154'}