{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "ab5a5ad8-1964-7a7d-48ed-7bf7cd9b195a"
      },
      "source": [
        "This kernel outputs a text file for each input image in the training set, the format is {dot_id, point_x, point_y}\n",
        "\n",
        "**NOTE**:\n",
        "It masks the input image with some predefined colors for each dot and generates k-means clusters according to the number of class type in that particular input image. It is *NOT* 100% accurate, as some points in the image could be masked.\n",
        "\n",
        "**AGAIN**:\n",
        "Use it until a more robust labels could be generated.\n",
        "\n",
        "Credits go to KarimAmer"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "b8d1b422-fd2e-071c-ce71-1f897fbe60c4"
      },
      "outputs": [],
      "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 in \n",
        "\n",
        "import numpy as np # linear algebra\n",
        "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n",
        "\n",
        "# Input data files are available in the \"../input/\" directory.\n",
        "# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n",
        "\n",
        "from subprocess import check_output\n",
        "print(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n",
        "\n",
        "# Any results you write to the current directory are saved as output."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "8e0d52de-8879-2b4b-c89e-1bc06672a1f0"
      },
      "outputs": [],
      "source": [
        "import cv2\n",
        "import matplotlib.pyplot as plt\n",
        "import time\n",
        "import pickle\n",
        "\n",
        "plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\n",
        "plt.rcParams['image.interpolation'] = 'none'\n",
        "plt.rcParams['image.cmap'] = 'gray'\n",
        "import glob\n",
        "import os\n",
        "from sklearn.cluster import KMeans\n",
        "# import caffe\n",
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "23f86ad4-684c-7238-fe22-88417b9d775d"
      },
      "outputs": [],
      "source": [
        "#train_data = pd.read_csv('../input/Train/train.csv')\n",
        "#train_imgs = sorted(glob.glob('../input/Train/*.jpg'), key=lambda name: int(os.path.basename(name)[:-4]))\n",
        "train_df = pd.read_csv('../input/Train/train.csv')\n",
        "lion_classes = ['adult_males', 'subadult_males', 'adult_females', 'juveniles', 'pups']\n",
        "#train_df.shape[0]\n",
        "for img_fn in range(10):\n",
        "    img_fn = str(img_fn)\n",
        "    print('Image: ', img_fn)\n",
        "    for lion_class_idx, lion_class_str in enumerate(lion_classes):\n",
        "        if train_df[lion_class_str][int(img_fn)] <=0:\n",
        "            continue\n",
        "        img=cv2.imread(\"../input/TrainDotted/\"+img_fn+\".jpg\")\n",
        "        img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
        "        \n",
        "        if lion_class_idx == 0:\n",
        "            lower_red = np.array([0,(95-5)*2.55,(95-5)*2.55])\n",
        "            upper_red = np.array([2,(95+5)*2.55,(95+5)*2.55])\n",
        "            mask0 = cv2.inRange(img_hsv, lower_red, upper_red)\n",
        "            lower_red = np.array([178,(95-5)*2.55,(95-5)*2.55])\n",
        "            upper_red = np.array([180,(95+5)*2.55,(95+5)*2.55])\n",
        "            mask1 = cv2.inRange(img_hsv, lower_red, upper_red)\n",
        "            red_mask = mask0+mask1\n",
        "            mask = red_mask\n",
        "        \n",
        "        elif lion_class_idx == 1:\n",
        "            lower_magenta = np.array([150,(95-5)*2.55,(95-5)*2.55])\n",
        "            upper_magenta = np.array([155,(95+5)*2.55,(95+5)*2.55])\n",
        "            magenta_mask = cv2.inRange(img_hsv, lower_magenta, upper_magenta)\n",
        "            mask = magenta_mask\n",
        "        \n",
        "        elif lion_class_idx == 2:\n",
        "            lower_brown = np.array([12, (85-6)*2.55, (35-5)*2.55])\n",
        "            upper_brown = np.array([18, (85+16)*2.55, (35+5)*2.55])\n",
        "            brown_mask = cv2.inRange(img_hsv, lower_brown, upper_brown)\n",
        "            mask = brown_mask\n",
        "        \n",
        "        elif lion_class_idx == 3:\n",
        "            lower_blue = np.array([110, 200, (67-8)*2.55])\n",
        "            upper_blue = np.array([130, 255, (67+8)*2.55])\n",
        "            blue_mask = cv2.inRange(img_hsv, lower_blue, upper_blue)\n",
        "            mask = blue_mask\n",
        "        \n",
        "        elif lion_class_idx == 4:\n",
        "            lower_green = np.array([40, 200, (67-8)*2.55])\n",
        "            upper_green = np.array([70, 255, (67+8)*2.55])\n",
        "            green_mask = cv2.inRange(img_hsv, lower_green, upper_green)\n",
        "            mask = green_mask\n",
        "\n",
        "        dot_places = np.where(mask!=0)\n",
        "        dot_count = dot_places[0].shape[0]\n",
        "\n",
        "        X = np.array( [dot_places[0], dot_places[1]]).T\n",
        "        kmeans = KMeans(n_clusters=train_df[lion_class_str][int(img_fn)], random_state=0).fit(X)\n",
        "\n",
        "        with open(img_fn+'.txt', 'a') as txt_file:\n",
        "            for i in range(kmeans.cluster_centers_.shape[0]):\n",
        "                x, y = kmeans.cluster_centers_[i][0], kmeans.cluster_centers_[i][1]\n",
        "                txt_file.write(str(lion_class_idx)+','+str(int(x))+','+str(int(y))+'\\n')"
      ]
    }
  ],
  "metadata": {
    "_change_revision": 0,
    "_is_fork": false,
    "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.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}