{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h1 style=\"border:2px solid Purple;text-align:center\">Table of Contents</h1>\n\n1. [The Competition](#competition)\n\n2. [Objective](#objective)\n\n3. [Dataset](#dataset)\n\n4. [Importing the necessary libraries](#imports)\n\n5. [Disease Mappings](#mappings)\n\n6. [Trainining Dataset](#trainds)\n\n7. [Image Training Dataset](#imgtrainds)\n\n8. [Why care about Histograms](#hists)\n\n    8.1. [Healthy Leaves](#healthy)\n    \n    8.2. [Cassava Bacterial Blight (CBB)](#cbb)\n    \n    8.3. [Cassava Brown Streak Disease (CBSD)](#cbsd)\n    \n    8.4. [Cassava Green Mottle (CGM)](#cgm)\n    \n    8.5. [Cassava Mosaic Disease (CMD)](#cmd)\n\n9. [Image Augmentation](#imageaug)\n\n    9.1 [Image Augmentation - Tensorflow](#imageaugtens)\n    \n    9.2 [Image Augmentation - Pytorch](#imageaugpy)\n    \n    9.3 [Image Augmentation - Albumentations](#imagealbu)"},{"metadata":{},"cell_type":"markdown","source":"<a id=#competition></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">The Competition</h1>"},{"metadata":{},"cell_type":"markdown","source":"![](https://www.pestnet.org/fact_sheets/assets/image/cassava_brown_leaf_spot_095/46.jpg)"},{"metadata":{},"cell_type":"markdown","source":"Manihot esculenta, commonly called cassava, manioc, yuca, macaxeira, mandioca, aipim, and agbeli, is a woody shrub native to South America of the spurge family, Euphorbiaceae. Although a perennial plant, cassava is extensively cultivated as an annual crop in tropical and subtropical regions for its edible starchy tuberous root, a major source of carbohydrates. \n\nCassava is the third-largest source of food carbohydrates in the tropics, after rice and maize. Cassava is a major staple food in the developing world, providing a basic diet for over half a billion people. It is one of the most drought-tolerant crops, capable of growing on marginal soils. Nigeria is the world's largest producer of cassava, while Thailand is the largest exporter of cassava starch.\n\nSource : Wikipedia"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"objective\"></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Objective</h1>\n\n\nThe task is to classify each cassava image into four disease categories or a fifth category indicating a healthy leaf. With the help of data science, farmers may be able to quickly identify diseased plants, potentially saving their crops before they inflict irreparable damage.[](http://)"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"dataset\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Dataset</h1>\n\nIn this competition, we are introduced with a dataset of 21,367 labeled images collected during a regular survey in Uganda. Most images were crowdsourced from farmers taking photos of their gardens, and annotated by experts at the National Crops Resources Research Institute (NaCRRI) in collaboration with the AI lab at Makerere University, Kampala. This is in a format that most realistically represents what farmers would need to diagnose in real life."},{"metadata":{},"cell_type":"markdown","source":"<a id= \"imports\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Importing the Necessary Libraries</h1>"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\n# Importing Libraries for Image Augmentations\nimport tensorflow as tf\nimport torchvision\nimport albumentations as A\n\n# Working with Files\nimport os\nfrom pathlib import Path\n\n# Fancy progress bar\nfrom tqdm import tqdm\n\n# Dynamic Graphs\nimport plotly.graph_objects as go\nimport plotly_express as px\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\n\n# Static Graphs\nimport matplotlib.pyplot as plt\n\n# Working with images\nimport cv2\n\n# For plotly graphs to be rendered properly\nfrom plotly.offline import init_notebook_mode\ninit_notebook_mode()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Storing the base address of the files\nbase_path = Path('../input/cassava-leaf-disease-classification')\ntrain_img_dir = base_path /'train_images'\ntest_img_dir = base_path /'test_images'\n\n# reading the train.csv file and the json file with the labels mapped to disease names\ntrain_df = pd.read_csv(base_path/'train.csv')\ndiseaseMapping = pd.read_json(base_path/'label_num_to_disease_map.json', typ='series')\n\n# List of all train and test Images\ntrain_images = os.listdir(base_path/'train_images/')\ntest_images = os.listdir(base_path/'test_images/')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id= \"mappings\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Disease Mappings</h1>"},{"metadata":{"trusted":true},"cell_type":"code","source":"diseaseMapping","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are 5 classes for prediction in this dataset : \n\n* **Healthy** -> The Leaf is healthy\n* **Cassava Bacterial Blight (CBB)**\n* **Cassava Brown Streak Disease (CBSD)**\n* **Cassava Green Mottle (CGM)**\n* **Cassava Mosaic Disease (CMD)**\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Converting into a Dictionary\nmappingDict = diseaseMapping.to_dict()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id= \"trainds\"></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Training Dataset</h1>"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There is nothing fancy here. Just the image name and the assiciated labels with the image. Since the labels are given as numbers, we can change them to their corresponding disease name using the mapping provided. "},{"metadata":{"trusted":true},"cell_type":"code","source":"# Replacing Numeric Labels with Disease Names\ntrain_df = train_df.replace(mappingDict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Counting the Number of Training Samples for each Label\nlabelCounts = train_df['label'].value_counts().reset_index()\nlabelCounts.columns = ['Label', 'Number of Observations']\n\n# Plotting a Pie Chart to show the Distribution\nfig = px.pie(labelCounts, \n             names = 'Label',values='Number of Observations', \n             labels = mappingDict, \n             title = 'Distribution of Labels in the Training Dataset',\n             color_discrete_sequence=px.colors.sequential.Greens_r)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Only around 12% of the dataset is of images of healthy leaves, while the rest of the images are for diseased leaves.\n\nThe images of Cassava Mosaic Disease (CMD) are the most abundant taking up more than half of the dataset. "},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"uniqueIds = train_df['image_id'].nunique()\nif(uniqueIds == len(train_df)):\n    print('There are no repeating Image IDs in the dataset')\nelse:\n    print(f'There are {len(train_df) - uniqueIds} repeating Image IDs')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The training dataset does not have repeating Image IDs. However, it might still be the case that there are duplicate images in the dataset"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"imgtrainds\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Training Image Dataset</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"print(f'There are {len(train_images)} training images in the dataset')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"healthyImages = train_df[train_df['label'] == 'Healthy']['image_id'].to_list()\ncbbImages = train_df[train_df['label'] == 'Cassava Bacterial Blight (CBB)']['image_id'].to_list()\ncbsdImages = train_df[train_df['label'] == 'Cassava Brown Streak Disease (CBSD)']['image_id'].to_list()\ncgmImages = train_df[train_df['label'] == 'Cassava Green Mottle (CGM)']['image_id'].to_list()\ncmdImages = train_df[train_df['label'] == 'Cassava Mosaic Disease (CMD)']['image_id'].to_list()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"''' code modified from Parul Pandey's notebook\nhttps://www.kaggle.com/parulpandey/melanoma-classification-eda-starter\n'''\ndef showImages(images):\n\n    # Extract 9 random images from it\n    random_images = [np.random.choice(images) for i in range(9)]\n\n    # Adjust the size of your images\n    plt.figure(figsize=(10,8))\n\n    # Iterate and plot random images\n    for i in range(9):\n        plt.subplot(3, 3, i + 1)\n        img = plt.imread(train_img_dir/random_images[i])\n        plt.imshow(img, cmap='gray')\n        plt.axis('off')\n\n    # Adjust subplot parameters to give specified padding\n    plt.tight_layout()   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"''' code used from Parul Pandey's notebook\nhttps://www.kaggle.com/parulpandey/melanoma-classification-eda-starter\n'''\n\ndef showHistogram(sample_img, title):\n    f = plt.figure(figsize=(16,8))\n    f.add_subplot(1,2, 1)\n\n    raw_image = plt.imread(train_img_dir/sample_img)\n    plt.imshow(raw_image, cmap='gray')\n    plt.colorbar()\n    plt.title(title)\n    print(f\"Image dimensions:  {raw_image.shape[0],raw_image.shape[1]}\")\n    print(f\"Maximum pixel value : {raw_image.max():.1f} ; Minimum pixel value:{raw_image.min():.1f}\")\n    print(f\"Mean value of the pixels : {raw_image.mean():.1f} ; Standard deviation : {raw_image.std():.1f}\")\n\n    f.add_subplot(1,2, 2)\n\n    #_ = plt.hist(raw_image.ravel(),bins = 256, color = 'orange',)\n    _ = plt.hist(raw_image[:, :, 0].ravel(), bins = 256, color = 'red', alpha = 0.5)\n    _ = plt.hist(raw_image[:, :, 1].ravel(), bins = 256, color = 'Green', alpha = 0.5)\n    _ = plt.hist(raw_image[:, :, 2].ravel(), bins = 256, color = 'Blue', alpha = 0.5)\n    _ = plt.xlabel('Intensity Value')\n    _ = plt.ylabel('Count')\n    _ = plt.legend(['Red_Channel', 'Green_Channel', 'Blue_Channel'])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"'''\nInspired and modified from Tarun Paparaju's Work\nhttps://www.kaggle.com/tarunpaparaju/plant-pathology-2020-eda-models\n'''\n\ndef load_image(image_id):\n    image = cv2.imread(str(train_img_dir/image_id))\n    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\ndef showChannelDistribution(images, leafType):\n    imageArray = [load_image(image_id) for image_id in images]\n    \n    red_values = [np.mean(imageArray[idx][:, :, 0]) for idx in range(len(imageArray))]\n    green_values = [np.mean(imageArray[idx][:, :, 1]) for idx in range(len(imageArray))]\n    blue_values = [np.mean(imageArray[idx][:, :, 2]) for idx in range(len(imageArray))]\n    values = [np.mean(imageArray[idx]) for idx in range(len(imageArray))]\n    \n    hist_data = [red_values, green_values, blue_values, values]\n    group_labels = ['Red', 'Green', 'Blue', 'All']\n\n    fig = ff.create_distplot(hist_data, group_labels,colors = ['red', 'green','blue','grey'])\n    fig.update_layout(template = 'plotly_white', title_text = f'Channel Distribution - {leafType}')\n    fig.show()\n    return hist_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def showBoxPlot(histData, leafType):\n    figData = []\n    for i, name in zip(range(3), ['Red', 'Green', 'Blue']):\n        trace = go.Box(y = histData[i], name = name, boxpoints='all', marker_color  = name)\n        figData.append(trace)\n\n    fig = go.Figure(figData)\n    fig.update_layout(title_text = f'Pixel Intensity Distribution - {leafType}', template = 'plotly_white')\n    fig.show() ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id= \"hists\" ></a>\n<h1 style=\"border:2px solid Blue;text-align:center\">Why care about Image Histograms?</h1>\n\nIn image processing histograms are used to depict many aspects regarding the image we are working with. Such as,\n- Exposure\n- Contrast\n- Dynamic Range\n- Saturation\n\nand many more. \n\nBy visualizing the histogram we can improve the visual presence of an image and also we can find out what type of image processing could have been applied by comparing the histograms of an image.\n\nSource : [Histogram in Image Processing with skImage-Python](https://towardsdatascience.com/histograms-in-image-processing-with-skimage-python-be5938962935)"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"healthy\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Healthy Leaves</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showImages(healthyImages)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showHistogram(healthyImages[0], 'Healthy Image')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"data = showChannelDistribution(healthyImages, 'Healthy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"showBoxPlot(data, 'Healthy Leaves')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We see a  difference in the median values of the pixel intensities for each of the channels:\n- Red - 108\n- Green - 126\n- Blue - 80"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"cbb\"></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">CBB Images</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showImages(cbbImages)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showHistogram(cbbImages[0], 'CBB Image')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"data = showChannelDistribution(cbbImages, 'CBB Images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"showBoxPlot(data, 'CBB Images')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For CBB Images, the median values of the pixel intensities for the 3 channels are:\n- Red - 102\n- Green - 117\n- Blue - 66"},{"metadata":{},"cell_type":"markdown","source":"We can see that the median values for the Blue channel are lower than healthy Images. This makes the difference between the median pixel intensity much more striking between the Blue and Red channel. "},{"metadata":{},"cell_type":"markdown","source":"<a id= \"cbsd\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">CBSD Images</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showImages(cbsdImages)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showHistogram(cbsdImages[0], 'CBSD Image')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"data = showChannelDistribution(cbsdImages, 'CBSD Images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"showBoxPlot(data, 'CBSD Images')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The median values for different channels for CBSD Images are:\n- Red - 106\n- Green - 123\n- Blue - 72"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"cgm\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">CGM Images</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showImages(cgmImages)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showHistogram(cgmImages[0], 'CGM Image')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"data = showChannelDistribution(cgmImages, 'CGM Images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"showBoxPlot(data, 'CGM Images')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The median values of pixel intensity for CGM Images for the 3 channels are \n\n- Red - 113\n- Green - 128\n- Blue - 85"},{"metadata":{},"cell_type":"markdown","source":"<a id= \"cmd\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">CMD Images</h1>"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showImages(cmdImages)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"showHistogram(cmdImages[0], 'CMD Image')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# Doing this for the First 2k CMD Images, as doing this for all the images crashes the notebook\ndata = showChannelDistribution(cmdImages[:2000], 'CMD Images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"showBoxPlot(data, 'CMD Images')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The pixel intensities median value for the first 2k CMD Images are\n- Red - 110\n- Green - 128\n- Blue -80"},{"metadata":{},"cell_type":"markdown","source":"### Insights\n- CGM types images have the highest median RGB values \n- CBB type images have the lowest median RGB values\n- The channel intensity median values follow this trend G>R>B"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"channelIntensityDf = pd.DataFrame(\n    {\n        'Leaf Type' : ['Healthy', 'CBB','CBSD', 'CGM', 'CMD'], \n        'Red Channel Mean' : [108,102,106,113,110],\n        'Green Channel Mean' : [126,117,123,128,128],\n        'Blue Channel Mean' : [80,66,72,85,80]\n    }\n)\n\nchannelIntensityDf.style.background_gradient(cmap='Greens', axis = 0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id = \"imageaug\" ></a>\n<h1 style=\"border:2px solid Purple;text-align:center\">Image Augmentations</h1>"},{"metadata":{},"cell_type":"markdown","source":"<a id = \"imageaugtens\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Image Augmentations - Tensorflow</h1>\n\nTensorflow offers tons of Image Augmentations as part of its tf.image module and many more as part of tensorflow addons. \n\nLink to the tf.image module docs -> https://www.tensorflow.org/api_docs/python/tf/image\n\nLink to tensorflow addons image module docs -> https://www.tensorflow.org/addons/api_docs/python/tfa/image/"},{"metadata":{"trusted":true},"cell_type":"code","source":"def augmentImage(imageFile, seed = 0):\n    image = tf.io.read_file(str(train_img_dir/imageFile))\n    image = tf.image.decode_jpeg(image,channels = 3)\n    actual_image = image\n    brightness = tf.image.random_brightness(image, 0.2, seed = seed)\n    contrast = tf.image.random_contrast(image, 0.2,0.3, seed = seed)\n    crop = tf.image.random_crop(image, size = [448,448,3], seed = seed)\n    left_right = tf.image.flip_left_right(image) #replace with random_flip_left_right when using as part of a augmentation pipeline\n    up_down = tf.image.flip_up_down(image) #replace with random_flip_up_down when using as part of a augmentation pipeline\n    hue = tf.image.random_hue(image, 0.2, seed = seed)\n    saturation = tf.image.random_saturation(image, 5,10, seed = seed)\n    jpeg_quality = tf.image.random_jpeg_quality(image, 75,85)\n    \n    return (\n        actual_image, \n        brightness,\n        contrast,\n        crop,\n        left_right,\n        up_down,\n        hue,\n        saturation, \n        jpeg_quality\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"augmentedImages = augmentImage(healthyImages[0])\nplt.figure(figsize=(10, 10))\nfor i, imageName in zip(range(9), ['Input Image', 'Augmented - Brightness','Augmented - Contrast','Augmented - Crop','Augmented - Horizontal Flip',\n                                  'Augmented - Vertical Flip','Augmented - Hue','Augmented - Saturation','Augmented - Jpeg Quality']):\n    ax = plt.subplot(3, 3, i + 1)\n    plt.imshow(augmentedImages[i].numpy().astype(\"uint8\"))\n    plt.title(imageName)\n    plt.axis(\"off\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id = \"imageaugpy\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Image Augmentations - Pytorch</h1>\n\nYou can find more image augmentation examples from the official Pytorch Documentation. \n\nLink to the docs -> https://pytorch.org/docs/stable/torchvision/transforms.html"},{"metadata":{"trusted":true},"cell_type":"code","source":"def augmentImage(imageFile):\n    image = load_image(imageFile)\n    image = torchvision.transforms.ToPILImage()(image)\n    actual_image = image\n    brightness = torchvision.transforms.ColorJitter(brightness=0.2)(image)\n    contrast = torchvision.transforms.ColorJitter(contrast=(0.2,0.3))(image)\n    crop = torchvision.transforms.RandomCrop((448,448))(image)\n    left_right = torchvision.transforms.RandomHorizontalFlip(p = 1.0)(image)\n    up_down = torchvision.transforms.RandomVerticalFlip(p = 1.0)(image)\n    hue = torchvision.transforms.ColorJitter(hue=0.2)(image)\n    saturation = torchvision.transforms.ColorJitter(saturation=(0.05,0.1))(image)\n    perspective = torchvision.transforms.RandomPerspective(p= 1.0)(image)\n    \n    return (\n        actual_image, \n        brightness,\n        contrast,\n        crop,\n        left_right,\n        up_down,\n        hue,\n        saturation, \n        perspective\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"augmentedImages = augmentImage(healthyImages[0])\nplt.figure(figsize=(10, 10))\nfor i, imageName in zip(range(9), ['Input Image', 'Augmented - Brightness','Augmented - Contrast','Augmented - Crop','Augmented - Horizontal Flip',\n                                  'Augmented - Vertical Flip','Augmented - Hue','Augmented - Saturation','Augmented - Perspective']):\n    ax = plt.subplot(3, 3, i + 1)\n    plt.imshow(augmentedImages[i])\n    plt.title(imageName)\n    plt.axis(\"off\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id = \"imageaugalbu\" ></a>\n<h1 style=\"border:2px solid LightGreen;text-align:center\">Image Augmentations - Albumentations</h1>\n\nAs Kagglers, we should be more aware of Albumentations as an Augmentation library. It blends well with both tensorflow and pytorch. \n\n#### Why use Albumentations?\n\n> Albumentations is a Python library for fast and flexible image augmentations. Albumentations efficiently implements a rich variety of image transform operations that are optimized for performance, and does so while providing a concise, yet powerful image augmentation interface for different computer vision tasks, including object classification, segmentation, and detection.\n\nAlbumentations offers a wide variety of Augmentations for all sorts of Computer Vision tasks. You can read more abut the available augmentations at -> https://albumentations.ai/docs/api_reference/augmentations/transforms/\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"def augmentImage(imageFile):\n    image = load_image(imageFile)\n    actual_image = image\n    brightness = A.RandomBrightness(limit = 0.2, p = 1.0)(image = image)['image']\n    contrast = A.RandomContrast(limit = 0.2,p = 1.0)(image = image)['image']\n    crop = A.RandomCrop(448,448)(image = image)['image']\n    left_right = A.HorizontalFlip(p = 1.0)(image = image)['image']\n    up_down = A.VerticalFlip(p = 1.0)(image = image)['image']\n    hue = A.ColorJitter(hue=0.2,brightness=0,saturation=0, contrast=0,p=1.0)(image = image)['image']\n    saturation = A.ColorJitter(hue=0,brightness=0,saturation=0.2, contrast=0,p=1.0)(image = image)['image']\n    downscale = A.Downscale(scale_min = 0.25, scale_max = 0.25,p= 1.0)(image = image)['image']\n    \n    return (\n        actual_image, \n        brightness,\n        contrast,\n        crop,\n        left_right,\n        up_down,\n        hue,\n        saturation, \n        downscale\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"augmentedImages = augmentImage(healthyImages[0])\nplt.figure(figsize=(10, 10))\nfor i, imageName in zip(range(9), ['Input Image', 'Augmented - Brightness','Augmented - Contrast','Augmented - Crop','Augmented - Horizontal Flip',\n                                  'Augmented - Vertical Flip','Augmented - Hue','Augmented - Saturation','Augmented - Quality']):\n    ax = plt.subplot(3, 3, i + 1)\n    plt.imshow(augmentedImages[i])\n    plt.title(imageName)\n    plt.axis(\"off\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Work in progress"}],"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":4,"nbformat_minor":4}