{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Open cv library\n",
    "import cv2\n",
    "\n",
    "# matplotlib for displaying the images \n",
    "from matplotlib import pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = cv2.imread('dolphin.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 132576 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def printI(img):\n",
    "    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
    "    plt.imshow(rgb)\n",
    "    \n",
    "def printI2(i1, i2):\n",
    "    fig = plt.figure()\n",
    "    ax1 = fig.add_subplot(1,2,1)\n",
    "    ax1.imshow(cv2.cvtColor(i1, cv2.COLOR_BGR2RGB))\n",
    "    ax2 = fig.add_subplot(1,2,2)\n",
    "    ax2.imshow(cv2.cvtColor(i2, cv2.COLOR_BGR2RGB))\n",
    "    \n",
    "printI(img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 75860 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def pixelate(img, w, h):\n",
    "    height, width = img.shape[:2]\n",
    "\n",
    "    # Resize input to \"pixelated\" size\n",
    "    temp = cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR)\n",
    "\n",
    "    # Initialize output image\n",
    "    return cv2.resize(temp, (width, height), interpolation=cv2.INTER_NEAREST)\n",
    "\n",
    "img16 = pixelate(img, 16, 16)\n",
    "\n",
    "printI2(img, img16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 76676 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "img32 = pixelate(img, 32, 32)\n",
    "img64 = pixelate(img, 64, 64)\n",
    "\n",
    "printI2(img32, img64)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 6048 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "img8 = pixelate(img, 8, 8)\n",
    "printI(img8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import skimage\n",
    "from sklearn.cluster import KMeans\n",
    "from numpy import linalg as LA\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def colorClustering(idx, img, k):\n",
    "    clusterValues = []\n",
    "    for _ in range(0, k):\n",
    "        clusterValues.append([])\n",
    "    \n",
    "    for r in range(0, idx.shape[0]):\n",
    "        for c in range(0, idx.shape[1]):\n",
    "            clusterValues[idx[r][c]].append(img[r][c])\n",
    "\n",
    "    imgC = np.copy(img)\n",
    "\n",
    "    clusterAverages = []\n",
    "    for i in range(0, k):\n",
    "        clusterAverages.append(np.average(clusterValues[i], axis=0))\n",
    "    \n",
    "    for r in range(0, idx.shape[0]):\n",
    "        for c in range(0, idx.shape[1]):\n",
    "            imgC[r][c] = clusterAverages[idx[r][c]]\n",
    "            \n",
    "    return imgC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def segmentImgClrRGB(img, k):\n",
    "    \n",
    "    imgC = np.copy(img)\n",
    "    \n",
    "    h = img.shape[0]\n",
    "    w = img.shape[1]\n",
    "    \n",
    "    imgC.shape = (img.shape[0] * img.shape[1], 3)\n",
    "    \n",
    "    #5. Run k-means on the vectorized reponses X to get a vector of labels (the clusters); \n",
    "    #  \n",
    "    kmeans = KMeans(n_clusters=k, random_state=0).fit(imgC).labels_\n",
    "    \n",
    "    #6. Reshape the label results of k-means so that it has the same size as the input image\n",
    "    #   Return the label image which we call idx\n",
    "    kmeans.shape = (h, w)\n",
    "\n",
    "    return kmeans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 91092 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def kMeansImage(image, k):\n",
    "    idx = segmentImgClrRGB(image, k)\n",
    "    return colorClustering(idx, image, k)\n",
    "\n",
    "printI(kMeansImage(img, 5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9156 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "printI(kMeansImage(img32, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 267768 characters]\n",
      "text/plain": [
       "<Figure size 1296x432 with 3 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def printI3(i1, i2, i3):\n",
    "    fig = plt.figure(figsize=(18,6))\n",
    "    ax1 = fig.add_subplot(1,3,1)\n",
    "    ax1.imshow(cv2.cvtColor(i1, cv2.COLOR_BGR2RGB))\n",
    "    ax2 = fig.add_subplot(1,3,2)\n",
    "    ax2.imshow(cv2.cvtColor(i2, cv2.COLOR_BGR2RGB))\n",
    "    ax3 = fig.add_subplot(1,3,3)\n",
    "    ax3.imshow(cv2.cvtColor(i3, cv2.COLOR_BGR2RGB))\n",
    "    plt.savefig('trifecta.png')\n",
    "printI3(img, img32, kMeansImage(img32, 3))"
   ]
  }
 ],
 "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.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
