{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"}],"dockerImageVersionId":30666,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-04-20T17:03:26.675534Z","iopub.execute_input":"2024-04-20T17:03:26.676286Z","iopub.status.idle":"2024-04-20T17:03:33.700045Z","shell.execute_reply.started":"2024-04-20T17:03:26.676249Z","shell.execute_reply":"2024-04-20T17:03:33.699015Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install seaborn\n","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:23:53.033724Z","iopub.execute_input":"2024-04-20T17:23:53.034763Z","iopub.status.idle":"2024-04-20T17:24:06.259700Z","shell.execute_reply.started":"2024-04-20T17:23:53.034729Z","shell.execute_reply":"2024-04-20T17:24:06.258714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport time\nimport shutil\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport tensorflow as tf\nsns.set_style('darkgrid')\nimport matplotlib.pyplot as plt\nfrom PIL import Image","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-04-20T17:24:43.145658Z","iopub.execute_input":"2024-04-20T17:24:43.146071Z","iopub.status.idle":"2024-04-20T17:24:55.085651Z","shell.execute_reply.started":"2024-04-20T17:24:43.146035Z","shell.execute_reply":"2024-04-20T17:24:55.084840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n\nfrom tensorflow.keras.applications import ResNet152V2\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras import backend as K\n\n\nfrom keras.layers import Dense, Conv2D , SeparableConv2D, MaxPooling2D , Flatten , Dropout , BatchNormalization, Activation\n\nfrom tensorflow.keras.utils import img_to_array,array_to_img\nfrom keras.callbacks import ReduceLROnPlateau \n\nfrom keras import optimizers\nfrom sklearn.metrics import classification_report, recall_score, precision_score, confusion_matrix, f1_score, accuracy_score\nfrom tensorflow.keras.utils import plot_model\nfrom IPython.display import Image\n\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.optimizers import Adam, Adamax\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.models import Model, load_model, Sequential\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout, BatchNormalization\nprint ('modules loaded')","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-04-20T17:25:08.352552Z","iopub.execute_input":"2024-04-20T17:25:08.353489Z","iopub.status.idle":"2024-04-20T17:25:08.530188Z","shell.execute_reply.started":"2024-04-20T17:25:08.353453Z","shell.execute_reply":"2024-04-20T17:25:08.529191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ntest_df = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head(10)","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-04-20T17:25:13.128870Z","iopub.execute_input":"2024-04-20T17:25:13.129310Z","iopub.status.idle":"2024-04-20T17:25:13.172924Z","shell.execute_reply.started":"2024-04-20T17:25:13.129276Z","shell.execute_reply":"2024-04-20T17:25:13.171927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head()","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-04-20T17:25:17.405630Z","iopub.execute_input":"2024-04-20T17:25:17.406347Z","iopub.status.idle":"2024-04-20T17:25:17.414962Z","shell.execute_reply.started":"2024-04-20T17:25:17.406311Z","shell.execute_reply":"2024-04-20T17:25:17.413996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['diagnosis'].hist(figsize = (10, 5))","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:25:20.336426Z","iopub.execute_input":"2024-04-20T17:25:20.337352Z","iopub.status.idle":"2024-04-20T17:25:20.814647Z","shell.execute_reply.started":"2024-04-20T17:25:20.337317Z","shell.execute_reply":"2024-04-20T17:25:20.813578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.pivot_table(index='diagnosis', aggfunc=len)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:25:24.474841Z","iopub.execute_input":"2024-04-20T17:25:24.475897Z","iopub.status.idle":"2024-04-20T17:25:24.496963Z","shell.execute_reply.started":"2024-04-20T17:25:24.475854Z","shell.execute_reply":"2024-04-20T17:25:24.496037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Label Mapping\n\n0 - No DR\n1 - Mild\n2 - Moderate\n3 - Severe\n4 - Proliferative DR","metadata":{"execution":{"iopub.status.busy":"2024-04-16T11:14:54.324086Z","iopub.execute_input":"2024-04-16T11:14:54.324398Z","iopub.status.idle":"2024-04-16T11:14:54.328525Z","shell.execute_reply.started":"2024-04-16T11:14:54.324372Z","shell.execute_reply":"2024-04-16T11:14:54.327481Z"}}},{"cell_type":"code","source":"sns.set_style(\"white\")\ncount = 1\nplt.figure(figsize=[20, 20])\nfor img_name in train_df['id_code'][:15]:\n    img = cv2.imread(\"../input/aptos2019-blindness-detection/train_images/%s.png\" % img_name)[...,[2, 1, 0]]\n    plt.subplot(5, 5, count)\n    plt.imshow(img)\n    plt.title(\"Image %s\" % count)\n    count += 1\n    \nplt.show()\n     ","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:25:28.060215Z","iopub.execute_input":"2024-04-20T17:25:28.060965Z","iopub.status.idle":"2024-04-20T17:25:42.236443Z","shell.execute_reply.started":"2024-04-20T17:25:28.060933Z","shell.execute_reply":"2024-04-20T17:25:42.235231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_samples(df, columns=4, rows=4):\n    fig=plt.figure(figsize=(5*columns, 4*rows))\n\n    for i in range(columns*rows):\n        image_path = df.loc[i,'id_code']\n        image_id = df.loc[i,'diagnosis']\n        img = cv2.imread(f'../input/aptos2019-blindness-detection/train_images/{image_path}.png')\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        fig.add_subplot(rows, columns, i+1)\n        plt.title(image_id)\n        plt.imshow(img)\n    \n    plt.tight_layout()\n\ndisplay_samples(train_df)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:25:48.380673Z","iopub.execute_input":"2024-04-20T17:25:48.381106Z","iopub.status.idle":"2024-04-20T17:26:09.075429Z","shell.execute_reply.started":"2024-04-20T17:25:48.381068Z","shell.execute_reply":"2024-04-20T17:26:09.074329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 512\nSEED = 77","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-04-20T17:26:17.412109Z","iopub.execute_input":"2024-04-20T17:26:17.412833Z","iopub.status.idle":"2024-04-20T17:26:17.418903Z","shell.execute_reply.started":"2024-04-20T17:26:17.412798Z","shell.execute_reply":"2024-04-20T17:26:17.417950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def crop_image_from_gray(img,tol=7):\n    if img.ndim ==2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n    #         print(img1.shape,img2.shape,img3.shape)\n            img = np.stack([img1,img2,img3],axis=-1)\n    #         print(img.shape)\n        return img\n     ","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:26:26.227444Z","iopub.execute_input":"2024-04-20T17:26:26.228125Z","iopub.status.idle":"2024-04-20T17:26:26.236839Z","shell.execute_reply.started":"2024-04-20T17:26:26.228094Z","shell.execute_reply":"2024-04-20T17:26:26.235738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_color_correction(path, sigmaX=10):\n    image = cv2.imread(path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = crop_image_from_gray(image)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)\n        \n    return image","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:26:30.046574Z","iopub.execute_input":"2024-04-20T17:26:30.047329Z","iopub.status.idle":"2024-04-20T17:26:30.052778Z","shell.execute_reply.started":"2024-04-20T17:26:30.047289Z","shell.execute_reply":"2024-04-20T17:26:30.051750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_SAMP=7\nfig = plt.figure(figsize=(25, 16))\nfor class_id in train_df['diagnosis'].unique():\n    for i, (idx, row) in enumerate(train_df.loc[train_df['diagnosis'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n        ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n        path=f'../input/aptos2019-blindness-detection/train_images/{row[\"id_code\"]}.png'\n        image = load_color_correction(path,sigmaX=20)\n\n        plt.imshow(image)\n        ax.set_title('%d-%d-%s' % (class_id, idx, row['id_code']) )\n        ","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:26:34.350233Z","iopub.execute_input":"2024-04-20T17:26:34.351146Z","iopub.status.idle":"2024-04-20T17:26:49.037595Z","shell.execute_reply.started":"2024-04-20T17:26:34.351105Z","shell.execute_reply":"2024-04-20T17:26:49.035892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Observation:\n\nLighting condition improved       *\nNeed to modify the cropping function (as roi getting cropped)","metadata":{}},{"cell_type":"markdown","source":"# Function for (lighting condition + Circle crop)","metadata":{}},{"cell_type":"code","source":"def circle_crop(img, sigmaX=10):   \n    \"\"\"\n    Create circular crop around image centre    \n    \"\"\"    \n    \n    img = cv2.imread(img)\n    img = crop_image_from_gray(img)    \n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    \n    height, width, depth = img.shape    \n    \n    x = int(width/2)\n    y = int(height/2)\n    r = np.amin((x,y))\n    \n    circle_img = np.zeros((height, width), np.uint8)\n    cv2.circle(circle_img, (x,y), int(r), 1, thickness=-1)\n    img = cv2.bitwise_and(img, img, mask=circle_img)\n    img = crop_image_from_gray(img)\n    img=cv2.addWeighted ( img,4, cv2.GaussianBlur( img , (0,0) , sigmaX) ,-4 ,128)\n    return img \n     ","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:27:21.906399Z","iopub.execute_input":"2024-04-20T17:27:21.907024Z","iopub.status.idle":"2024-04-20T17:27:21.915049Z","shell.execute_reply.started":"2024-04-20T17:27:21.906991Z","shell.execute_reply":"2024-04-20T17:27:21.914144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_SAMP=7\nfig = plt.figure(figsize=(25, 16))\nfor class_id in train_df['diagnosis'].unique():\n    for i, (idx, row) in enumerate(train_df.loc[train_df['diagnosis'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n        ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n        path=f'../input/aptos2019-blindness-detection/train_images/{row[\"id_code\"]}.png'\n        image = circle_crop(path,sigmaX=30)\n\n        plt.imshow(image)\n        ax.set_title('%d-%d-%s' % (class_id, idx, row['id_code']) )","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:27:26.383138Z","iopub.execute_input":"2024-04-20T17:27:26.383546Z","iopub.status.idle":"2024-04-20T17:28:13.851652Z","shell.execute_reply.started":"2024-04-20T17:27:26.383517Z","shell.execute_reply":"2024-04-20T17:28:13.850101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Processed Data","metadata":{}},{"cell_type":"code","source":"train_source_path = '../input/aptos2019-blindness-detection/train_images/'\ntest_source_path = '../input/aptos2019-blindness-detection/test_images/'\n\n","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:28:31.434738Z","iopub.execute_input":"2024-04-20T17:28:31.435548Z","iopub.status.idle":"2024-04-20T17:28:31.440020Z","shell.execute_reply.started":"2024-04-20T17:28:31.435512Z","shell.execute_reply":"2024-04-20T17:28:31.438819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\nbase_dir = '/kaggle/working'\n\ntrain_dest_path = os.path.join(base_dir, 'train_images')\n\n# Remove existing directories if they exist\nif os.path.exists(train_dest_path):\n    shutil.rmtree(train_dest_path)\n\n# Create train directory\nos.makedirs(train_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:28:34.263908Z","iopub.execute_input":"2024-04-20T17:28:34.264800Z","iopub.status.idle":"2024-04-20T17:28:34.269943Z","shell.execute_reply.started":"2024-04-20T17:28:34.264765Z","shell.execute_reply":"2024-04-20T17:28:34.268948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_dir = '/kaggle/working'\n\ntest_dest_path = os.path.join(base_dir, 'test_images')\n\n# Remove existing directories if they exist\nif os.path.exists(test_dest_path):\n    shutil.rmtree(test_dest_path)\n\n# Create train directory\nos.makedirs(test_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:28:37.173036Z","iopub.execute_input":"2024-04-20T17:28:37.173926Z","iopub.status.idle":"2024-04-20T17:28:37.179022Z","shell.execute_reply.started":"2024-04-20T17:28:37.173896Z","shell.execute_reply":"2024-04-20T17:28:37.178004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Applying preprocessing & Saving images\n","metadata":{}},{"cell_type":"code","source":"def process_image_folder(df, source_path, dest_path):\n    for i, (idx, row) in enumerate(df.iterrows()):\n        img_path = os.path.join(source_path, f\"{row['id_code']}.png\")\n        dest_img_path = os.path.join(dest_path, f\"{row['id_code']}.png\")\n        \n        try:\n            image = circle_crop(img_path, sigmaX=30)\n            cv2.imwrite(dest_img_path, image)\n            print(f\"Processed image {img_path}\")\n        except Exception as e:\n            print(f\"Error processing image {img_path}: {e}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:28:40.518033Z","iopub.execute_input":"2024-04-20T17:28:40.518893Z","iopub.status.idle":"2024-04-20T17:28:40.525005Z","shell.execute_reply.started":"2024-04-20T17:28:40.518859Z","shell.execute_reply":"2024-04-20T17:28:40.523968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"process_image_folder(train_df,train_source_path,train_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T17:28:43.226148Z","iopub.execute_input":"2024-04-20T17:28:43.226558Z","iopub.status.idle":"2024-04-20T18:13:53.057421Z","shell.execute_reply.started":"2024-04-20T17:28:43.226527Z","shell.execute_reply":"2024-04-20T18:13:53.056435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"process_image_folder(test_df,test_source_path,test_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T18:15:17.535896Z","iopub.execute_input":"2024-04-20T18:15:17.536433Z","iopub.status.idle":"2024-04-20T18:26:10.897779Z","shell.execute_reply.started":"2024-04-20T18:15:17.536396Z","shell.execute_reply":"2024-04-20T18:26:10.896642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Images with their labeled folder","metadata":{}},{"cell_type":"code","source":"# Define the source and destination paths\nprocessed_src_path = '/kaggle/working/train_images/'\n\n\nbase_dir = '/kaggle/working'\n\nnew_dest_path = os.path.join(base_dir, 'Final_Dataset')\n\n# Remove existing directories if they exist\nif os.path.exists(new_dest_path):\n    shutil.rmtree(new_dest_path)\n\n# Create train directory\nos.makedirs(new_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T18:27:33.751236Z","iopub.execute_input":"2024-04-20T18:27:33.751953Z","iopub.status.idle":"2024-04-20T18:27:33.757530Z","shell.execute_reply.started":"2024-04-20T18:27:33.751914Z","shell.execute_reply":"2024-04-20T18:27:33.756554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_dataset(df, source_path, dest_path):\n    # Create destination directory if it doesn't exist\n    if not os.path.exists(dest_path):\n        os.makedirs(dest_path)\n    \n    for i, (idx, row) in enumerate(df.iterrows()):\n        img_path = f\"{source_path}{row['id_code']}.png\"\n        # Create destination directory path for the class (diagnosis)\n        class_dir = os.path.join(dest_path, str(row['diagnosis']))\n        \n        # Ensure the class directory exists\n        if not os.path.exists(class_dir):\n            os.makedirs(class_dir)\n        \n        # Create the destination image path\n        dest_img_path = os.path.join(class_dir, f\"{row['id_code']}.png\")\n        \n        # Check if the image file exists and is readable\n        if os.path.exists(img_path):\n            image = cv2.imread(img_path)\n            \n            # Check if the image is successfully read\n            if image is not None:\n                cv2.imwrite(dest_img_path, image)\n                print(f\"Processed image {img_path}\")\n            else:\n                print(f\"Error: Unable to read image {img_path}\")\n        else:\n            print(f\"Error: Image file not found {img_path}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-04-20T18:27:40.289565Z","iopub.execute_input":"2024-04-20T18:27:40.289952Z","iopub.status.idle":"2024-04-20T18:27:40.297918Z","shell.execute_reply.started":"2024-04-20T18:27:40.289920Z","shell.execute_reply":"2024-04-20T18:27:40.296887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Call the create_dataset function\ncreate_dataset(train_df, processed_src_path, new_dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-04-20T18:27:46.106516Z","iopub.execute_input":"2024-04-20T18:27:46.107288Z","iopub.status.idle":"2024-04-20T18:38:28.294434Z","shell.execute_reply.started":"2024-04-20T18:27:46.107254Z","shell.execute_reply":"2024-04-20T18:38:28.293452Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}