text_plain_output_1.png
from pydicom.pixel_data_handlers.util import apply_voi_lut

from tensorflow import keras

import cv2

import glob

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import pydicom

import re

import tensorflow as tf

data_directory = '../input/rsna-miccai-brain-tumor-radiogenomic-classification'
pytorch3dpath = '../input/efficientnetpyttorch3d/EfficientNet-PyTorch-3D'
mri_types = ['FLAIR', 'T1w', 'T1wCE', 'T2w']
IMAGE_SIZE = 256
NUM_IMAGES = 64

sample_submission = pd.read_csv('../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv')
test = sample_submission
test['BraTS21ID5'] = [format(x, '05d') for x in test.BraTS21ID]

def load_dicom_image(path, img_size=IMAGE_SIZE, voi_lut=True, rotate=0):
    dicom = pydicom.read_file(path)
    data = dicom.pixel_array
    if voi_lut:
        data = apply_voi_lut(dicom.pixel_array, dicom)
    else:
        data = dicom.pixel_array
    if rotate > 0:
        rot_choices = [0, cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE, cv2.ROTATE_180]
        data = cv2.rotate(data, rot_choices[rotate])
    data = cv2.resize(data, (img_size, img_size))
    return data
def load_dicom_images_3d(scan_id, num_imgs=NUM_IMAGES, img_size=IMAGE_SIZE, mri_type='FLAIR', split='test', rotate=0):
    files = sorted(glob.glob(f'{data_directory}/{split}/{scan_id}/{mri_type}/*.dcm'), key=lambda var: [int(x) if x.isdigit() else x for x in re.findall('[^0-9]|[0-9]+', var)])
    middle = len(files) // 2
    num_imgs2 = num_imgs // 2
    p1 = max(0, middle - num_imgs2)
    p2 = min(len(files), middle + num_imgs2)
    img3d = np.stack([load_dicom_image(f, rotate=rotate) for f in files[p1:p2]]).T
    if img3d.shape[-1] < num_imgs:
        n_zero = np.zeros((img_size, img_size, num_imgs - img3d.shape[-1]))
        img3d = np.concatenate((img3d, n_zero), axis=-1)
    if np.min(img3d) < np.max(img3d):
        img3d = img3d - np.min(img3d)
        img3d = img3d / np.max(img3d)
    return np.expand_dims(img3d, 0)
a = load_dicom_images_3d('00001')
image = a[0]

def plot_slices(num_rows, num_columns, width, height, data):
    """Plot a montage of 20 CT slices"""
    data = np.rot90(np.array(data))  
    data = np.transpose(data)
    data = np.reshape(data, (num_rows, num_columns, width, height))
    rows_data, columns_data = data.shape[0], data.shape[1]
    heights = [slc[0].shape[0] for slc in data]
    widths = [slc.shape[1] for slc in data[0]]
    fig_width = 12.0
    fig_height = fig_width * sum(heights) / sum(widths)
    f, axarr = plt.subplots(
        rows_data,
        columns_data,
        figsize=(fig_width, fig_height),
        gridspec_kw={"height_ratios": heights},
    )
    for i in range(rows_data):
        for j in range(columns_data):
            axarr[i, j].imshow(data[i][j], cmap="gray")
            axarr[i, j].axis("off")
    plt.subplots_adjust(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)
    plt.show()
# Visualize montage of slices.
# 5 rows and 10 columns for 100 slices of the CT scan.
plot_slices(3, 10, 256, 256, image[:, :, :30])

test_dataset = Dataset(test, is_train=False)

for i in range(1):
    image = test_dataset[i]

model = keras.Model()
model = tf.keras.models.load_model('../input/brain-tumor-3d-weights-l/Brain_3d_cls_FLAIR.h5')

preds = model.predict(test_dataset)
preds = preds.reshape(-1)

submission = pd.DataFrame({'BraTS21ID': sample_submission['BraTS21ID'], 'MGMT_value': preds})

submission.to_csv('submission.csv', index=False)

plt.figure(figsize=(5, 5))
plt.hist(submission['MGMT_value'])