<jupyter_start><jupyter_text>Library<jupyter_code>%matplotlib inline
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pydicom
import os<jupyter_output><empty_output><jupyter_text>Function<jupyter_code>def ShowImage(title,img,ctype):
  plt.figure(figsize=(9, 9))
  if ctype=='gray':
    plt.imshow(img,cmap='gray')
  elif ctype=='rgb':
    plt.imshow(img)
  else:
    raise Exception("Unknown colour type")
  plt.axis('off')
  plt.title(title)
  plt.show()

def masking(image):
    foreground_value = 255
    mask = np.uint8(image == foreground_value)

    labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
    largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
    image = np.zeros_like(image)
    image[labels == largest_label] = foreground_value
    ShowImage('masking',image,'rgb')
basepath ="C:\\Users\\Asus\\Desktop\\tugas\\RPLB (python)\\Simple_Brain_MRI_Segmentation\\dicom\\"
d = pydicom.read_file(basepath + "Z103")
file = np.array(d.pixel_array)
img = file
img_2d = img.astype(float)
img_2d_scaled = (np.maximum(img_2d,0) / img_2d.max()) * 255.0
img_2d_scaled = np.uint8(img_2d_scaled)
hasil = img_2d_scaled
ShowImage('origin',hasil,'rgb')<jupyter_output><empty_output><jupyter_text>Gaussian Thresholding<jupyter_code>gaussian = cv2.adaptiveThreshold(hasil,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,115, 1)
# masking(gaussian)
foreground_value = 255
mask = np.uint8(gaussian == foreground_value)

labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
gaussian = np.zeros_like(gaussian)
gaussian[labels == largest_label] = foreground_value
ShowImage('gaussian',gaussian,'rgb')<jupyter_output><empty_output><jupyter_text>Erosion from Gaussian<jupyter_code>kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(gaussian,kernel,iterations = 1)

foreground_value = 255
mask = np.uint8(erosion == foreground_value)

labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
erosion = np.zeros_like(erosion)
erosion[labels == largest_label] = foreground_value
ShowImage('erosion',erosion,'rgb')<jupyter_output><empty_output><jupyter_text>Dilation from Erosion<jupyter_code>shape = np.ones((5, 5), np.uint8)
dilation = cv2.dilate(erosion,shape,iterations = 1)

foreground_value = 255
mask = np.uint8(dilation == foreground_value)

labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
dilation = np.zeros_like(dilation)
dilation[labels == largest_label] = foreground_value
ShowImage('dilation',dilation,'rgb')<jupyter_output><empty_output><jupyter_text>Skull Stripping<jupyter_code>img_2d = file.astype(float)
img_2d_scaled = (np.maximum(img_2d,0) / img_2d.max()) * 255.0
img_2d_scaled = np.uint8(img_2d_scaled)
hasil = img_2d_scaled

#Skull Stripping
skull_stripped_image = cv2.bitwise_and(hasil, hasil, mask = dilation)
brain_pixels = skull_stripped_image[dilation == foreground_value]


# Adapting the data to K-means
kmeans_input = np.float32(brain_pixels.reshape(brain_pixels.shape[0], brain_pixels.ndim))

# K-means parameters
epsilon = 0.01
number_of_iterations = 50
number_of_clusters = 4
number_of_repetition = 10
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,number_of_iterations, epsilon)
flags = cv2.KMEANS_RANDOM_CENTERS
print(criteria, "Kmeans Criteria")

# K-means segmentation
_, labels, centers = cv2.kmeans(kmeans_input, number_of_clusters, None, criteria,number_of_repetition, flags)

# Adapting the labels
labels = labels.flatten('F')
for x in range(number_of_clusters):
    labels[labels == x] = centers[x]<jupyter_output>(3, 50, 0.01) Kmeans Criteria<jupyter_text>Segmented Image<jupyter_code>segmented_image = np.zeros_like(dilation)
