{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","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"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"}],"dockerImageVersionId":29271,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Browse through images and try to guess the stage of DR\n\nThis kernel allows you to browse through randomly selected images one on at a time (in an interactive session) and guess the label.\n\nFirst, you see the image without label and can try to classify it yourself.  \nThen, you'll see the image with the label and check if your guess was correct.\n\nJust scroll to the bottom to give it a try!","metadata":{}},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nfrom os.path import join\n\nimport numpy as np\nfrom numpy.random import choice\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom PIL import ImageDraw, ImageFont, Image\n\nimport ipywidgets as widgets\nfrom ipywidgets import interactive, IntSlider\nfrom IPython.display import display\n\nimport torch\nfrom torchvision import transforms\nimport torchvision","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-02-19T15:26:08.910549Z","iopub.execute_input":"2023-02-19T15:26:08.911133Z","iopub.status.idle":"2023-02-19T15:26:09.988891Z","shell.execute_reply.started":"2023-02-19T15:26:08.911086Z","shell.execute_reply":"2023-02-19T15:26:09.988022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_DIR = '../input/aptos2019-blindness-detection'\n\ntrain_dir = join(DATA_DIR, 'train_images')\ntrain_df  = pd.read_csv(os.path.join(DATA_DIR, 'train.csv'))","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-02-19T15:26:09.990489Z","iopub.execute_input":"2023-02-19T15:26:09.990710Z","iopub.status.idle":"2023-02-19T15:26:10.010125Z","shell.execute_reply.started":"2023-02-19T15:26:09.990667Z","shell.execute_reply":"2023-02-19T15:26:10.009173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Examples of labeld images","metadata":{}},{"cell_type":"code","source":"def annotate_image(image: Image,\n                   text: str,\n                   bounding_box=((0, 0), (20, 15)),\n                   fontsize=20):\n    \n    draw = ImageDraw.Draw(image)\n    draw.rectangle(bounding_box, fill='white', outline='black')\n    draw.text((2, 1), text, fill='black')\n    \n    return image\n\n\ndef sample_images(data_dir: str,\n                  files=None,\n                  resize_to=None,\n                  n=15,\n                  label_df=None,\n                  id_col='id_code',\n                  label_col='diagnosis'):\n    \n    if files is None:\n        files = choice(os.listdir(data_dir), size=n)\n        \n    images = []\n    for filename in files:\n        img = Image.open(join(train_dir, filename))\n        \n        if resize_to is not None:\n            img = img.resize(resize_to)\n        \n        if label_df is not None:\n            id_   = filename.split('.')[0]\n            label = label_df[label_df[id_col] == id_][label_col].item()\n            img   = annotate_image(img, f'y={label}')\n            \n        images.append(img)\n        \n    return images\n\n\ndef show_grid(*args, n=5, **kwargs):\n    \n    images = sample_images(*args, n=n, **kwargs)\n\n    tensors = list(map(transforms.ToTensor(), images))\n    tensor  = torch.stack(tensors)\n    grid    = torchvision.utils.make_grid(tensor, nrow=n // int(np.ceil(n / 5)))\n    \n    plt.figure(figsize=(24, 10))\n    plt.imshow(grid.permute(1, 2, 0))\n    plt.grid(False)\n    plt.xticks([])\n    plt.yticks([]);\n    plt.show()\n\nshow_grid(data_dir=train_dir, resize_to=(128, 128), n=5, label_df=train_df)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-02-19T15:26:10.011655Z","iopub.execute_input":"2023-02-19T15:26:10.011914Z","iopub.status.idle":"2023-02-19T15:26:11.659495Z","shell.execute_reply.started":"2023-02-19T15:26:10.011861Z","shell.execute_reply":"2023-02-19T15:26:11.658133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Guess the label (interactive)\n\n### Stages of diabetic retinopathy\n\n    0 - No DR\n\n    1 - Mild\n\n    2 - Moderate\n\n    3 - Severe\n\n    4 - Proliferative DR\n    \n    \n### Random examples per stage","metadata":{}},{"cell_type":"code","source":"for y, group_df in train_df.groupby('diagnosis'):\n    print(f'-------------------------------\\nstage {y}:')\n    example_id = group_df.sample(1).id_code.item()\n    image = Image.open(join(train_dir, f'{example_id}.png'))\n    plt.imshow(image)\n    plt.xticks([])\n    plt.yticks([])\n    plt.show()\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-02-19T15:26:11.660935Z","iopub.execute_input":"2023-02-19T15:26:11.661257Z","iopub.status.idle":"2023-02-19T15:26:13.603077Z","shell.execute_reply.started":"2023-02-19T15:26:11.661192Z","shell.execute_reply":"2023-02-19T15:26:13.602273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Class frequency","metadata":{}},{"cell_type":"code","source":"train_df.diagnosis.hist()\nplt.xticks(range(5))\nplt.title('frequency of diagnoses')\nplt.xlabel('stage')\nplt.ylabel('number of training images');","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-02-19T15:26:13.604509Z","iopub.execute_input":"2023-02-19T15:26:13.604933Z","iopub.status.idle":"2023-02-19T15:26:13.819337Z","shell.execute_reply.started":"2023-02-19T15:26:13.604890Z","shell.execute_reply":"2023-02-19T15:26:13.818746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Guess label\n\nJust start scrolling through the images:\n\nFirst, you'll see the unlabled image.  \nThen, you'll see the same image with the label.  ","metadata":{}},{"cell_type":"code","source":"def guess_label(image_dir,\n                label_df,\n                resize_to=None,\n                n=10):\n    \n    images = []\n    \n    for _ in range(n):\n        file = choice(os.listdir(image_dir))\n        \n        # raw and labeled version of the same image:\n        raw = sample_images(image_dir, files=[file], label_df=None)[0]\n        labeled = sample_images(image_dir, files=[file], label_df=label_df, resize_to=resize_to)[0]\n        \n        images.extend([raw, labeled])  # order: raw, labeld, raw, ....\n\n    def show_image(i):\n        \n        plt.figure(figsize=(24, 10))\n        img = images[i]\n        \n        if resize_to is not None:\n            img = img.resize(resize_to)            \n        \n        plt.imshow(img)\n        plt.grid(False)\n        plt.xticks([])\n        plt.yticks([]);\n        plt.show()    \n\n    return interactive(show_image, i=IntSlider(min=0, max=n*2 - 1))\n\nguess_label(image_dir=train_dir,\n            label_df=train_df,\n            resize_to=(224, 224),\n            n=25)","metadata":{"execution":{"iopub.status.busy":"2023-02-19T15:26:13.820999Z","iopub.execute_input":"2023-02-19T15:26:13.821390Z","iopub.status.idle":"2023-02-19T15:26:18.382434Z","shell.execute_reply.started":"2023-02-19T15:26:13.821352Z","shell.execute_reply":"2023-02-19T15:26:18.381854Z"},"trusted":true},"execution_count":null,"outputs":[]}]}