{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipfml import processing\n",
    "from ipfml import utils\n",
    "from ipfml import metrics\n",
    "from PIL import Image\n",
    "from scipy import signal\n",
    "from skimage import color\n",
    "import scipy.stats as stats\n",
    "import seaborn as sns\n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "from pylab import *\n",
    "from skimage import data, io, color\n",
    "from skimage import feature\n",
    "\n",
    "import cv2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_folder = \"../fichiersSVD_light\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Local Binary Pattern analysis on Synthesis Images for noise dectection "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Utils functions definition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_images_path(dict_data):\n",
    "    \n",
    "    all_images_path = []\n",
    "    for cur_dict in dict_data:\n",
    "        scene = cur_dict['name']\n",
    "        prefix = cur_dict['prefix']\n",
    "        indices = cur_dict['indices']\n",
    "\n",
    "        scene_images_path = []\n",
    "        for index in indices:\n",
    "            path = os.path.join(data_folder, os.path.join(scene, prefix + index + \".png\"))\n",
    "            scene_images_path.append(path)\n",
    "            \n",
    "        all_images_path.append(scene_images_path)\n",
    "            \n",
    "    return all_images_path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def display_sv_data(dict_data, interval, all_images_path):\n",
    "    \n",
    "    sv_values = []\n",
    "    plt.figure(figsize=(25, 20))\n",
    "    begin, end = interval\n",
    "    \n",
    "    for id_dict, cur_dict in enumerate(dict_data):\n",
    "        \n",
    "        scene_name = cur_dict['name']\n",
    "        image_indices = cur_dict['indices']\n",
    "        scene_sv_values = []\n",
    "    \n",
    "        for id_img, img_path in enumerate(all_images_path[id_dict]):\n",
    "            img = Image.open(img_path)\n",
    "            print(img_path)\n",
    "            \n",
    "            blocks = processing.divide_in_blocks(img, (200, 200))\n",
    "            block = np.array(blocks[0])\n",
    "            \n",
    "            if block.ndim == 3:\n",
    "                U, s, V = processing.get_LAB_L_SVD(block)\n",
    "            else:\n",
    "                U, s, V = metrics.get_SVD(block)\n",
    "                \n",
    "            data = s[begin:end]\n",
    "            plt.plot(data, label=scene_name + '_' + str(image_indices[id_img]))\n",
    "            scene_sv_values.append(data)\n",
    "            \n",
    "        sv_values.append(scene_sv_values)\n",
    "\n",
    "    plt.legend(fontsize=18)\n",
    "    plt.show()\n",
    "    return sv_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_sv_data(cur_dict, interval, images_path_scene, norm=False):\n",
    "    \n",
    "    scene_name = cur_dict['name']\n",
    "    image_indices = cur_dict['indices']\n",
    "    zone = cur_dict['zone']\n",
    "    scene_sv_values = []\n",
    "    begin, end = interval\n",
    "    \n",
    "    plt.figure(figsize=(25, 15))\n",
    "        \n",
    "    for id_img, img_path in enumerate(images_path_scene):\n",
    "        img = Image.open(img_path)\n",
    "        \n",
    "        img = processing.divide_in_blocks(img, (200, 200))[zone]\n",
    "        \n",
    "        # Convert to L canal\n",
    "        img_grey = np.asarray(metrics.get_LAB_L(img), 'uint8')\n",
    "        \n",
    "        data_new = whiten(img_grey)\n",
    "        data_new = np.diagonal(data_new)\n",
    "        \n",
    "        data = processing.get_LAB_L_SVD_s(img)\n",
    "        \n",
    "        #Image.fromarray(new_img).show()\n",
    "        \n",
    "        if norm:\n",
    "            data_new = utils.normalize_arr(data_new)\n",
    "            data = utils.normalize_arr(data)\n",
    "        \n",
    "        plt.plot(data, label=scene_name + '_' + str(image_indices[id_img] + ' (new)'))\n",
    "        plt.plot(data_new, label=scene_name + '_' + str(image_indices[id_img]))\n",
    "        scene_sv_values.append(data)\n",
    "    \n",
    "    plt.legend(fontsize=18)\n",
    "    plt.show()\n",
    "    return scene_sv_values\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class LocalBinaryPatterns:\n",
    "\tdef __init__(self, numPoints, radius):\n",
    "\t\t# store the number of points and radius\n",
    "\t\tself.numPoints = numPoints\n",
    "\t\tself.radius = radius\n",
    " \n",
    "\tdef describe(self, image, eps=1e-7):\n",
    "\t\t# compute the Local Binary Pattern representation\n",
    "\t\t# of the image, and then use the LBP representation\n",
    "\t\t# to build the histogram of patterns\n",
    "\t\tlbp = feature.local_binary_pattern(image, self.numPoints,\n",
    "\t\t\tself.radius, method=\"uniform\")\n",
    "\t\t(hist, _) = np.histogram(lbp.ravel(),\n",
    "\t\t\tbins=np.arange(0, self.numPoints + 3),\n",
    "\t\t\trange=(0, self.numPoints + 2))\n",
    " \n",
    "\t\t# normalize the histogram\n",
    "\t\thist = hist.astype(\"float\")\n",
    "\t\thist /= (hist.sum() + eps)\n",
    " \n",
    "\t\t# return the histogram of Local Binary Patterns\n",
    "\t\treturn hist"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scenes zones data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# start 00020 - ref 00900 - step 10\n",
    "dict_appart = {'name': 'Appart1opt02', \n",
    "               'prefix': 'appartAopt_', \n",
    "               'indices': [\"00020\", \"00200\", \"00300\", \"00900\"],\n",
    "               'zone': 6}\n",
    "\n",
    "# start 00050 - ref 01200 - step 10\n",
    "dict_cuisine = {'name': 'Cuisine01', \n",
    "               'prefix': 'cuisine01_', \n",
    "               'indices': [\"00050\", \"00400\", \"01200\"],\n",
    "               'zone': 6}\n",
    "\n",
    "# start 00020 - ref 00950 - step 10\n",
    "dict_sdb_c = {'name': 'SdbCentre', \n",
    "               'prefix': 'SdB2_', \n",
    "               'indices': [\"00020\", \"00400\", \"00950\"],\n",
    "               'zone': 6}\n",
    "\n",
    "# start 00020 - ref 00950 - step 10\n",
    "dict_sdb_d = {'name': 'SdbDroite', \n",
    "               'prefix': 'SdB2_D_', \n",
    "               'indices': [\"00020\", \"00400\", \"00950\"],\n",
    "               'zone': 6}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "all_dicts = [dict_appart, dict_cuisine, dict_sdb_c, dict_sdb_d]\n",
    "interval = (30, 200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "images_path = compute_images_path(all_dicts)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "thesis-venv",
   "language": "python",
   "name": "thesis-venv"
  },
  "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": 2
}
