{"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_minor":4,"nbformat":4,"cells":[{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -U pylibjpeg pylibjpeg-openjpeg pylibjpeg-libjpeg","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport sys\nimport platform\nfrom PIL import Image\nimport numpy as np\nimport pydicom \nimport os\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport sys\nimport platform\nfrom PIL import Image\nimport numpy as np\nimport pydicom\nfrom tqdm.notebook import tqdm\nfrom pathlib import Path\nfrom sklearn.preprocessing import MinMaxScaler\nfrom skimage.transform import rotate, AffineTransform, warp\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport albumentations as A\nfrom sklearn.preprocessing import MinMaxScaler","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/train.csv\")\npath = \"/kaggle/input/rsna-breast-cancer-detection/train_images\"\ndata['file'] = data.apply(lambda x: f'{path}/{x[\"patient_id\"]}/{x[\"image_id\"]}.dcm', axis=1)\n\n\ncase = 00000\ninfo = []\n\nfor i , row in data.iterrows():\n  if not row[\"patient_id\"] == case:\n    df = data[data[\"patient_id\"] == case]\n    if len(df) == 4:\n      if (len(df.laterality.unique() == 2)) and (len(df.view.unique() == 2)):\n        imgcc_left = df[(df[\"view\"] == \"CC\") & (df[\"laterality\"]==\"L\")][\"file\"].iloc[0]\n        imgcc_right = df[(df[\"view\"] == \"CC\") & (df[\"laterality\"]==\"R\")][\"file\"].iloc[0]\n        imgmlo_left = df[(df[\"view\"] == \"MLO\") & (df[\"laterality\"]==\"L\")][\"file\"].iloc[0]\n        imgmlo_right = df[(df[\"view\"] == \"MLO\") & (df[\"laterality\"]==\"R\")][\"file\"].iloc[0]\n        \n        info.append((case , imgcc_left , imgmlo_left , df[df[\"laterality\"] == \"L\"][\"cancer\"].iloc[0] , df[df[\"laterality\"] == \"L\"][\"density\"].iloc[0]))\n        info.append((case , imgcc_right, imgmlo_right , df[df[\"laterality\"] == \"R\"][\"cancer\"].iloc[0] ,df[df[\"laterality\"] == \"R\"][\"density\"].iloc[0]))\n  case = row[\"patient_id\"]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(info)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(info)\nnp.random.shuffle(info)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info_density =  [(c,cc,mlo,l,d) for (c,cc,mlo,l,d) in info if d in [\"A\",\"B\",\"C\",\"D\"]]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"scaler = MinMaxScaler()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dicom_file_to_ary(path):\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\n    if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n    data = scaler.fit_transform(data)\n    data = (data * 255).astype(np.uint8)\n    return data\n\ndef add_pad(image, new_height=512, new_width=512):\n    height, width = image.shape\n\n    final_image = np.zeros((new_height, new_width))\n\n    pad_left = int((new_width - width) // 2)\n    pad_top = int((new_height - height) // 2)\n    \n    \n    # Replace the pixels with the image's pixels\n    final_image[pad_top:pad_top + height, pad_left:pad_left + width] = image\n    \n    return final_image\n\n\ndef combine2channelPad(cc,mlo):\n    if cc.shape[0] > mlo.shape[0]:\n        h = cc.shape[0]\n    else:\n        h = mlo.shape[0]\n        \n    if cc.shape[1] > mlo.shape[1]:\n        w = cc.shape[1]\n    else:\n        w = mlo.shape[1]\n        \n    \n    ccn = add_pad(cc,h,w)\n    mlon = add_pad(mlo,h,w)\n    \n    return (ccn,mlon)\n\n\n\ndef fit_image(X):\n \n    output= cv2.connectedComponentsWithStats((X > 10).astype(np.uint8)[:, :], 8, cv2.CV_32S)\n    stats = output[2]\n    idx = stats[1:, 4].argmax() + 1\n    x1, y1, w, h = stats[idx][:4]\n    x2 = x1 + w\n    y2 = y1 + h\n    X_fit = X[y1: y2, x1: x2]\n    return X_fit / 255\n\n\n\ndef sample(file):\n    a , b , c, d =  0,0,0,0\n    for _, den in file:\n        if den == \"A\":\n            a+=1\n        if den == \"B\":\n            b+=1\n        if den == \"C\":\n            c+=1\n        if den == \"D\":\n            d+=1\n        \n    return a ,b ,c ,d\n\n\n\ndef sampleb(file):\n    a , b , c, d =  0,0,0,0\n    for _,_,_,_,den in file:\n        if den == \"A\":\n            a+=1\n        if den == \"B\":\n            b+=1\n        if den == \"C\":\n            c+=1\n        if den == \"D\":\n            d+=1\n        \n    return a ,b ,c ,d\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info = {}\nfor i , row in tqdm(data.iterrows()):\n    c = row[\"patient_id\"]\n    d = row[\"density\"]\n    \n    info[c] = d","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_bal = []\nb = 0 \nc = 0\nfor case,cc,mlo,cancer,den in info_density:\n    if den == \"A\":\n        train_bal.append((case,cc,mlo,cancer,den))\n    if den == \"B\" and b < 750:\n        train_bal.append((case,cc,mlo,cancer,den))\n        b+=1\n    if den == \"C\" and c < 750:\n        train_bal.append((case,cc,mlo,cancer,den))\n        c+=1\n    if den == \"D\":\n        train_bal.append((case,cc,mlo,cancer,den))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(train_bal)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T12:29:23.86731Z","iopub.execute_input":"2023-03-19T12:29:23.867608Z","iopub.status.idle":"2023-03-19T12:29:23.927002Z","shell.execute_reply.started":"2023-03-19T12:29:23.867583Z","shell.execute_reply":"2023-03-19T12:29:23.924878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SAVE_PATH = Path(\"Processed_bal/\")\nfor c , (case , cc , mlo , can , density) in enumerate(tqdm(train_bal)):\n    \n    \n    a_cc = dicom_file_to_ary(cc)\n    a_mlo = dicom_file_to_ary(mlo)\n    \n    \n    img1=fit_image(a_cc)\n    img2=fit_image(a_mlo)\n\n                           \n    img1 , img2 = combine2channelPad(img1,img2)\n    \n    img=np.stack([img1,img2],axis=2)\n                \n    img = cv2.resize(img,(400,600),interpolation=cv2.INTER_LINEAR).astype(np.float16)\n    #img2 = cv2.resize(img2,(400,400),interpolation=cv2.INTER_LINEAR).astype(np.float16)\n    \n    \n    train_or_val = \"train\" if c < 2500 else \"val\" \n        \n    current_save_path = SAVE_PATH/train_or_val # Define save path and create if necessary\n    current_save_path.mkdir(parents=True, exist_ok=True)\n    case = str(case) + \"_\" + str(c) + \"_\" +density\n    np.save(current_save_path/case, img)  # Save the array in the corresponding directory","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}