{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\nimport matplotlib.pyplot as plt\nimport pydicom\nimport matplotlib.patches as patches\nfrom skimage.filters import *\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"505c08cbac8c70e0850f64cedd05ac59d95736c5"},"cell_type":"markdown","source":"## build a dataframe indexed by patient"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"def my_list(rows):\n    for row in rows:\n        return list(row)\ndf = pd.read_csv(\"../input/stage_1_train_labels.csv\")\n#                 converters={\"x\" : np.float64, \"y\" : np.float64, \"width\" : np.float64, \"height\" : np.float64})\ndf.head()\ndf_patient = pd.DataFrame(df.groupby(\"patientId\")[\"x\"].apply(list))\ndf_patient[\"y\"] = pd.DataFrame(df.groupby(\"patientId\")[\"y\"].apply(list))\ndf_patient[\"width\"] = pd.DataFrame(df.groupby(\"patientId\")[\"width\"].apply(list))\ndf_patient[\"height\"] = pd.DataFrame(df.groupby(\"patientId\")[\"height\"].apply(list))\ndf_patient[\"Target\"] = pd.DataFrame(df.groupby(\"patientId\")[\"Target\"].apply(list))\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"19966a625b5ee98b589bb89250d9d3354421495c"},"cell_type":"markdown","source":"## sample 3 each of positive and negative images and display with tags"},{"metadata":{"trusted":true,"_uuid":"f460dad23d271f508f71171ae8d6bb855d98cbb1"},"cell_type":"code","source":"def display_image(row, col, img, values, title):\n    ax[row][col].set_title(title)\n    ax[row][col].imshow(img, cmap=plt.cm.bone) \n    for val in values:\n        for i in range(len(val[0])):\n            rect = patches.Rectangle((val[0][i], val[1][i]),\n                                     val[2][i], val[3][i],linewidth=1,edgecolor='r',facecolor='none')\n            ax[row][col].add_patch(rect)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b13d87a71670622e0dafa4e7ff5e294ae11af0af"},"cell_type":"code","source":"last_target = 1\ncount = 0\nnum_cols = 2\nfig,ax = plt.subplots(nrows=3, ncols=2, figsize=(8, 20))\nwhile count < 6:\n    sample = df_patient.sample()\n    if  sample.iloc[0][\"Target\"][0] == last_target:\n        continue\n    last_target = 0 if last_target == 1 else 1\n    filename =  \"../input/stage_1_train_images/\" + sample.index[0] + \".dcm\"\n    ds = pydicom.dcmread(filename)\n    row = int(count/num_cols)\n    col = count%num_cols\n    display_image(row, col,ds.pixel_array,sample.values, sample.index[0]  )\n    count += 1\n\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6a0a0e97c4d13193d97791aea27e953313748fa6"},"cell_type":"markdown","source":"## Normalize contrasts"},{"metadata":{"trusted":true,"_uuid":"c8ee4e32932fa45a066f61192ce1d50a514a5f50"},"cell_type":"code","source":"# def display_image(row, col, ax, image, values):\n#     ax[row][col].imshow(image, cmap=plt.cm.bone) \n#     for val in values:\n#         for i in range(len(val[0])):\n#             rect = patches.Rectangle((val[0][i], val[1][i]),\n#                                      val[2][i], val[3][i],linewidth=1,edgecolor='r',facecolor='none')\n#             ax[row][col].add_patch(rect)\n  \n\ncount = 0\nnum_cols = 2\nfig,ax = plt.subplots(nrows=4, ncols=2, figsize=(8, 20))\nwhile count < 6:\n    sample = df_patient.sample()\n    filename =  \"../input/stage_1_train_images/\" + sample.index[0] + \".dcm\"\n    ds = pydicom.dcmread(filename)\n    row = int(count/num_cols)\n    col = count%num_cols\n    img = ds.pixel_array\n    display_image(row, col, img, sample.values, \"original\" )\n    count += 1\n    from skimage import exposure\n    # Contrast stretching\n    p2, p98 = np.percentile(img, (2, 98))\n    img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))\n\n    # Equalization\n    img_eq = exposure.equalize_hist(img)\n\n    # Adaptive Equalization\n    img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03)\n    row = int(count/num_cols)\n    col = count%num_cols\n    display_image(row, col, img_rescale, sample.values, \"rescale\" )\n    count += 1\n    row = int(count/num_cols)\n    col = count%num_cols\n    display_image(row, col, img_eq, sample.values, \"hist eq\" )\n    count += 1\n    row = int(count/num_cols)\n    col = count%num_cols\n    display_image(row, col, img_adapteq, sample.values, \"adaptive eq\" )\n    count += 1\nplt.show()\n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}