{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pydicom\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2DTranspose\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.datasets import cifar10,mnist\nimport numpy as np\nimport argparse\nimport cv2\nimport os\nfrom tensorflow.keras import layers # just randommmmm\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_dcm(filepath):\n    return pydicom.read_file(filepath)\ndef rescale_dcm_to_hounsfield_img(dcm):\n    slope, intercept = get_rescale_slope_intercept(dcm)\n    img = dcm.pixel_array\n    img = np.multiply(img, slope) + intercept\n    return img.astype('float32')\ndef get_rescale_slope_intercept(dcm):\n    slope = int(dcm.RescaleSlope)\n    intercept = int(dcm.RescaleIntercept)\n    return (slope, intercept)\ndef window_img(img, window_center, window_width):\n    windowed_img = np.copy(img)\n    px_max = window_center + (window_width // 2)\n    px_min = window_center - (window_width // 2)\n    windowed_img[windowed_img > px_max] = px_max\n    windowed_img[windowed_img < px_min] = px_min\n    return windowed_img\ndef plot_img(img):\n    plt.figure(figsize=(10,6))\n    plt.imshow(img, cmap=plt.cm.bone)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"class GAN:\n\n    def build_generator(dim, depth, channels=1, inputDim=100,\n        outputDim=512):\n        model = Sequential()\n        \n        inputShape = (dim, dim, depth)\n        chanDim = -1\n        model.add(Dense(input_dim=inputDim, units=outputDim))\n        model.add(Activation(\"relu\"))\n        model.add(BatchNormalization())\n        model.add(Dense(dim * dim * depth))\n        model.add(Activation(\"relu\"))\n        model.add(BatchNormalization())\n        model.add(Reshape(inputShape))\n        model.add(Conv2DTranspose(32, (5, 5), strides=(2, 2),padding=\"same\"))\n        model.add(Activation(\"relu\"))\n        model.add(BatchNormalization(axis=chanDim))\n        model.add(Conv2DTranspose(channels, (5, 5), strides=(2, 2),padding=\"same\"))\n        model.add(Activation(\"tanh\"))\n       # model.add(layers.Dense((), activation=\"tanh\"))\n\n        return model\n    def build_discriminator(width, height, depth, alpha=0.2):\n        model = Sequential()\n    #    print(height,width,depth)\n\n        inputShape = (height, width, depth)\n        model.add(Conv2D(32, (5, 5), padding=\"same\", strides=(2, 2),\n        input_shape=inputShape))\n        model.add(LeakyReLU(alpha=alpha))\n        model.add(Conv2D(64, (5, 5), padding=\"same\", strides=(2, 2)))\n\n        model.add(LeakyReLU(alpha=alpha))\n        model.add(Flatten())\n        print(model.output_shape)\n        model.add(Dense(512))\n        model.add(LeakyReLU(alpha=alpha))\n        model.add(Dense(1))\n        model.add(Activation(\"sigmoid\"))\n        return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#parameter\nNUM_EPOCHS = 50\nBATCH_SIZE = 5\nINIT_LR = 2e-4\nOUTPUT_PATH = '.'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dcm = load_dcm('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_test/ID_000cef503.dcm')\nimg = rescale_dcm_to_hounsfield_img(dcm)\nbone_window = window_img(img, 40, 80)\nplot_img(bone_window)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i = 0\nimageList = list()\nfor image in  os.listdir('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train'):\n    if(i<=100):\n        imageList.append(image)\n        i+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainX = list()\ntestX = list()\ni = 0\nfor e in imageList:\n    dcm = load_dcm('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train/'+e)\n    img = rescale_dcm_to_hounsfield_img(dcm)\n    bone_window = window_img(img, 40, 80)\n    if(i<=80):\n        trainX.append(bone_window)\n    else:\n        testX.append(bone_window)\n    i+=1\ntrainX = np.array(trainX)\ntestX = np.array(testX)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(testX[3])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = GAN.build_generator(128, 64, channels=1)\n#dis = GAN.build_discriminator(32, 32, 1)\ndis = GAN.build_discriminator(512, 512, 1)\ndis.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer = Adam(lr=INIT_LR, beta_1=0.5, decay=INIT_LR / NUM_EPOCHS)\ndis.compile(loss=\"binary_crossentropy\", optimizer=optimizer)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ganInput = Input(shape=(100,))\nganOutput = dis(gen(ganInput))\ngan = Model(ganInput, ganOutput)\nganOpt = Adam(lr=INIT_LR, beta_1=0.5, decay=INIT_LR / NUM_EPOCHS)\ngan.compile(loss=\"binary_crossentropy\", optimizer=optimizer)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"benchmarkNoise  = np.random.uniform(-1, 1, size=(256, 100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install imutils","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.utils import shuffle\nfrom imutils import build_montages\n#print(trainX.shape,testX.shape)\nresult = list()\ntrainImages = np.concatenate([trainX, testX])\n\ntrainImages = np.expand_dims(trainImages, axis=-1)\ntrainImages = (trainImages.astype(\"float\") - 127.5) / 127.5\n\nfor epoch in range(0, NUM_EPOCHS):\n   \n    batchesPerEpoch = int(trainImages.shape[0] / BATCH_SIZE)\n    print(batchesPerEpoch,'batch')\n    \n    for i in range(0, batchesPerEpoch):\n        p = None\n      \n        imageBatch = trainImages[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]\n        noise = np.random.uniform(-1, 1, size=(BATCH_SIZE, 100))\n      #  print(noise.shape)\n        genImages = gen.predict(noise, verbose=0)\n        imageBatch = imageBatch.reshape((BATCH_SIZE,512,512,1))\n        #print('batch gen',imageBatch.shape,genImages.shape)\n        X = np.concatenate((imageBatch, genImages))\n        del genImages,imageBatch\n        y = ([1] * BATCH_SIZE) + ([0] * BATCH_SIZE)\n        y = np.reshape(y, (-1,))\n        (X, y) = shuffle(X, y)\n\n        discLoss = dis.train_on_batch(X, y)\n        noise = np.random.uniform(-1, 1, (BATCH_SIZE, 100))\n        fakeLabels = [1] * BATCH_SIZE\n        fakeLabels = np.reshape(fakeLabels, (-1,))\n        ganLoss = gan.train_on_batch(noise, fakeLabels)\n        if i == batchesPerEpoch - 1:\n            p = [OUTPUT_PATH, \"epoch_{}_output.png\".format(str(epoch + 1).zfill(4))]\n        if p is not None:\n            print('output path ',p)\n            print('result ',epoch + 1, i,discLoss, ganLoss)\n    \n            images = gen.predict(benchmarkNoise)\n            images = ((images * 127.5) + 127.5).astype(\"uint8\")\n            images = np.repeat(images, 3, axis=-1)\n            result.append(images)\n            vis = build_montages(images, (32, 32), (16, 16))[0]\n            p = os.path.sep.join(p)\n            cv2.imwrite(p, vis)\n        if p is None:\n            print('doing',discLoss,ganLoss,epoch+1,i)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}