Commit 9fd6d565 authored by Kelly Chang's avatar Kelly Chang
Browse files

add

parents 5c7cf95e 2350ec98
Loading
Loading
Loading
Loading
+282 −0
Original line number Original line Diff line number Diff line
%% Cell type:code id:dbef8759 tags:

``` python
import numpy as np
from matplotlib import pyplot as plt
from itertools import product
import os
import sys
from PIL import Image
from scipy.optimize import minimize
from time import time
from numpy import linalg as la
```

%% Cell type:code id:b7a550e0 tags:

``` python
def file_extractor(dirname="images"):
    files = os.listdir(dirname)
    scenes = []
    for file in files:
        scenes.append(os.path.join(dirname, file))
    return scenes

def image_extractor(scenes):
    image_folder = []
    for scene in scenes:
        files = os.listdir(scene)
        for file in files:
            image_folder.append(os.path.join(scene, file))
    images = []
    for folder in image_folder:
        ims = os.listdir(folder)
        for im in ims:
            if im[-4:] == ".jp4" or im[-7:] == "_6.tiff":
                continue
            else:
                images.append(os.path.join(folder, im))
    return images #returns a list of file paths to .tiff files in the specified directory given in file_extractor

def im_distribution(images, num):
    """
    Function that extracts tiff files from specific cameras and returns a list of all
    the tiff files corresponding to that camera. i.e. all pictures labeled "_7.tiff" or otherwise
    specified camera numbers.

    Parameters:
        images (list): list of all tiff files, regardless of classification. This is NOT a list of directories but
        of specific tiff files that can be opened right away. This is the list that we iterate through and
        divide.

        num (str): a string designation for the camera number that we want to extract i.e. "14" for double digits
        of "_1" for single digits.

    Returns:
        tiff (list): A list of tiff files that have the specified designation from num. They are the files extracted
        from the 'images' list that correspond to the given num.
    """
    tiff = []
    for im in images:
        if im[-7:-5] == num:
            tiff.append(im)
    return tiff
```

%% Cell type:code id:9ed20f84 tags:

``` python
def plot_hist(tiff_list, i):
    """
    This function is the leftovers from the first attempt to plot histograms.
    As it stands it needs some work in order to function again. We will
    fix this later. 1/25/22
    """


    image = tiff_list[i]
    image = Image.open(image)    #Open the image and read it as an Image object
    image = np.array(image)[1:,:]    #Convert to an array, leaving out the first row because the first row is just housekeeping data
    image = image.astype(int)
    row, col = image.shape
    """predict = np.empty([row,col])     # create a empty matrix to update prediction
    predict[0,:] = np.copy(image[0,:])       # keep the first row from the image
    predict[:,0] = np.copy(image[:,0])      # keep the first columen from the image
    predict[-1,:] = np.copy(image[-1,:])       # keep the first row from the image
    predict[:,-1] = np.copy(image[:,-1])      # keep the first columen from the image
    diff = np.empty([row,col])
    diff[0,:] = np.zeros(col)       # keep the first row from the image
    diff[:,0] = np.zeros(row)
    diff[-1,:] = np.zeros(col)       # keep the first row from the image
    diff[:,-1] = np.zeros(row)"""
    A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]])
    z0 = image[0:-2,0:-2]
    z1 = image[0:-2,1:-1]
    z2 = image[0:-2,2::]
    z3 = image[1:-1,0:-2]
    y0 = np.ravel(-z0+z2-z3)
    y1 = np.ravel(z0+z1+z2)
    y2 = np.ravel(-z0-z1-z2-z3)
    y = np.vstack((y0,y1,y2))
    predict = la.solve(A,y)[-1]
    #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)]
    '''
    for r in range(1,row-1):                  # loop through the rth row
        for c in range(1,col-1):              # loop through the cth column
            actual_surrounding = np.array([image[r-1,c-1], image[r-1,c], image[r-1,c+1], image[r,c-1]])
            #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])])
            z = np.array([image[r-1,c-1], image[r-1,c], image[r-1,c+1], image[r,c-1]])
            y = np.array([-z[0]+z[2]-z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])
            predict[r,c] = np.linalg.solve(A,y)[-1]
            diff[r,c] = (np.max(actual_surrounding)-np.min(actual_surrounding))
    predict = np.ravel(predict[1:-1,1:-1])
    diff = np.ravel(diff[1:-1,1:-1])'''
    image = np.ravel(image[1:-1,1:-1])
    return image, predict#, diff
```

%% Cell type:code id:8e3ef654 tags:

``` python
scenes = file_extractor()
images = image_extractor(scenes)
num_images = im_distribution(images, "_9")
error_mean = []
error_mean1 = []
diff_mean = []
times = []
times1 = []
all_error = []
for i in range(len(num_images)):
    """start1 = time()
    image_1, predict_1, difference_1, x_s_1 = plot_hist(num_images, i, "second")
    stop1 = time()
    times1.append(stop1-start1)
    error1 = np.abs(image_1-predict_1)
    error_mean1.append(np.mean(np.ravel(error1)))"""
    start = time()
    image, predict = plot_hist(num_images, i)
    stop = time()
    times.append(stop-start)
    error = np.abs(image-predict)
    all_error.append(np.ravel(error))
    error_mean.append(np.mean(np.ravel(error)))
    #diff_mean.append(np.mean(np.ravel(difference)))

#image, predict, difference = plot_hist(images, 0)
```

