{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "dbef8759",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "from itertools import product\n",
    "import os\n",
    "import sys\n",
    "from PIL import Image\n",
    "from scipy.optimize import minimize\n",
    "from time import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "b7a550e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def file_extractor(dirname=\"images\"):\n",
    "    files = os.listdir(dirname)\n",
    "    scenes = []\n",
    "    for file in files:\n",
    "        scenes.append(os.path.join(dirname, file))\n",
    "    return scenes\n",
    "\n",
    "def image_extractor(scenes):\n",
    "    image_folder = []\n",
    "    for scene in scenes:\n",
    "        files = os.listdir(scene)\n",
    "        for file in files:\n",
    "            image_folder.append(os.path.join(scene, file))\n",
    "    images = []\n",
    "    for folder in image_folder:\n",
    "        ims = os.listdir(folder)\n",
    "        for im in ims:\n",
    "            if im[-4:] == \".jp4\" or im[-7:] == \"_6.tiff\":\n",
    "                continue\n",
    "            else:\n",
    "                images.append(os.path.join(folder, im))\n",
    "    return images #returns a list of file paths to .tiff files in the specified directory given in file_extractor\n",
    "\n",
    "def im_distribution(images, num):\n",
    "    \"\"\"\n",
    "    Function that extracts tiff files from specific cameras and returns a list of all\n",
    "    the tiff files corresponding to that camera. i.e. all pictures labeled \"_7.tiff\" or otherwise\n",
    "    specified camera numbers.\n",
    "    \n",
    "    Parameters:\n",
    "        images (list): list of all tiff files, regardless of classification. This is NOT a list of directories but\n",
    "        of specific tiff files that can be opened right away. This is the list that we iterate through and \n",
    "        divide.\n",
    "        \n",
    "        num (str): a string designation for the camera number that we want to extract i.e. \"14\" for double digits\n",
    "        of \"_1\" for single digits.\n",
    "        \n",
    "    Returns:\n",
    "        tiff (list): A list of tiff files that have the specified designation from num. They are the files extracted\n",
    "        from the 'images' list that correspond to the given num.\n",
    "    \"\"\"\n",
    "    tiff = []\n",
    "    for im in images:\n",
    "        if im[-7:-5] == num:\n",
    "            tiff.append(im)\n",
    "    return tiff"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "9ed20f84",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_hist(tiff_list, i):\n",
    "    \"\"\"\n",
    "    This function is the leftovers from the first attempt to plot histograms.\n",
    "    As it stands it needs some work in order to function again. We will\n",
    "    fix this later. 1/25/22\n",
    "    \"\"\"\n",
    "    \n",
    "\n",
    "    image = tiff_list[i]\n",
    "    image = Image.open(image)    #Open the image and read it as an Image object\n",
    "    image = np.array(image)[1:,:]    #Convert to an array, leaving out the first row because the first row is just housekeeping data\n",
    "    image = image.astype(int)\n",
    "    row, col = image.shape\n",
    "    predict = np.empty([row,col])     # create a empty matrix to update prediction\n",
    "    predict[0,:] = np.copy(image[0,:])       # keep the first row from the image\n",
    "    predict[:,0] = np.copy(image[:,0])      # keep the first columen from the image\n",
    "    predict[-1,:] = np.copy(image[-1,:])       # keep the first row from the image\n",
    "    predict[:,-1] = np.copy(image[:,-1])      # keep the first columen from the image\n",
    "    diff = np.empty([row,col])\n",
    "    diff[0,:] = np.zeros(col)       # keep the first row from the image\n",
    "    diff[:,0] = np.zeros(row)\n",
    "    diff[-1,:] = np.zeros(col)       # keep the first row from the image\n",
    "    diff[:,-1] = np.zeros(row)\n",
    "    A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]])\n",
<<<<<<< HEAD
    "    '''\n",
    "    z0 = image[0:-2,0:-2]\n",
=======
    "    '''z0 = image[0:-2,0:-2]\n",
>>>>>>> 33741419ea105dcee4ccf23ef34dcfabd7c1c968
    "    z1 = image[0:-2,1:-1]\n",
    "    z2 = image[0:-2,2::]\n",
    "    z3 = image[1:-1,0:-2]\n",
    "    y0 = -z0+z2-z3\n",
    "    y1 = z0+z1+z2\n",
    "    y2 = -z0-z1-z2-z3\n",
    "    predict = [np.linalg.solve(A,np.array([y0[r,c],y1[r,c],y2[r,c]]))[-1] for r in range(0,row-2) for c in range(0,col-2)]\n",
    "    diff = [(np.max([z0[r,c],z1[r,c],z2[r,c],z3[r,c]])-np.min([z0[r,c],z1[r,c],z2[r,c],z3[r,c]])) for r in range(0,row-2) for c in range(0,col-2)]\n",
    "    '''\n",
    "    for r in range(1,row-1):                  # loop through the rth row\n",
    "        for c in range(1,col-1):              # loop through the cth column\n",
    "            actual_surrounding = np.array([image[r-1,c-1], image[r-1,c], image[r-1,c+1], image[r,c-1]])\n",
    "            #z = np.array([int(image[r-1,c-1]), int(image[r-1,c]), int(image[r-1,c+1]), int(image[r,c-1])])\n",
    "            z = np.array([image[r-1,c-1], image[r-1,c], image[r-1,c+1], image[r,c-1]])\n",
    "            y = np.array([-z[0]+z[2]-z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])\n",
    "            predict[r,c] = np.linalg.solve(A,y)[-1]\n",
    "            diff[r,c] = (np.max(actual_surrounding)-np.min(actual_surrounding))\n",
    "    predict = np.ravel(predict[1:-1,1:-1])\n",
    "    diff = np.ravel(diff[1:-1,1:-1])\n",
    "    image = np.ravel(image[1:-1,1:-1])\n",
    "    return image, predict, diff"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "8e3ef654",
   "metadata": {},
   "outputs": [],
   "source": [
    "scenes = file_extractor()\n",
    "images = image_extractor(scenes)\n",
    "num_images = im_distribution(images, \"_9\")\n",
    "error_mean = []\n",
    "error_mean1 = []\n",
    "diff_mean = []\n",
    "times = []\n",
    "times1 = []\n",
    "all_error = []\n",
    "for i in range(len(num_images)):\n",
    "    \"\"\"start1 = time()\n",
    "    image_1, predict_1, difference_1, x_s_1 = plot_hist(num_images, i, \"second\")\n",
    "    stop1 = time()\n",
    "    times1.append(stop1-start1)\n",
    "    error1 = np.abs(image_1-predict_1)\n",
    "    error_mean1.append(np.mean(np.ravel(error1)))\"\"\"\n",
    "    start = time()\n",
    "    image, predict, difference = plot_hist(num_images, i)\n",
    "    stop = time()\n",
    "    times.append(stop-start)\n",
    "    error = np.abs(image-predict)\n",
    "    all_error.append(np.ravel(error))\n",
    "    error_mean.append(np.mean(np.ravel(error)))\n",
    "    diff_mean.append(np.mean(np.ravel(difference)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a51dcb6f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average Error First and Second Added: 20.017164930235467\n",
      "Standard Deviaiton of Mean Errors: 0.16101183692474846\n",
      "Average Difference: 53.678648426455226\n",
      "Average Time per Image for First: 9.85209345817566\n"
     ]
    }
   ],
   "source": [
    "print(f\"Average Error First and Second Added: {np.mean(error_mean)}\")\n",
    "\n",
    "print(f\"Standard Deviaiton of Mean Errors: {np.sqrt(np.var(error_mean))}\")\n",
    "print(f\"Average Difference: {np.mean(diff_mean)}\")\n",
    "print(f\"Average Time per Image for First: {np.mean(times)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "dda442ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 194476 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize = (10,10))\n",
    "ax = fig.add_subplot()\n",
    "x = np.abs(predict-image)\n",
    "y = diff\n",
    "plt.plot(x,y,'o',alpha = 0.2)\n",
    "plt.rcParams.update({'font.size': 20})\n",
    "plt.xlabel(\"differnece to the true value\" )\n",
    "plt.ylabel(\"differnece of min and max of true value of the surroundings\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "58da6063",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[22554 22552 22519 22561]\n",
      "[-22596  67625 -90186]\n",
      "-17.49999999999879 -1.8333333333369712 22543.500000000004\n"
     ]
    }
   ],
   "source": [
    "image = Image.open(images[0])    #Open the image and read it as an Image object\n",
    "image = np.array(image)[1:,:]\n",
    "#z = np.array([image[1-1,1-1], image[1-1,1], image[1-1,1+1], image[1,1-1]])\n",
    "z = np.array([22554,22552,22519,22561])\n",
    "print(z)\n",
    "'''A = np.array([[-3,0,1],[0,-3,3],[-1,-3,4]])\n",
    "y = np.array([z[0]-z[2]+z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])\n",
    "a,b,c = np.linalg.solve(A,y)'''\n",
    "A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]])\n",
    "y = np.array([-z[0]+z[2]-z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])\n",
    "print(y)\n",
    "a,b,c = np.linalg.solve(A,y)\n",
    "print(a,b,c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2562feeb",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "160.16666666662906\n"
     ]
    }
   ],
   "source": [
    "i0 = (a*(-1) + b*(1) + c)\n",
    "i1 = (a*(0) + b*(1) + c)\n",
    "i2 = (a*(1) + b*(1) + c)\n",
    "i3 = (a*(-1) + b*(0) + c)\n",
    "print(sum([(i0-z[0])**2,(i1-z[1])**2,(i2-z[2])**2,(i3-z[3])**2]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "470cc137",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2032748510\n"
     ]
    }
   ],
   "source": [
    "a = 0\n",
    "b = 2\n",
    "c = 2\n",
    "i0 = (a*(-1) + b*(1) + c)\n",
    "i1 = (a*(0) + b*(1) + c)\n",
    "i2 = (a*(1) + b*(1) + c)\n",
    "i3 = (a*(-1) + b*(0) + c)\n",
    "print(sum([(i0-z[0])**2,(i1-z[1])**2,(i2-z[2])**2,(i3-z[3])**2]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3292b395",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-75749.00000000001\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\calle\\AppData\\Local\\Temp/ipykernel_15648/1729129504.py:5: RuntimeWarning: overflow encountered in ushort_scalars\n",
      "  y = np.array([z[0]-z[2]+z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])\n"
     ]
    }
   ],
   "source": [
    "z = np.hstack((image[0,:3], image[1,0]))\n",
    "x = np.array([-1,0,1,-1])\n",
    "y = np.array([-1,-1,-1,0])\n",
    "A = np.array([[-3,0,1],[0,-3,3],[1,3,-4]])\n",
    "y = np.array([z[0]-z[2]+z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])\n",
    "print(np.linalg.solve(A,y)[-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9687830",
   "metadata": {},
   "outputs": [],
   "source": [
    "0.5**2 + 1.5**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e98eed4b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