segmented_image[dilation == foreground_value] = labels
ShowImage('Segmented Image',segmented_image,'rgb')
plt.imsave("C:\\Users\\Asus\\Desktop\\tugas\\RPLB (python)\\Simple_Brain_MRI_Segmentation\\experiment\\hasil_perc17.jpeg", segmented_image)
image = cv2.imread('C:\\Users\\Asus\\Desktop\\tugas\\RPLB (python)\\Simple_Brain_MRI_Segmentation\\experiment\\hasil_perc17.jpeg', 0)
ShowImage('ambil',image,'rgb')
fig=plt.figure(figsize=(15, 15))
plt.subplot(2,2,1)
plt.imshow(hasil)
plt.subplot(2,2,2)
plt.imshow(segmented_image)
import numpy as np

def dice(im1, im2, empty_score=1.0):
    im1 = np.asarray(im1).astype(np.bool)
    im2 = np.asarray(im2).astype(np.bool)

    if im1.shape != im2.shape:
        raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")        
    im_sum = im1.sum() + im2.sum()

    if im_sum == 0:
        return empty_score

    # Compute Dice coefficient
    intersection = np.logical_and(im1, im2)
    return 2. * intersection.sum() / im_sum
dice(hasil,segmented_image)<jupyter_output><empty_output><jupyter_text>All in One Row<jupyter_code>basepath ="C:\\Users\\Asus\\Desktop\\tugas\\RPLB (python)\\Simple_Brain_MRI_Segmentation\\dicom\\"
IMAGE_PATHS = os.listdir("C:\\Users\\Asus\\Desktop\\tugas\\RPLB (python)\\Simple_Brain_MRI_Segmentation\\dicom\\")

list_b = []
for f in IMAGE_PATHS:
    d = pydicom.read_file(basepath+f)
    a = np.array(d.pixel_array)
    img_2d = a.astype(float)
    img_2d_scaled = (np.maximum(img_2d,0) / img_2d.max()) * 255.0
    img_2d_scaled = np.uint8(img_2d_scaled)
    hasil = img_2d_scaled

    gaussian = cv2.adaptiveThreshold(hasil,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,115, 1)
    
    foreground_value = 255
    mask = np.uint8(gaussian == foreground_value)

    labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
    largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
    gaussian = np.zeros_like(gaussian)
    gaussian[labels == largest_label] = foreground_value

    kernel = np.ones((5, 5), np.uint8)
    erosion = cv2.erode(gaussian,kernel,iterations = 1)

    foreground_value = 255
    mask = np.uint8(erosion == foreground_value)

    labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
    largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
    erosion = np.zeros_like(erosion)
    erosion[labels == largest_label] = foreground_value

    dilation = cv2.dilate(erosion,kernel,iterations = 1)

    foreground_value = 255
    mask = np.uint8(dilation == foreground_value)

    labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]
    largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
    dilation = np.zeros_like(dilation)
    dilation[labels == largest_label] = foreground_value


    #Skull Stripping
    skull_stripped_image = cv2.bitwise_and(hasil, hasil, mask = dilation)
    brain_pixels = skull_stripped_image[dilation == foreground_value]

    # Adapting the data to K-means
    kmeans_input = np.float32(brain_pixels.reshape(brain_pixels.shape[0], brain_pixels.ndim))

    # K-means parameters
    epsilon = 0.01
    number_of_iterations = 50
    number_of_clusters = 4
    number_of_repetition = 10
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,number_of_iterations, epsilon)
    flags = cv2.KMEANS_RANDOM_CENTERS

    # K-means segmentation
    _, labels, centers = cv2.kmeans(kmeans_input, number_of_clusters, None, criteria,number_of_repetition, flags)

    # Adapting the labels
    labels = labels.flatten('F')
    for x in range(number_of_clusters):
        labels[labels == x] = centers[x]

    segmented_image = np.zeros_like(dilation)
    segmented_image[dilation == foreground_value] = labels
    
    list_b.append(segmented_image)
    
fig=plt.figure(figsize=(49, 49))
columns = 6
rows = 7
for i in range(1, columns*rows +1):
    fig.add_subplot(rows, columns, i)
    plt.imshow(list_b[i])
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1290860146135111, 'fraction_numerical': 0.030637097807973336, 'mean_word_length': 5.246597277822258, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '634188', 'license': 'MIT', 'n_tokens_mistral': 3182, 'n_tokens_neox': 2972, 'n_words': 464, 'path': 'experiment/perc17.ipynb', 'repo_name': 'asyrofist/brain-segmen', 'size': '7801'}