{"cells":[{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\">  \n<h1><strong>🎨Getting started with GANs</strong></h1>\n    <i>“All you need to paint is a few tools, a little instruction, and a vision in your mind.” -Bob Ross😁</i>\n</div>"},{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-warning\">  \n<h1><strong>So what are GANs?</strong></h1>\n    <p> GANs or Generative Adversial Networks comprise atleast two neural networks that are trained simultaneously, namely the <b>generator</b> and the <b>discriminator</b>. <br><br>\n        The generator learns how to create new images over time that resemble real images and tries to confuse the discriminator whose sole aim is to differentiate between which image is really real and which one is fake/generated.\n    </p>\n</div>\n\n\n![](https://www.tensorflow.org/tutorials/generative/images/gan1.png)\n\n![](https://www.tensorflow.org/tutorials/generative/images/gan2.png)"},{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-warning\">  \n<h1><strong>Moving forward to CycleGAN</strong></h1>\n    <p>CycleGAN uses a <b>cycle consistency loss</b> to enable training <b>without the need for paired data</b>. It can translate from one domain to the other without the need of a one-to-one mapping between the source and target domain. All we requre is a directory of source and target images. <br><br>\n      Use cases:  \n<ul>\n    <li>photo-enhancement</li>\n    <li>image colorization</li>\n    <li>style transfer</li>\n</ul>\n <a href=\"https://www.tensorflow.org/tutorials/generative/cyclegan\">Reference</a>\n    </p>\n</div>"},{"metadata":{},"cell_type":"markdown","source":"<h3>\nA sneak peak into the data we're working with\n</h3>"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true,"_kg_hide-input":true},"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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Imports <h3>"},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport cv2\n\nfrom colorama import Fore, Back, Style\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\ny_ = Fore.YELLOW\nr_ = Fore.RED\ng_ = Fore.GREEN\nb_ = Fore.BLUE\nm_ = Fore.MAGENTA\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n    \nprint(tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"monet_jpg_directory = '../input/gan-getting-started/monet_jpg/'\nphoto_jpg_directory = '../input/gan-getting-started/photo_jpg/'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Getting image paths from the directory </h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"def getImagePaths(path):\n    image_names = []\n    for dirname, _, filenames in os.walk(path):\n        for filename in filenames:\n            fullpath = os.path.join(dirname, filename)\n            image_names.append(fullpath)\n    return image_names","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"monet_images_path = getImagePaths(monet_jpg_directory)\nphoto_images_path = getImagePaths(photo_jpg_directory)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Number of images in each directory </h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f\"{y_}Number of Monet images: {g_} {len(monet_images_path)}\\n\")\nprint(f\"{y_}Number of Photo images: {g_} {len(photo_images_path)}\\n\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Checking if images in each directory have the same shape </h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"def getShape(images_paths):\n    shape = cv2.imread(images_paths[0]).shape\n    for image_path in images_paths:\n        image_shape=cv2.imread(image_path).shape\n        if (image_shape!=shape):\n            return \"Different image shape\"\n        else:\n            return \"Same image shape \" + str(shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"getShape(monet_images_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"getShape(photo_images_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_multiple_img(images_paths, rows, cols):\n    figure, ax = plt.subplots(nrows=rows,ncols=cols,figsize=(16,8) )\n    for ind,image_path in enumerate(images_paths):\n        image=cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) \n        try:\n            ax.ravel()[ind].imshow(image)\n            ax.ravel()[ind].set_axis_off()\n        except:\n            continue;\n    plt.tight_layout()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\">  \n<h3>Monet images</h3>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"display_multiple_img(monet_images_path, 4, 4)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\">  \n<h3>Photo images</h3>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"display_multiple_img(photo_images_path, 4, 4)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\">  \n<h3>Colour Histograms</h3>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"def styling():\n    for spine in plt.gca().spines.values():\n        spine.set_visible(False)\n        plt.xticks([])\n        plt.yticks([])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def hist(image_path):\n    plt.figure(figsize=(16, 3))\n    \n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    \n    plt.subplot(1, 5, 1)\n    plt.imshow(img)\n    styling()\n    \n    custom_colors = [\"#ef233c\", \"#76da71\", \"#2667ff\",\"#aea3b0\"]\n    labels = ['Red Channel', 'Green Channel', 'Blue Channel','Total']\n    \n    for i in range(1,4):\n        plt.subplot(1, 5, i+1)\n        plt.hist(img[:, :, i-1].reshape(-1),bins=64,color=custom_colors[i-1],alpha = 0.6)\n        plt.xlabel(labels[i-1],fontsize=10)\n        styling()\n        \n    plt.subplot(1, 5, 5)\n    plt.hist(img.reshape(-1),bins=128,color=custom_colors[3],alpha = 0.6)\n    plt.xlabel(labels[3],fontsize=10)\n    styling()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def display_hist(images_paths):\n        for ind,image_path in enumerate(images_paths):\n            if (ind<6):\n                hist(image_path)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> For Monet images </h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"display_hist(monet_images_path)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> For Photo images </h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"display_hist(photo_images_path)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Work in progress 🚧 </h3>"}],"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}