{"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":"markdown","source":"<div align=\"center\"><p style=\"font-family: 'Mochiy Pop P One';font-size:32px;color:black\" id=top>Image Processing - Resize and Augmentation</p></div>\n\n\n<ol> \n<li><a href=#1 >Data Description </a></li>    \n<li><a href=#2 >Load Original DICOM Images </a></li>\n<ol>  \n    <li><a href=#2.1>Cancer Positive Images</a> </li> \n    <li><a href=#2.2>Cancer Negative Images</a></li> \n    <li><a href=#2.3>Unusually Difficult Cases </a></li> \n</ol>  \n<li><a href=#3 >Resize images using PIL package </a></li> \n<li><a href=#4 >Image Augmentation by torchvisaion tranforms </a></li>   \n<ol>  \n    <li><a href=#4.1>4.1. center crop the image and pad image</a> </li> \n    <li><a href=#4.2>4.2. Add Gaussian Blur to images</a></li> \n</ol>   \n    \n    \n</ol>   \n\n\nDICOM: Digital Imaging and Communications in Medicine\n\n","metadata":{}},{"cell_type":"code","source":"!pip install -qU python-gdcm pydicom pylibjpeg","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:02:48.33587Z","iopub.execute_input":"2022-12-02T14:02:48.336842Z","iopub.status.idle":"2022-12-02T14:03:05.989262Z","shell.execute_reply.started":"2022-12-02T14:02:48.336712Z","shell.execute_reply":"2022-12-02T14:03:05.987493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport glob\nimport gdcm\nimport pydicom\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom tqdm.notebook import tqdm\nfrom joblib import Parallel, delayed\n\n\n#settings\npd.options.display.max_rows = 100\npd.options.display.max_columns = 100\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport pytorch_lightning as pl\nrandom_seed=1234\npl.seed_everything(random_seed)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:05.992232Z","iopub.execute_input":"2022-12-02T14:03:05.992758Z","iopub.status.idle":"2022-12-02T14:03:12.259146Z","shell.execute_reply.started":"2022-12-02T14:03:05.992705Z","shell.execute_reply":"2022-12-02T14:03:12.257799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=1>1. Data Description</p>\n\n<p><a href=#top>back to top</a></p>\n\n\n<p><strong>[train/test]_images/[patient_id]/[image_id].dcm</strong> The mammograms, in dicom format. You can expect roughly 8,000 patients in the hidden test set. There are usually but not always 4 images per patient. Note that many of the images use the jpeg 2000 format which may you may need special libraries to load.<br><br>\n<strong>sample_submission.csv</strong> A valid sample submission. Only the first few rows are available for download.<br><br>\n<strong>[train/test].csv</strong> Metadata for each patient and image. Only the first few rows of the test set are available for download.</p>\n\n<ul>\n<li><code>site_id</code> - ID code for the source hospital.</li>\n<li><code>patient_id</code> - ID code for the patient.</li>\n<li><code>image_id</code> - ID code for the image.</li>\n<li><code>laterality</code> - Whether the image is of the left or right breast.</li>\n<li><code>view</code> - The orientation of the image. The default for a screening exam is to capture two views per breast.</li>\n<li><code>age</code> - The patient's age in years.</li>\n<li><code>implant</code> - Whether or not the patient had breast implants. Site 1 only provides breast implant information at the patient level, not at the breast level.</li>\n<li><code>density</code> - A rating for how dense the breast tissue is, with A being the least dense and D being the most dense. Extremely dense tissue can make diagnosis more difficult.</li>\n<li><code>machine_id</code> - An ID code for the imaging device.</li>\n<li><code>cancer</code> - The target value. Only provided for train.</li>\n<li><code>biopsy</code> - Whether or not a follow-up biopsy was performed on the breast. Only provided for train.</li>\n<li><code>invasive</code> - If the breast is positive for cancer, whether or not the cancer proved to be invasive. Only provided for train.</li>\n<li><code>BIRADS</code> - 0 if the breast required follow-up, 1 if the breast was rated as negative for cancer, and 2 if the breast was rated as normal. Only provided for train.</li>\n<li><code>prediction_id</code> - The ID for the matching submission row. Multiple images will share the same prediction ID. Test only.</li>\n<li><code>difficult_negative_case</code> - True if the case was unusually difficult. Only provided for train.</li>\n</ul>","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/train.csv\")\ntrain_df.head(3)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:12.260641Z","iopub.execute_input":"2022-12-02T14:03:12.261384Z","iopub.status.idle":"2022-12-02T14:03:12.400297Z","shell.execute_reply.started":"2022-12-02T14:03:12.261349Z","shell.execute_reply":"2022-12-02T14:03:12.399128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:20px;\" id=2>2. Load Original DICOM Images</p>\n<p><a href=#top>back to top</a></p>\n\n\n<ol>  \n    <li><a href=#2.1>Cancer Positive Images</a> </li> \n    <li><a href=#2.2>Cancer Negative Images</a></li> \n    <li><a href=#2.3>Unusually Difficult Cases </a></li> \n</ol>  ","metadata":{}},{"cell_type":"code","source":"def load_img(img_path, resize=True):\n    #img_path=\"/kaggle/input/rsna-breast-cancer-detection/train_images/10038/1967300488.dcm\"\n    dicom = pydicom.dcmread(img_path)\n    img = dicom.pixel_array\n\n    if resize:\n        img = (img - img.min()) / (img.max() - img.min())\n\n        if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n            img = 1 - img\n\n    return img","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:12.40273Z","iopub.execute_input":"2022-12-02T14:03:12.403208Z","iopub.status.idle":"2022-12-02T14:03:12.410134Z","shell.execute_reply.started":"2022-12-02T14:03:12.40314Z","shell.execute_reply":"2022-12-02T14:03:12.408853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def visualize_sample(\n    base_path, \n    data_df\n):\n    nsamples = data_df.shape[0]\n    ncols = 4\n    nrows = int(np.ceil(nsamples/ncols))\n    fig, axs = plt.subplots(nrows, ncols, figsize=(18, 6*nrows), sharey=False, sharex=False)\n    #plt.style.use('seaborn-whitegrid')\n    i = 0\n    for _, row in data_df.iterrows():\n        if axs.size<=ncols:\n            ax = axs[i]\n        else:\n            ax = axs[i//ncols, i%ncols]\n        patient_id = row['patient_id']\n        image_id = row['image_id']\n        img_path =  f'{base_path}/{patient_id}/{image_id}.dcm'\n        #data = load_dicom(img_path)\n        data = load_img(img_path)\n        ax.imshow(data)#, cmap=\"gray\"\n        ax.set_title(f'patient: {patient_id}\\nimage:{image_id}\\nview:{row[\"view\"]}, side: {row[\"laterality\"]}\\ncancer positive: {row[\"cancer\"]}, age: {row[\"age\"]}', \n                         fontsize=13, loc='left')\n        i = i + 1\n\n    plt.suptitle(f\"\", fontsize=15,)\n    plt.xticks(fontsize=10)\n    plt.yticks(fontsize=10)\n    plt.show()","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-12-02T14:03:12.412194Z","iopub.execute_input":"2022-12-02T14:03:12.412642Z","iopub.status.idle":"2022-12-02T14:03:12.424279Z","shell.execute_reply.started":"2022-12-02T14:03:12.412598Z","shell.execute_reply":"2022-12-02T14:03:12.423189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_path=\"/kaggle/input/rsna-breast-cancer-detection/train_images\"","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:12.425536Z","iopub.execute_input":"2022-12-02T14:03:12.425829Z","iopub.status.idle":"2022-12-02T14:03:12.436206Z","shell.execute_reply.started":"2022-12-02T14:03:12.425803Z","shell.execute_reply":"2022-12-02T14:03:12.435214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=2.1>2.1 Cancer Positive</p>\n<p><a href=#top>back to top</a></p>","metadata":{}},{"cell_type":"code","source":"sub = train_df[(train_df['cancer']==1)].head(4)\n    \nvisualize_sample(base_path=base_path, data_df=sub)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:12.437572Z","iopub.execute_input":"2022-12-02T14:03:12.437971Z","iopub.status.idle":"2022-12-02T14:03:20.867253Z","shell.execute_reply.started":"2022-12-02T14:03:12.437942Z","shell.execute_reply":"2022-12-02T14:03:20.866027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:20.869134Z","iopub.execute_input":"2022-12-02T14:03:20.869995Z","iopub.status.idle":"2022-12-02T14:03:20.896242Z","shell.execute_reply.started":"2022-12-02T14:03:20.869947Z","shell.execute_reply":"2022-12-02T14:03:20.894503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=2.2>2.2 Cancer Negative</p>\n<p><a href=#top>back to top</a></p>","metadata":{}},{"cell_type":"code","source":"sub = train_df[(train_df['cancer']==0)].head(4)\n    \nvisualize_sample(base_path=base_path, data_df=sub)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:20.898161Z","iopub.execute_input":"2022-12-02T14:03:20.898591Z","iopub.status.idle":"2022-12-02T14:03:34.14434Z","shell.execute_reply.started":"2022-12-02T14:03:20.898555Z","shell.execute_reply":"2022-12-02T14:03:34.143243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=2.3>2.3 Unusually difficult cases</p>\n<p><a href=#top>back to top</a></p>","metadata":{}},{"cell_type":"code","source":"sub = train_df[(train_df['difficult_negative_case'])].head(4)\n    \nvisualize_sample(base_path=base_path, data_df=sub)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:34.149113Z","iopub.execute_input":"2022-12-02T14:03:34.149647Z","iopub.status.idle":"2022-12-02T14:03:39.23513Z","shell.execute_reply.started":"2022-12-02T14:03:34.1496Z","shell.execute_reply":"2022-12-02T14:03:39.233574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.236465Z","iopub.execute_input":"2022-12-02T14:03:39.236825Z","iopub.status.idle":"2022-12-02T14:03:39.254005Z","shell.execute_reply.started":"2022-12-02T14:03:39.236792Z","shell.execute_reply":"2022-12-02T14:03:39.253045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=3>3. Resize images using PIL package </p>\n<p><a href=#top>back to top</a></p>\n<div align=\"left\" style=\"font-family: 'Mochiy Pop P One';font-size:16px; font-weight: normal; \">\n\n<br>  \n  \n</div>  \n\n","metadata":{}},{"cell_type":"code","source":"#Load PIL package\nimport PIL\nfrom PIL import Image\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:04.211096Z","iopub.execute_input":"2022-12-02T14:06:04.21158Z","iopub.status.idle":"2022-12-02T14:06:04.216908Z","shell.execute_reply.started":"2022-12-02T14:06:04.211547Z","shell.execute_reply":"2022-12-02T14:06:04.215653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path=\"/kaggle/input/rsna-breast-cancer-detection/train_images/10049/1207499426.dcm\"\ndicom = pydicom.dcmread(img_path)\nimg = dicom.pixel_array\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.255062Z","iopub.execute_input":"2022-12-02T14:03:39.255833Z","iopub.status.idle":"2022-12-02T14:03:39.703361Z","shell.execute_reply.started":"2022-12-02T14:03:39.255798Z","shell.execute_reply":"2022-12-02T14:03:39.702125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://github.com/pydicom/contrib-pydicom/blob/master/viewers/pydicom_PIL.py\ntry:\n    import PIL.Image\n    have_PIL = True\nexcept ImportError:\n    have_PIL = False\n\ntry:\n    import numpy as np\n    have_numpy = True\nexcept ImportError:\n    have_numpy = False\n\n\ndef get_LUT_value(data, window, level):\n    \"\"\"Apply the RGB Look-Up Table for the given\n       data and window/level value.\"\"\"\n    if not have_numpy:\n        raise ImportError(\"Numpy is not available.\"\n                          \"See http://numpy.scipy.org/\"\n                          \"to download and install\")\n\n    return np.piecewise(data,\n                        [data <= (level - 0.5 - (window - 1) / 2),\n                         data > (level - 0.5 + (window - 1) / 2)],\n                        [0, 255, lambda data: ((data - (level - 0.5)) /\n                         (window - 1) + 0.5) * (255 - 0)])\n\n\ndef get_PIL_image(dataset):\n    \"\"\"Get Image object from Python Imaging Library(PIL)\"\"\"\n    if not have_PIL:\n        raise ImportError(\"Python Imaging Library is not available. \"\n                          \"See http://www.pythonware.com/products/pil/ \"\n                          \"to download and install\")\n\n    if ('PixelData' not in dataset):\n        raise TypeError(\"Cannot show image -- DICOM dataset does not have \"\n                        \"pixel data\")\n    # can only apply LUT if these window info exists\n    if ('WindowWidth' not in dataset) or ('WindowCenter' not in dataset):\n        bits = dataset.BitsAllocated\n        samples = dataset.SamplesPerPixel\n        if bits == 8 and samples == 1:\n            mode = \"L\"\n        elif bits == 8 and samples == 3:\n            mode = \"RGB\"\n        elif bits == 16:\n            # not sure about this -- PIL source says is 'experimental'\n            # and no documentation. Also, should bytes swap depending\n            # on endian of file and system??\n            mode = \"I;16\"\n        else:\n            raise TypeError(\"Don't know PIL mode for %d BitsAllocated \"\n                            \"and %d SamplesPerPixel\" % (bits, samples))\n\n        # PIL size = (width, height)\n        size = (dataset.Columns, dataset.Rows)\n\n        # Recommended to specify all details\n        # by http://www.pythonware.com/library/pil/handbook/image.htm\n        im = PIL.Image.frombuffer(mode, size, dataset.PixelData,\n                                  \"raw\", mode, 0, 1)\n\n    else:\n        ew = dataset['WindowWidth']\n        ec = dataset['WindowCenter']\n        ww = int(ew.value[0] if ew.VM > 1 else ew.value)\n        wc = int(ec.value[0] if ec.VM > 1 else ec.value)\n        image = get_LUT_value(dataset.pixel_array, ww, wc)\n        # Convert mode to L since LUT has only 256 values:\n        #   http://www.pythonware.com/library/pil/handbook/image.htm\n        im = PIL.Image.fromarray(image).convert('L')\n\n    return im\n\n\ndef show_PIL(dataset):\n    \"\"\"Display an image using the Python Imaging Library (PIL)\"\"\"\n    im = get_PIL_image(dataset)\n    im.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.705468Z","iopub.execute_input":"2022-12-02T14:03:39.705818Z","iopub.status.idle":"2022-12-02T14:03:39.723128Z","shell.execute_reply.started":"2022-12-02T14:03:39.705786Z","shell.execute_reply":"2022-12-02T14:03:39.721752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Step 1: convert numpy data to PIL image ","metadata":{}},{"cell_type":"code","source":"PIL_img=get_PIL_image(dicom)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.724944Z","iopub.execute_input":"2022-12-02T14:03:39.725363Z","iopub.status.idle":"2022-12-02T14:03:39.87072Z","shell.execute_reply.started":"2022-12-02T14:03:39.725313Z","shell.execute_reply":"2022-12-02T14:03:39.869506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Step 2: show PIL image size (as well as original image size)","metadata":{}},{"cell_type":"code","source":"print(f\"PIL image size: {PIL_img.size}, PIL image height: {PIL_img.height}, \\\nPIL image width: {PIL_img.width}, Original image shape: {img.shape}\")","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.872204Z","iopub.execute_input":"2022-12-02T14:03:39.872555Z","iopub.status.idle":"2022-12-02T14:03:39.879081Z","shell.execute_reply.started":"2022-12-02T14:03:39.872524Z","shell.execute_reply":"2022-12-02T14:03:39.877545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Step 3: compare the original and PIL images","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 8))\n\n\naxes[0].imshow(img)\naxes[0].set_title(f'Original Image')\naxes[1].imshow(PIL_img)\naxes[1].set_title(f'PIL Image')\n\nplt.suptitle(f\"compare original image and PIL image\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:03:39.880991Z","iopub.execute_input":"2022-12-02T14:03:39.881451Z","iopub.status.idle":"2022-12-02T14:03:42.061892Z","shell.execute_reply.started":"2022-12-02T14:03:39.881409Z","shell.execute_reply":"2022-12-02T14:03:42.060614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Step 4: resize image using PIL thumbnail function","metadata":{}},{"cell_type":"code","source":"#create the thumbnail of the image\n\nif hasattr(Image, 'Resampling'):  # Pillow<8.4.0\n    PIL_img.thumbnail((1024, 1024), resample=Image.Resampling.LANCZOS, reducing_gap=10)\n    if (PIL_img.height< PIL_img.width):\n        PIL_img = PIL_img.transpose(PIL.Image.Transpose.ROTATE_90)\nelse:\n    PIL_img.thumbnail((1024, 1024), resample=Image.LANCZOS, reducing_gap=10)\n    if (PIL_img.height> img.width):\n        PIL_img = PIL_img.transpose(PIL.Image.ROTATE_90)\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:09.677986Z","iopub.execute_input":"2022-12-02T14:06:09.678454Z","iopub.status.idle":"2022-12-02T14:06:09.770411Z","shell.execute_reply.started":"2022-12-02T14:06:09.678414Z","shell.execute_reply":"2022-12-02T14:06:09.769197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Step 5: compare the original and PIL resized images","metadata":{}},{"cell_type":"code","source":"print(f\"PIL image size: {PIL_img.size}, PIL image height: {PIL_img.height}, \\\nPIL image width: {PIL_img.width}, Original image shape: {img.shape}\")\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 8))\n\n\naxes[0].imshow(img)\naxes[0].set_title(f'Original Image')\naxes[1].imshow(PIL_img)\naxes[1].set_title(f'PIL resized Image')\n\nplt.suptitle(f\"compare original image and PIL image\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:11.590655Z","iopub.execute_input":"2022-12-02T14:06:11.591081Z","iopub.status.idle":"2022-12-02T14:06:13.0096Z","shell.execute_reply.started":"2022-12-02T14:06:11.591047Z","shell.execute_reply":"2022-12-02T14:06:13.008359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n<p style=\"font-family: 'Mochiy Pop P One';font-size:22px;color:black\" id=4>4. Image Augmentation by torchvisaion tranforms</p>\n<p><a href=#top>back to top</a></p>\n\n<ol>  \n    <li><a href=#4.1>4.1. center crop the image and pad image</a> </li> \n    <li><a href=#4.2>4.2. Add Gaussian Blur to images</a></li> \n</ol>   \n<div align=\"left\" style=\"font-family: 'Mochiy Pop P One';font-size:16px; font-weight: normal; \">\n\n<br>  \n  \n</div>  ","metadata":{}},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.backends.cudnn as cudnn\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:15.917514Z","iopub.execute_input":"2022-12-02T14:06:15.918417Z","iopub.status.idle":"2022-12-02T14:06:15.927249Z","shell.execute_reply.started":"2022-12-02T14:06:15.918326Z","shell.execute_reply":"2022-12-02T14:06:15.925349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"font-family: 'Mochiy Pop P One';font-size:18px;color:black\" id=4.1>4.1. center crop the image and pad image</p>\n<p><a href=#top>back to top</a></p>","metadata":{}},{"cell_type":"code","source":"#https://stackoverflow.com/questions/10965417/how-to-convert-a-numpy-array-to-pil-image-applying-matplotlib-colormap\n\n#use torchvision to center crop the image\nimg2 = transforms.functional.center_crop(PIL_img, 1024)\n#use torchvision to pad the image\nimg3 = transforms.functional.pad(PIL_img, 10)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:16.57954Z","iopub.execute_input":"2022-12-02T14:06:16.580019Z","iopub.status.idle":"2022-12-02T14:06:16.590025Z","shell.execute_reply.started":"2022-12-02T14:06:16.579983Z","shell.execute_reply":"2022-12-02T14:06:16.587854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"PIL image size: {PIL_img.size}, PIL image height: {PIL_img.height},\\n \\\nPIL image width: {PIL_img.width}, Original image shape: {img.shape},\\n  \\\nCenter crop image shape: {img2.size}, Pad image shape: {img3.size},\\n  \\\n\")\n\nfig, axes = plt.subplots(nrows=1, ncols=4, figsize=(18, 8))\n\n\naxes[0].imshow(img)\naxes[0].set_title(f'Original Image')\naxes[1].imshow(PIL_img)\naxes[1].set_title(f'PIL resized Image')\naxes[2].imshow(img2)\naxes[2].set_title(f'Center crop Image')\naxes[3].imshow(img3)\naxes[3].set_title(f'Pad Image')\n\nplt.suptitle(f\"compare original image, PIL image, center crop and pad images\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:17.338244Z","iopub.execute_input":"2022-12-02T14:06:17.338714Z","iopub.status.idle":"2022-12-02T14:06:19.091508Z","shell.execute_reply.started":"2022-12-02T14:06:17.338679Z","shell.execute_reply":"2022-12-02T14:06:19.08966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n<p style=\"font-family: 'Mochiy Pop P One';font-size:18px;color:black\" id=4.2>4.2. Add Gaussian Blur to images</p>\n<p><a href=#top>back to top</a></p>","metadata":{}},{"cell_type":"code","source":"#https://dsp.stackexchange.com/questions/10057/gaussian-blur-standard-deviation-radius-and-kernel-size\n#try different kernal sizes\n\nfig, axes = plt.subplots(nrows=1, ncols=4, figsize=(18, 8))\n\naxes[0].imshow(PIL_img)\naxes[0].set_title(f'PIL image')\n\nfor i, k_sizes  in enumerate([(5, 5),(15, 15), (25, 45)]):\n    img4 = transforms.functional.gaussian_blur(PIL_img, kernel_size=k_sizes, sigma=(0.1, 5))\n    #print(i+1, k_sizes, img4.size, np.asarray(img4, np.uint8).min(), np.asarray(img4, np.uint8).max())\n    axes[i+1].imshow(img4)\n    axes[i+1].set_title(f'Kernal sizes: {k_sizes}')\n\nplt.suptitle(f\"compare PIL image and different Gaussian Blur Kernel sizes\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:19.094154Z","iopub.execute_input":"2022-12-02T14:06:19.095358Z","iopub.status.idle":"2022-12-02T14:06:20.770551Z","shell.execute_reply.started":"2022-12-02T14:06:19.095292Z","shell.execute_reply":"2022-12-02T14:06:20.769219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#try different sigma\n\nfig, axes = plt.subplots(nrows=1, ncols=4, figsize=(18, 8))\n\naxes[0].imshow(PIL_img)\naxes[0].set_title(f'PIL image')\n\nfor i, sigma  in enumerate([ (0.05, 1), (0.1, 5),(0.8, 10)]):\n    img4 = transforms.functional.gaussian_blur(PIL_img, kernel_size=(5, 9), sigma=sigma)\n    #print(i, k_sizes, img4.size, np.asarray(img4, np.uint8).min(), np.asarray(img4, np.uint8).max())\n    axes[i+1].imshow(img4)\n    axes[i+1].set_title(f'sigma: {sigma}')\n\nplt.suptitle(f\"compare PIL image and different Gaussian Blur sigma\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:20.772596Z","iopub.execute_input":"2022-12-02T14:06:20.773086Z","iopub.status.idle":"2022-12-02T14:06:21.774833Z","shell.execute_reply.started":"2022-12-02T14:06:20.773046Z","shell.execute_reply":"2022-12-02T14:06:21.773967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#try different sigma and kernel_size\n\nfig, axes = plt.subplots(nrows=1, ncols=4, figsize=(18, 8))\n\naxes[0].imshow(PIL_img)\naxes[0].set_title(f'PIL image')\n\nfor i, (sigma, k_sizes) in enumerate([[(0.1, 5), (35, 65)],\n                                     [(0.8, 10), (5, 9)], [(0.8, 10), (35, 65)]]):\n    img4 = transforms.functional.gaussian_blur(PIL_img, kernel_size=k_sizes, sigma=sigma)\n    #print(i, k_sizes, img4.size, np.asarray(img4, np.uint8).min(), np.asarray(img4, np.uint8).max())\n    axes[i+1].imshow(img4)\n    axes[i+1].set_title(f'kernel_size={k_sizes}, sigma={sigma}')\n\nplt.suptitle(f\"compare PIL image and different Gaussian Blur kernel size and sigma\", fontsize=15,)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=10)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-02T14:06:21.77624Z","iopub.execute_input":"2022-12-02T14:06:21.776787Z","iopub.status.idle":"2022-12-02T14:06:25.699821Z","shell.execute_reply.started":"2022-12-02T14:06:21.776753Z","shell.execute_reply":"2022-12-02T14:06:25.698141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n<p style=\"font-family: 'Mochiy Pop P One';font-size:20px;\">Reference:</p>\n\n* https://www.kaggle.com/code/ihelon/brain-tumor-eda-with-animations-and-modeling\n* https://www.kaggle.com/code/theoviel/dicom-resized-png-jpg/notebook\n* https://www.kaggle.com/code/xxxxyyyy80008/strip-ai-understand-image-processing","metadata":{}}]}