%% Cell type:code id:fa65dcd6 tags:

``` python
print(f"Average Error First and Second Added: {np.mean(error_mean)}")
print(np.std(image))
print(f"Standard Deviaiton of Mean Errors: {np.sqrt(np.var(error_mean))}")
#print(f"Average Difference: {np.mean(diff_mean)}")
print(f"Average Time per Image for First: {np.mean(times)}")
```

%% Output

    Average Error First and Second Added: 20.017164930235474
    233.22663391021266
    Standard Deviaiton of Mean Errors: 0.16101183692475135
    Average Time per Image for First: 0.023412495851516724

%% Cell type:code id:f592fa32 tags:

``` python
b = np.arange(9).reshape((3,3))
print(b)
print(b[1,1::])
print(b[1,1:])
```

%% Output

    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    [4 5]
    [4 5]

%% Cell type:code id:dda442ae tags:

``` python
fig = plt.figure(figsize = (10,10))
ax = fig.add_subplot()
x = np.abs(predict-image)
y = difference
plt.plot(x,y,'o',alpha = 0.2)
plt.rcParams.update({'font.size': 20})
plt.xlabel("differnece to the true value" )
plt.ylabel("differnece of min and max of true value of the surroundings")
plt.show()
```

%% Output

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    ~\AppData\Local\Temp/ipykernel_10808/722042198.py in <module>
          2 ax = fig.add_subplot()
          3 x = np.abs(predict-image)
    ----> 4 y = difference
          5 plt.plot(x,y,'o',alpha = 0.2)
          6 plt.rcParams.update({'font.size': 20})
    NameError: name 'difference' is not defined


%% Cell type:code id:58da6063 tags:

``` python
image = Image.open(images[0])    #Open the image and read it as an Image object
image = np.array(image)[1:,:]
#z = np.array([image[1-1,1-1], image[1-1,1], image[1-1,1+1], image[1,1-1]])
z = np.array([22554,22552,22519,22561])
print(z)
'''A = np.array([[-3,0,1],[0,-3,3],[-1,-3,4]])
y = np.array([z[0]-z[2]+z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])
a,b,c = np.linalg.solve(A,y)'''
A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]])
y = np.array([-z[0]+z[2]-z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])
print(y)
a,b,c = np.linalg.solve(A,y)
print(a,b,c)
```

%% Cell type:code id:2562feeb tags:

``` python
i0 = (a*(-1) + b*(1) + c)
i1 = (a*(0) + b*(1) + c)
i2 = (a*(1) + b*(1) + c)
i3 = (a*(-1) + b*(0) + c)
print(sum([(i0-z[0])**2,(i1-z[1])**2,(i2-z[2])**2,(i3-z[3])**2]))
```

%% Cell type:code id:470cc137 tags:

``` python
a = 0
b = 2
c = 2
i0 = (a*(-1) + b*(1) + c)
i1 = (a*(0) + b*(1) + c)
i2 = (a*(1) + b*(1) + c)
i3 = (a*(-1) + b*(0) + c)
print(sum([(i0-z[0])**2,(i1-z[1])**2,(i2-z[2])**2,(i3-z[3])**2]))
```

%% Cell type:code id:3292b395 tags:

``` python
#z = np.hstack((image[0,:3], image[1,0]))
#x = np.array([-1,0,1,-1])
#y = np.array([-1,-1,-1,0])
A = np.array([[-3,0,1],[0,-3,3],[1,3,-4]])
#y = np.array([z[0]-z[2]+z[3], z[0]+z[1]+z[2], -z[0]-z[1]-z[2]-z[3]])
y = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(np.linalg.solve(A,y))
```

%% Cell type:code id:f9687830 tags:

``` python
0.5**2 + 1.5**2
```

%% Cell type:code id:e98eed4b tags:

``` python
y1= [0,1,2,3]
y2=[4,5,6,7]
y3=[8,9,10,11]
np.vstack((y1,y2,y3)).T
```

%% Cell type:code id:b7e88aab tags:

``` python
```
+8 −0
Original line number Original line Diff line number Diff line
@@ -152,7 +152,15 @@
  },
  },
  {
  {
   "cell_type": "code",
   "cell_type": "code",
<<<<<<< HEAD:.ipynb_checkpoints/prediction_MSE_kelly-checkpoint.ipynb
   "execution_count": 52,
   "execution_count": 52,
=======
<<<<<<< HEAD
   "execution_count": 31,
=======
   "execution_count": 43,
>>>>>>> e4df997c1a14994e77600c8c4e3e1a2ec84ff59e
>>>>>>> 2350ec9881b7954dc94449b36af098af82acbb95:.ipynb_checkpoints/prediction_MSE-checkpoint.ipynb
   "id": "fa65dcd6",
   "id": "fa65dcd6",
   "metadata": {},
   "metadata": {},
   "outputs": [
   "outputs": [
+383 −0

File added.

Preview size limit exceeded, changes collapsed.

+0 −0
Original line number Original line Diff line number Diff line