{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f4850afd",
   "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 numpy import linalg as la\n",
    "from time import time\n",
    "from scipy.optimize import linprog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b240b11f",
   "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": 3,
   "id": "5d044d19",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_hist(tiff_list, i, tech = \"first\"):\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",
    "    '''jj = 0\n",
    "    fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15,12))\n",
    "    for cam, ax in zip(cameras, axs.ravel()):\n",
    "        diff = []\n",
    "        for ii in range(len(cam)):\n",
    "            image = Image.open(cam[ii])    #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",
    "            ar1, ar2 = image.shape\n",
    "            ind1, ind2 = np.random.randint(1,ar1-1), np.random.randint(1,ar2-1) #ind1 randomly selects a row, ind2 randomly selects a column, \n",
    "                                                                            #this is now a random pixel selection within the image\n",
    "            \n",
    "            surrounding = []                                                #initialize a list to be filled the 8 surrounding pixels\n",
    "            for i,j in product(np.arange(-1,2), repeat=2):                  #Iterate through the combinations of surrounding pixel indices\n",
    "                if i == 0 and j == 0:                                       #Avoid the target pixel\n",
    "                    continue\n",
    "                else:\n",
    "                    surrounding.append(image[ind1+i, ind1+j])               #Add the other 8 pixels to the list\n",
    "            diff.append(np.max(surrounding)-np.min(surrounding))\n",
    "        ax.hist(diff)\n",
    "        ax.set_title(f\"tiff {jj}\")\n",
    "        jj += 1\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    return '''\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",
    "    row, col = image.shape\n",
    "    diff = np.empty((row,col))\n",
    "    predict = np.empty([row,col])     # create a empty matrix to update prediction\n",
    "    predict[0,:] = image[0,:]       # keep the first row from the image\n",
    "    predict[:,0] = image[:,0]       # keep the first columen from the image\n",
    "    predict[-1,:] = image[-1,:]       # keep the first row from the image\n",
    "    predict[:,-1] = 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",
    "    x_s = []\n",
    "    for r in range(1,row-1):                  # loop through the rth row\n",
    "        for cc in range(1,col-1):              # loop through the cth column\n",
    "            surrounding = np.array([image[r-1,cc-1], image[r-1,cc], image[r-1,cc+1], image[r,cc-1]])\n",
    "            #Solve the linear system Ax = v for the coefficients a, b, and c\n",
    "            if tech == \"second\":\n",
    "                v = np.array([image[r-1,cc-1], image[r-1,cc]+image[r-1,cc+1], image[r,cc-1]])\n",
    "                #A = np.array([[-1,-1,1], [0,-1,1], [1,-1,1], [-1,0,1]])\n",
    "                A = np.array([[-1,-1,1], [1,-2,2], [-1,0,1]])\n",
    "            else:\n",
    "                v = np.array([image[r-1,cc-1]+image[r-1,cc], image[r-1,cc+1], image[r,cc-1]])\n",
    "                #A = np.array([[-1,-1,1], [0,-1,1], [1,-1,1], [-1,0,1]])\n",
    "                A = np.array([[-1,-2,2], [1,-1,1], [-1,0,1]])\n",
    "                \n",
    "            x = la.solve(A,v)\n",
    "            x_s.append(x)\n",
    "            c = x[2]\n",
    "            predict[r,cc] = c\n",
    "            diff[r,cc] = (np.max(surrounding)-np.min(surrounding))\n",
    "            \n",
    "            #predict[r,c] = np.mean(surrounding)       # take the mean of the previous 4 pixels\n",
    "\n",
    "\n",
    "    \"\"\"predict = np.ravel(predict)\n",
    "    diff = np.ravel(diff)\n",
    "    n = len(predict)\n",
    "    fig = plt.figure()\n",
    "\n",
    "    ax1 = fig.add_subplot(111, projection='3d')\n",
    "    z3 = np.zeros(n)\n",
    "    \n",
    "    dx = np.ones(n)\n",
    "    dy = np.ones(n)\n",
    "    dz = np.arange(n)\n",
    "    \n",
    "    ax1.bar3d(predict, diff, z3, dx, dy, dz, color=\"red\")\n",
    "    ax1.axis('off')\n",
    "    plt.show()\"\"\"\n",
    "    return image, predict, diff, x_s\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6cdea201",
   "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, x_s = plot_hist(num_images, i, \"first\")\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": 8,
   "id": "a2b4212b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average Error First and Second Added: 20.74347343444824\n",
      "Standard Deviaiton of Mean Errors: 0.13532270001617094\n",
      "Average Difference: 53.3018756866455\n",
      "Average Time per Image for First: 10.643209546804428\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)}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5b6d25f7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 1.,\n",
       "        2., 0., 1.]),\n",
       " array([19.81767883, 19.84657283, 19.87546682, 19.90436081, 19.9332548 ,\n",
       "        19.96214879, 19.99104279, 20.01993678, 20.04883077, 20.07772476,\n",
       "        20.10661875, 20.13551275, 20.16440674, 20.19330073, 20.22219472,\n",
       "        20.25108871, 20.27998271, 20.3088767 , 20.33777069, 20.36666468,\n",
       "        20.39555868]),\n",
       " <BarContainer object of 20 artists>)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 6684 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.hist(error_mean, bins=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "59fd96bd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "19.817678833007815\n",
      "52.82225646972656\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 58732 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "i = 0\n",
    "print(np.mean(np.ravel(error)))\n",
    "print(np.mean(np.ravel(difference)))\n",
    "z = np.array(list(zip(np.ravel(error), np.ravel(difference))))\n",
    "random = np.random.randint(640,len(z), size=1000)\n",
    "samples = z[random]\n",
    "plt.scatter(z[:,0], z[:,1], alpha=.2)\n",
    "plt.xlabel(\"Error\")\n",
    "plt.ylabel(\"Surrounding Differences\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "0d486682",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 50824 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist, xedges, yedges = np.histogram2d(samples[:,0], samples[:,1], bins=250, range=[[0, 800], [0, 50]])\n",
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(projection='3d')\n",
    "# Construct arrays for the anchor positions of the 16 bars.\n",
    "xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing=\"ij\")\n",
    "xpos = xpos.ravel()\n",
    "ypos = ypos.ravel()\n",
    "zpos = 0\n",
    "\n",
    "# Construct arrays with the dimensions for the 16 bars.\n",
    "dx = dy = 0.5 * np.ones_like(zpos)\n",
    "dz = hist.ravel()\n",
    "\n",
    "ax.bar3d(xpos, ypos, zpos, dx, dy, dz)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "d04d6e06",
   "metadata": {},
   "outputs": [],
   "source": [
    "def poly2(x, y):\n",
    "    a, b, c = np.polyfit(x,y,2)\n",
    "    return a, b, c\n",
    "\n",
    "def poly1(x, y):\n",
    "    m, b = np.polyfit(x,y,1)\n",
    "    return m, b\n",
    "\n",
    "def generate_random(image):\n",
    "    # image is the array of pixel values of a given image\n",
    "    row, col = image.shape\n",
    "    ind1, ind2 = np.random.randint(0,row), np.random.randint(0,col)\n",
    "    points = [image[ind1, ind2-1], image[ind1-1, ind2-1], image[ind1-1, ind2], image[ind1-1, ind2+1]]\n",
    "    points = np.array([np.arange(4), points]).T\n",
    "\n",
    "    x, y = points[:,0], points[:,1]\n",
    "    return x, y, ind1, ind2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "5d97d89b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1D Difference: 5.000000000014552\n",
      "2D Difference: 54.99999999997817\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 19624 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "x, y, ind1, ind2 = generate_random(image)\n",
    "\n",
    "m, inter = poly1(x,y)\n",
    "a, b, c = poly2(x,y)\n",
    "\n",
    "lin = np.linspace(0,4,50)\n",
    "\n",
    "plt.plot(x,y,'.')\n",
    "plt.plot(lin, m*lin + inter, label=\"1d\")\n",
    "plt.plot(lin, a*lin**2 + b*lin + c, label=\"2d\")\n",
    "\n",
    "plt.scatter(4, image[ind1, ind2], label=\"Actual\")\n",
    "\n",
    "plt.scatter(4, m*4 + inter, label=\"1D approx\")\n",
    "plt.scatter(4, a*4**2 + b*4 + c, label=\"2D approx\")\n",
    "plt.legend()\n",
    "print(f\"1D Difference: {np.abs(image[ind1, ind2] - (m*4 + inter))}\")\n",
    "print(f\"2D Difference: {np.abs(image[ind1, ind2] - (a*4**2 + b*4 +c))}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "c1c0222e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(512, 640)\n"
     ]
    }
   ],
   "source": [
    "print(image.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "id": "98a4e4e5",
   "metadata": {},
   "outputs": [
    {
     "ename": "IndexError",
     "evalue": "index 640 is out of bounds for axis 1 with size 640",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mIndexError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_2432/4036596452.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     13\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"1D Avg: {np.mean(one_d)}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     14\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"2D Avg: {np.mean(two_d)}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 15\u001b[1;33m \u001b[0mavg\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimage\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_2432/4036596452.py\u001b[0m in \u001b[0;36mavg\u001b[1;34m(image)\u001b[0m\n\u001b[0;32m      3\u001b[0m     \u001b[0mtwo_d\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m     \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1000\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m         \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mgenerate_random\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimage\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      6\u001b[0m         \u001b[0mm\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0minter\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpoly1\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m         \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mc\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpoly2\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_2432/1166824526.py\u001b[0m in \u001b[0;36mgenerate_random\u001b[1;34m(image)\u001b[0m\n\u001b[0;32m     11\u001b[0m     \u001b[0mrow\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcol\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mimage\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     12\u001b[0m     \u001b[0mind1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mrow\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mcol\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m     \u001b[0mpoints\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[0mimage\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mind1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mimage\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mind1\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mimage\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mind1\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mimage\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mind1\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mind2\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     14\u001b[0m     \u001b[0mpoints\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0marray\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0marange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mpoints\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mT\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     15\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mIndexError\u001b[0m: index 640 is out of bounds for axis 1 with size 640"
     ]
    }
   ],
   "source": [
    "def avg(image):\n",
    "    one_d = []\n",
    "    two_d = []\n",
    "    for i in range(1000):\n",
    "        x, y, ind1, ind2 = generate_random(image)\n",
    "        m, inter = poly1(x, y)\n",
    "        a, b, c = poly2(x, y)\n",
    "        one_diff = np.abs(image[ind1, ind2] - m*4 + inter)\n",
    "        two_diff = np.abs(image[ind1, ind2] - a*4**2 + b*4 + c)\n",
    "        one_d.append(one_diff)\n",
    "        two_d.append(two_diff)\n",
    "\n",
    "    print(f\"1D Avg: {np.mean(one_d)}\")\n",
    "    print(f\"2D Avg: {np.mean(two_d)}\")\n",
    "avg(image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "8248910a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "-53873.666\n",
      "22654\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\calle\\AppData\\Local\\Temp/ipykernel_2432/1182217676.py:7: RuntimeWarning: overflow encountered in ushort_scalars\n",
      "  vec = np.array([-p1+p3-p4, -p1-p2-p3, -p1-p2-p3-p4])\n"
     ]
    }
   ],
   "source": [
    "x_test, y_test, ind1_test, ind2_test = generate_random(image)\n",
    "p1 = image[ind1_test-1, ind2_test-1]\n",
    "p2 = image[ind1_test-1, ind2_test]\n",
    "p3 = image[ind1_test-1, ind2_test+1]\n",
    "p4 = image[ind1_test, ind2_test-1]\n",
    "\n",
    "vec = np.array([-p1+p3-p4, -p1-p2-p3, -p1-p2-p3-p4])\n",
    "mat = np.array([[3, 0, -1], [0, 3, -3], [1,3,-4]])\n",
    "print(np.allclose(np.dot(mat, la.solve(mat,vec)), vec))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "43f46b48",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22605.0\n",
      "22631\n"
     ]
    }
   ],
   "source": [
    "A = np.array([[-1,-1,1], [0,-1,1], [0,-1,2]])\n",
    "b = np.array([p1,p2,p3+p4])\n",
    "print(la.solve(A,b)[2])\n",
    "print(image[ind1_test, ind2_test])\n"
   ]
  }
 ],
 "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
}
