{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import os\n",
    "import argparse\n",
    "import json\n",
    "import cv2\n",
    "import sys\n",
    "sys.path += [os.path.abspath('keras-yolo3-master')]\n",
    "\n",
    "from utils.utils import get_yolo_boxes, makedirs\n",
    "from utils.bbox import draw_boxes\n",
    "from tensorflow.keras.models import load_model\n",
    "from tqdm import tqdm\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from panel_disconnect import disconnect\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Define Image Path and output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_path   = 'images/Mision 23_DJI_0061.jpg' \n",
    "#output_path  = 'Result_Complete_Example/'\n",
    "#makedirs(output_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load Model (Panel Detector, Soiling, Diode, Cell Damage)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n",
      "WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n",
      "WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n",
      "WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n"
     ]
    }
   ],
   "source": [
    "## Config of trained model, change this for use different trained model\n",
    "config_path_panel  = 'config_full_yolo_panel_infer.json' #Panel\n",
    "config_path_soiling  = 'config_full_yolo_fault_1_infer.json' #Soiling\n",
    "config_path_diode  = 'config_full_yolo_fault_4_infer.json'  #Diode\n",
    "config_path_cellD  = 'config_full_yolo_fault_2_infer.json'  #Cell Damage\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## Parameters of detection\n",
    "net_h, net_w = 416, 416 # a multiple of 32, the smaller the faster\n",
    "obj_thresh, nms_thresh, nms_thresh_panel = 0.5, 0.45, 0.3\n",
    "\n",
    "####################################################\n",
    "#####   Load the model Panel Detector  #############\n",
    "####################################################\n",
    "with open(config_path_panel) as config_buffer:\n",
    "        config_panel = json.load(config_buffer)\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = config_panel['train']['gpus']\n",
    "infer_model_panel = load_model(config_panel['train']['saved_weights_name'])\n",
    "\n",
    "####################################################\n",
    "#####   Load the model Soiling  #############\n",
    "####################################################\n",
    "with open(config_path_soiling) as config_buffer:\n",
    "        config_soiling = json.load(config_buffer)\n",
    "\n",
    "infer_model_soiling = load_model(config_soiling['train']['saved_weights_name'])\n",
    "\n",
    "####################################################\n",
    "#####   Load the model Diode  #############\n",
    "####################################################\n",
    "with open(config_path_diode) as config_buffer:\n",
    "        config_diode = json.load(config_buffer)\n",
    "\n",
    "infer_model_diode = load_model(config_diode['train']['saved_weights_name'])\n",
    "\n",
    "####################################################\n",
    "#####   Load the model Cell Damage  #############\n",
    "####################################################\n",
    "with open(config_path_cellD) as config_buffer:\n",
    "        config_cellD = json.load(config_buffer)\n",
    "\n",
    "infer_model_cellD = load_model(config_cellD['train']['saved_weights_name'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load Image paths"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_paths = []\n",
    "\n",
    "if os.path.isdir(input_path):\n",
    "    for inp_file in os.listdir(input_path):\n",
    "        image_paths += [input_path + inp_file]\n",
    "else:\n",
    "    image_paths += [input_path]\n",
    "\n",
    "image_paths = [inp_file for inp_file in image_paths if (inp_file[-4:] in ['.jpg', '.png', 'JPEG'])]\n",
    "\n",
    "# the main loop\n",
    "times = []\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Detection of images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "images/Mision 23_DJI_0061.jpg\n",
      "Elapsed time = 5.464144468307495\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 377280 characters]\n",
      "text/plain": [
       "<Figure size 1152x1152 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "for image_path in image_paths:\n",
    "    image = cv2.imread(image_path)\n",
    "    print(image_path)\n",
    "    start = time.time()\n",
    "    # predict the bounding boxes\n",
    "    boxes_soiling = get_yolo_boxes(infer_model_soiling, [image], net_h, net_w, config_soiling['model']['anchors'], obj_thresh, nms_thresh)[0]\n",
    "    boxes_diode = get_yolo_boxes(infer_model_diode, [image], net_h, net_w, config_diode['model']['anchors'], obj_thresh, nms_thresh)[0]\n",
    "    boxes_cellD = get_yolo_boxes(infer_model_cellD, [image], net_h, net_w, config_cellD['model']['anchors'], obj_thresh, nms_thresh)[0]\n",
    "    boxes_panel = get_yolo_boxes(infer_model_panel, [image], net_h, net_w, config_panel['model']['anchors'], obj_thresh, nms_thresh_panel)[0]\n",
    "    boxes_panel = [box for box in boxes_panel if box.get_score() > obj_thresh]\n",
    "    boxes_disc = disconnect(image, boxes_panel, z_thresh = 1.8)\n",
    "    print('Elapsed time = {}'.format(time.time() - start))\n",
    "    times.append(time.time() - start)\n",
    "    # Draw boxes\n",
    "    draw_boxes(image, boxes_soiling, config_soiling['model']['labels'], obj_thresh, number_color = 0)\n",
    "    draw_boxes(image, boxes_diode, config_diode['model']['labels'], obj_thresh, number_color = 2)\n",
    "    draw_boxes(image, boxes_cellD, config_cellD['model']['labels'], obj_thresh, number_color = 4)\n",
    "    draw_boxes(image, boxes_disc, ['disc'], obj_thresh, number_color = 5)\n",
    "    \n",
    "    # write the image with bounding boxes to file\n",
    "    plt.figure(figsize=(16, 16))\n",
    "    plt.imshow(image)\n",
    "\n",
    "#file = open(output_path + 'time.txt','w')\n",
    "#file.write('Tiempo promedio:' + str(np.mean(times)))\n",
    "#file.close()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Type Fault\n",
    "## 1: Soiling Fault\n",
    "## 2: Affected Cell \n",
    "## 4: Diode Fault\n",
    "## disc: Panel Disconnected"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
