{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Image Augmentation and Visualization with Keras\n\nImage augmentation is a way to generate more training image from original training image.\nThis way increases the image by applying several random transformations to produce a plausible image.\nIn addition, models will train many aspects of the image, which will help you create a generalized model."},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport cv2\n\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\nfrom keras.applications.inception_v3 import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator, load_img","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"DATA_PATH = '../input/aptos2019-blindness-detection'\nTRAIN_IMG_PATH = os.path.join(DATA_PATH, 'train_images')\nTRAIN_LABEL_PATH = os.path.join(DATA_PATH, 'train.csv')\n\ndf_train = pd.read_csv(TRAIN_LABEL_PATH)\ndf_train['diagnosis'] = df_train['diagnosis'].astype('str')\ndf_train = df_train[['id_code', 'diagnosis']]\nif df_train['id_code'][0].split('.')[-1] != 'png':\n    for index in range(len(df_train['id_code'])):\n        df_train['id_code'][index] = df_train['id_code'][index] + '.png'\nX_train = df_train","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Image Generator"},{"metadata":{"_kg_hide-input":false,"_kg_hide-output":false,"trusted":true},"cell_type":"code","source":"def generator(datagen):\n    return datagen.flow_from_dataframe(\n        dataframe=X_train, \n        directory=TRAIN_IMG_PATH,\n        x_col='id_code',\n        y_col='diagnosis',\n        target_size=(299, 299),\n        color_mode='rgb',\n        class_mode='categorical',\n        batch_size=32,\n        shuffle=False\n    )\n\ndef visualization(generator):\n    fig, ax = plt.subplots(1, 5, figsize=(30,50))\n    count = 0\n    for X_batch, y_batch in generator:\n        while count < 5:\n            ax[count].imshow(X_batch[count])\n            count += 1\n        break\n\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Arguments\n\n- rotation_range      :  Rotation range of the image.\n\n- width_shift_range   :  Horizontal shift range of the image.\n\n- height_shift_range  :  vertical shift range of the image.\n\n- brightness_range    :  Range the brightness of the image.\n\n- zoom_range          :  Range for random zoom.\n\n- fill_mode           :  Fills the space created when rotating, moving, and shrinking an image.\n\n- horizontal_flip     :  When set to True, flip the image vertically with a 50% probability.\n\n- vertical_flip       :  When set to True, flip the image horizontally with a 50% probability.\n\n- rescale             :  The original image consists of 0-255 RGB coefficients, which are too high to effectively learn the model. Therefore, it scales it by 1/255 and converts it into 0-1 range.\n\n[Reference: Keras Documentation](https://keras.io/preprocessing/image)"},{"metadata":{},"cell_type":"markdown","source":"## 1) Original Images (No augmentation)"},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"datagen1 = ImageDataGenerator(\n    rescale=1./255\n)\nvisualization(generator(datagen1))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2) Apply horizontal flip"},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"datagen2 = ImageDataGenerator(\n    rescale=1./255,\n    horizontal_flip=True,\n    vertical_flip=True\n)\nvisualization(generator(datagen2))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3) Apply brightness"},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"datagen3 = ImageDataGenerator(\n    rescale=1./255,\n    brightness_range=[0.5, 1.5]\n)\nvisualization(generator(datagen3))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4) Apply vrious"},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"datagen4 = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=30,\n    brightness_range=[0.5, 1.5],\n    zoom_range=[0.8, 1.2],\n    horizontal_flip=True,\n    vertical_flip=False\n)\nvisualization(generator(datagen4))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 5) Apply Pre-Processing of ImageNet"},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"datagen5 = ImageDataGenerator(\n    preprocessing_function=preprocess_input\n)\nvisualization(generator(datagen5))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}