Commit b428fbbd authored by Nathaniel Callens's avatar Nathaniel Callens
Browse files

basic fixes

parents 093ce109 829e9198
Loading
Loading
Loading
Loading
(8 KiB)

File changed.

No diff preview for this file type.

+548 −459

File changed.

Preview size limit exceeded, changes collapsed.

+567 −273

File changed.

Preview size limit exceeded, changes collapsed.

+25 −32
Original line number Diff line number Diff line
%% Cell type:code id:8868bc30 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,linprog
import time
import seaborn as sns
from sklearn.neighbors import KernelDensity
import pandas as pd
from collections import Counter
import time
```

%% Cell type:code id:76317b02 tags:

``` python
def file_extractor(dirname="images"):
    files = os.listdir(dirname)
    scenes = []
    for file in files:
        if file == '.DS_Store':
            continue
        else:
            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 image_extractor(scenes):
    image_folder = []
    for scene in scenes:
        files = os.listdir(scene)
        for file in files:
            #if file[-4:] == ".jp4" or file[-7:] == "_6.tiff":
            if file[-5:] != ".tiff" or file[-7:] == "_6.tiff":
                print(file)
                continue
            else:
                image_folder.append(os.path.join(scene, file))
    return image_folder

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:be1ff8a1 tags:

``` python
def plot_hist(tiff_list):
    """
    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
    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)
    A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]]) # the matrix for system of equation
    z0 = image[0:-2,0:-2]   # get all the first pixel for the entire image
    z1 = image[0:-2,1:-1]   # get all the second pixel for the entire image
    z2 = image[0:-2,2::]    # get all the third pixel for the entire image
    z3 = image[1:-1,0:-2]   # get all the forth pixel for the entire image
    # calculate the out put of the system of equation
    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))
    # use numpy solver to solve the system of equations all at once
    predict = np.floor(np.linalg.solve(A,y)[-1])
    # flatten the neighbor pixlels and stack them together
    z0 = np.ravel(z0)
    z1 = np.ravel(z1)
    z2 = np.ravel(z2)
    z3 = np.ravel(z3)
    neighbor = np.vstack((z0,z1,z2,z3)).T
    # calculate the difference
    diff = np.max(neighbor,axis = 1) - np.min(neighbor, axis=1)

    # flatten the image to a vector
    image = np.ravel(image[1:-1,1:-1])
    error = image-predict

    return image, predict, diff, error, A
```

%% Cell type:code id:8483903e tags:

``` python
class NodeTree(object):
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right

    def children(self):
        return self.left, self.right

    def __str__(self):
        return self.left, self.right


def huffman_code_tree(node, binString=''):
    '''
    Function to find Huffman Code
    '''
    if type(node) is str:
        return {node: binString}
    (l, r) = node.children()
    d = dict()
    d.update(huffman_code_tree(l, binString + '0'))
    d.update(huffman_code_tree(r, binString + '1'))
    return d


def make_tree(nodes):
    '''
    Function to make tree
    :param nodes: Nodes
    :return: Root of the tree
    '''
    while len(nodes) > 1:
        (key1, c1) = nodes[-1]
        (key2, c2) = nodes[-2]
        nodes = nodes[:-2]
        node = NodeTree(key1, key2)
        nodes.append((node, c1 + c2))
        nodes = sorted(nodes, key=lambda x: x[1], reverse=True)
    return nodes[0][0]
```

%% Cell type:markdown id:c7104fbf tags:

### Huffman without dividing into bins

%% Cell type:code id:a43f3f1c tags:

``` python

def huffman_nb(image):
    origin, predict, diff, error, A = plot_hist(image)
    image = Image.open(image)
    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)

    new_error = np.copy(image)
    new_error[1:-1,1:-1] = np.reshape(error,(510, 638))
    keep = new_error[0,0]
    new_error[0,:] = new_error[0,:] - keep
    new_error[-1,:] = new_error[-1,:] - keep
    new_error[1:-1,0] = new_error[1:-1,0] - keep
    new_error[1:-1,-1] = new_error[1:-1,-1] - keep
    new_error[0,0] = keep
    new_error = np.ravel(new_error)



    #ab_error = np.abs(new_error)
    #string = [str(i) for i in ab_error]
    string = [str(i) for i in new_error.astype(int)]
    freq = dict(Counter(string))

    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encoding = huffman_code_tree(node)
    #encoded = ["1"+encoding[str(-i)] if i < 0 else "0"+encoding[str(i)] for i in error]

    # return the huffman dictionary
    return encoding, new_error, image.reshape(-1)


def compress_rate_nb(image, error, encoding):
    #original = original.reshape(-1)
    #error = error.reshape(-1)
    original = image.reshape(-1)
    error = error.reshape(-1)
    o_len = 0
    c_len = 0
    for i in range(0, len(original)):
        o_len += len(bin(original[i])[2:])
        c_len += len(encoding[str(int(error[i]))])


    return c_len/o_len

```

%% Cell type:markdown id:eac2f456 tags:

### Huffman with dividing into non-uniform bins

%% Cell type:code id:207b0bd2 tags:

``` python
def huffman(image):
    origin, predict, diff, error, A = plot_hist(image)
    image = Image.open(image)
    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)


    boundary = np.hstack((image[0,:],image[-1,:],image[1:-1,0],image[1:-1,-1]))
    boundary = boundary - image[0,0]
    boundary[0] = image[0,0]

    string = [str(i) for i in boundary]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode1 = huffman_code_tree(node)


    mask = diff <= 25
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode2 = huffman_code_tree(node)


    mask = diff > 25
    new_error = error[mask]
    mask2 = diff[mask] <= 40
    string = [str(i) for i in new_error[mask2].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode3 = huffman_code_tree(node)


    mask = diff > 40
    new_error = error[mask]
    mask2 = diff[mask] <= 70
    string = [str(i) for i in new_error[mask2].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode4 = huffman_code_tree(node)


    mask = diff > 70
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode5 = huffman_code_tree(node)




    new_error = np.copy(image)
    new_error[1:-1,1:-1] = np.reshape(error,(510, 638))
    keep = new_error[0,0]
    new_error[0,:] = new_error[0,:] - keep
    new_error[-1,:] = new_error[-1,:] - keep
    new_error[1:-1,0] = new_error[1:-1,0] - keep
    new_error[1:-1,-1] = new_error[1:-1,-1] - keep
    new_error[0,0] = keep
    new_error = np.ravel(new_error)

    # return the huffman dictionary
    return encode1, encode2, encode3, encode4, encode5, np.ravel(image), error, diff, boundary

def compress_rate(image, error, diff, bound, encode1, encode2, encode3, encode4, encode5):
    #original = original.reshape(-1)
    #error = error.reshape(-1)
    o_len = 0
    c_len = 0
    im = np.reshape(image,(512, 640))
    real_b = np.hstack((im[0,:],im[-1,:],im[1:-1,0],im[1:-1,-1]))
    original = im[1:-1,1:-1].reshape(-1)

    for i in range(0,len(bound)):
        o_len += len(bin(real_b[i])[2:])
        c_len += len(encode1[str(bound[i])])

    for i in range(0, len(original)):
        o_len += len(bin(original[i])[2:])
        if diff[i] <= 25:
            c_len += len(encode2[str(int(error[i]))])

        if diff[i] <= 40 and diff[i] > 25:
            c_len += len(encode3[str(int(error[i]))])

        if diff[i] <= 70 and diff[i] > 40:
            c_len += len(encode4[str(int(error[i]))])

        if diff[i] > 70:
            c_len += len(encode5[str(int(error[i]))])

    return c_len/o_len
scenes = file_extractor()
images = image_extractor(scenes)
encode1, encode2, encode3, encode4, encode5, image, error, diff, boundary = huffman(images[0])
compress_rate(image, error, diff, boundary, encode1, encode2, encode3, encode4, encode5)
```

%% Output

    0.44205322265625

%% Cell type:markdown id:3a3f06a5 tags:

### Huffman with dividing into uniform bins

%% Cell type:code id:14075c94 tags:

``` python
def huffman_u(image):
    origin, predict, diff, error, A = plot_hist(image)
    image = Image.open(image)
    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)

    bins = np.linspace(min(diff),max(diff),5)[1:-1]

    boundary = np.hstack((image[0,:],image[-1,:],image[1:-1,0],image[1:-1,-1]))
    boundary = boundary - image[0,0]
    boundary[0] = image[0,0]

    string = [str(i) for i in boundary]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode1 = huffman_code_tree(node)


    mask = diff <= 100
    mask = diff <= bins[0]
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode2 = huffman_code_tree(node)


    mask = diff > 100
    #new_error = error[mask]
    #mask2 = diff[mask] <= 200
    #string = [str(i) for i in new_error[mask2].astype(int)]
    string = [str(i) for i in error[mask].astype(int)]
    mask = diff > bins[0]
    new_error = error[mask]
    mask2 = diff[mask] <= bins[1]
    string = [str(i) for i in new_error[mask2].astype(int)]
    #string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode3 = huffman_code_tree(node)


    '''mask = diff > 200
    mask = diff > bins[1]
    new_error = error[mask]
    mask2 = diff[mask] <= 300
    mask2 = diff[mask] <= bins[2]
    string = [str(i) for i in new_error[mask2].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode4 = huffman_code_tree(node)


    mask = diff > 300
    mask = diff > bins[2]
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode5 = huffman_code_tree(node)'''
    encode5 = huffman_code_tree(node)





    new_error = np.copy(image)
    new_error[1:-1,1:-1] = np.reshape(error,(510, 638))
    keep = new_error[0,0]
    new_error[0,:] = new_error[0,:] - keep
    new_error[-1,:] = new_error[-1,:] - keep
    new_error[1:-1,0] = new_error[1:-1,0] - keep
    new_error[1:-1,-1] = new_error[1:-1,-1] - keep
    new_error[0,0] = keep
    new_error = np.ravel(new_error)

    # return the huffman dictionary
    #return encode1, encode2, encode3, encode4, encode5, np.ravel(image), error, diff, boundary
    return encode1, encode2, encode3, np.ravel(image), error, diff, boundary
    return [encode1, encode2, encode3, encode4, encode5], np.ravel(image), error, diff, boundary, bins

#def compress_rate_u(image, error, diff, bound, encode1, encode2, encode3, encode4, encode5):
def compress_rate_u(image, error, diff, bound, encode1, encode2, encode3):
def compress_rate_u(image, error, diff, bound, list_dic, bins):
    #original = original.reshape(-1)
    #error = error.reshape(-1)
    o_len = 0
    c_len = 0
    im = np.reshape(image,(512, 640))
    real_b = np.hstack((im[0,:],im[-1,:],im[1:-1,0],im[1:-1,-1]))
    original = im[1:-1,1:-1].reshape(-1)

    for i in range(0,len(bound)):
        o_len += len(bin(real_b[i])[2:])
        c_len += len(encode1[str(bound[i])])
        c_len += len(list_dic[0][str(bound[i])])

    for i in range(0, len(original)):
        o_len += len(bin(original[i])[2:])
        if diff[i] <= 100:
            c_len += len(encode2[str(int(error[i]))])

        if diff[i] > 100:
            c_len += len(encode3[str(int(error[i]))])
        if diff[i] <= bins[0]:
            c_len += len(list_dic[1][str(int(error[i]))])

        '''if diff[i] <= 200 and diff[i] > 100:
            c_len += len(encode3[str(int(error[i]))])'''
        if diff[i] <= bins[1] and diff[i] > bins[0]:
            c_len += len(list_dic[2][str(int(error[i]))])

        '''if diff[i] <= 300 and diff[i] > 200:
            c_len += len(encode4[str(int(error[i]))])
        if diff[i] <= bins[2] and diff[i] > bins[1]:
            c_len += len(list_dic[3][str(int(error[i]))])

        if diff[i] > 300:
            c_len += len(encode5[str(int(error[i]))])'''
        if diff[i] > bins[2]:
            c_len += len(list_dic[4][str(int(error[i]))])

    return c_len/o_len
scenes = file_extractor()
images = image_extractor(scenes)
encode1, encode2, encode3, image, error, diff, boundary = huffman_u(images[0])
compress_rate_u(image, error, diff, boundary, encode1, encode2, encode3)
```

%% Output

    0.4432273356119792

%% Cell type:code id:f8b93cc5 tags:

``` python
```

%% Cell type:code id:6abed5da tags:

``` python
scenes = file_extractor()
images = image_extractor(scenes)
num_images = im_distribution(images, "_9")
rate = []
rate_nb = []
rate_u = []
for i in range(len(num_images)):
    encode1, encode2, encode3, encode4, encode5, image, error, diff, bound = huffman(num_images[i])
    r = compress_rate(image, error, diff, bound, encode1, encode2, encode3, encode4, encode5)
    rate.append(r)
    encoding, error, image = huffman_nb(num_images[i])
    r = compress_rate_nb(image, error, encoding)
    rate_nb.append(r)
    encode1, encode2, encode3, image, error, diff, bound = huffman_u(num_images[i])
    r = compress_rate_u(image, error, diff, bound, encode1, encode2, encode3)
    rate_u.append(r)

print(f"Compression rate of huffman with different bins: {np.mean(rate)}")
print(f"Compression rate of huffman without bins: {np.mean(rate_nb)}")
print(f"Compression rate of huffman with uniform bins: {np.mean(rate_u)}")
```

%% Output

    Compression rate of huffman with different bins: 0.44946919759114584
    Compression rate of huffman without bins: 0.4513634314749933
    Compression rate of huffman with uniform bins: 0.44956921895345053

%% Cell type:code id:15eecad3 tags:

``` python
def huffman(image):
    origin, predict, diff, error, A = plot_hist(image)
    image = Image.open(image)
    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)

    boundary = np.hstack((image[0,:],image[-1,:],image[1:-1,0],image[1:-1,-1]))
    boundary = boundary - image[0,0]
    boundary[0] = image[0,0]

    string = [str(i) for i in boundary]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode1 = huffman_code_tree(node)


    mask = diff <= 10
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode2 = huffman_code_tree(node)


    mask = diff > 10
    new_error = error[mask]
    mask2 = diff[mask] <= 25
    string = [str(i) for i in new_error[mask2].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode3 = huffman_code_tree(node)


    mask = diff > 25
    new_error = error[mask]
    mask2 = diff[mask] <= 45
    string = [str(i) for i in new_error[mask2].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode4 = huffman_code_tree(node)


    mask = diff > 45
    string = [str(i) for i in error[mask].astype(int)]
    freq = dict(Counter(string))
    freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    node = make_tree(freq)
    encode5 = huffman_code_tree(node)




    new_error = np.copy(image)
    new_error[1:-1,1:-1] = np.reshape(error,(510, 638))
    keep = new_error[0,0]
    new_error[0,:] = new_error[0,:] - keep
    new_error[-1,:] = new_error[-1,:] - keep
    new_error[1:-1,0] = new_error[1:-1,0] - keep
    new_error[1:-1,-1] = new_error[1:-1,-1] - keep
    new_error[0,0] = keep
    new_error = np.ravel(new_error)

    # return the huffman dictionary
    return encode1, encode2, encode3, encode4, encode5, np.ravel(image), error, diff, boundary

def compress_rate(image, error, diff, bound, encode1, encode2, encode3, encode4, encode5):
    #original = original.reshape(-1)
    #error = error.reshape(-1)
    o_len = 0
    c_len = 0
    im = np.reshape(image,(512, 640))
    real_b = np.hstack((im[0,:],im[-1,:],im[1:-1,0],im[1:-1,-1]))
    original = im[1:-1,1:-1].reshape(-1)

    for i in range(0,len(bound)):
        o_len += len(bin(real_b[i])[2:])
        c_len += len(encode1[str(bound[i])])

    for i in range(0, len(original)):
        o_len += len(bin(original[i])[2:])
        if diff[i] <= 10:
            c_len += len(encode2[str(int(error[i]))])

        if diff[i] <= 25 and diff[i] > 10:
            c_len += len(encode3[str(int(error[i]))])

        if diff[i] <= 45 and diff[i] > 25:
            c_len += len(encode4[str(int(error[i]))])

        if diff[i] > 45:
            c_len += len(encode5[str(int(error[i]))])

    return c_len/o_len
scenes = file_extractor()
images = image_extractor(scenes)
encode1, encode2, encode3, encode4, encode5, image, error, diff, boundary = huffman(images[0])
compress_rate(image, error, diff, boundary, encode1, encode2, encode3, encode4, encode5)
```

%% Output

    0.4427516682942708

%% Cell type:code id:f8a8c717 tags:

``` python
scenes = file_extractor()
images = image_extractor(scenes)
num_images = im_distribution(images, "_9")
rate = []

for i in range(len(num_images)):
    encode1, encode2, encode3, encode4, encode5, image, error, diff, bound = huffman(num_images[i])
    r = compress_rate(image, error, diff, bound, encode1, encode2, encode3, encode4, encode5)
    rate.append(r)


print(f"Compression rate of huffman with different bins: {np.mean(rate)}")
```

%% Output

    Compression rate of huffman with different bins: 0.4488415273030599

%% Cell type:code id:992dd8bb tags:

``` python
origin, predict, diff, error, A = plot_hist(images[0])
```

%% Cell type:code id:904ba7b1 tags:

``` python
plt.hist(error,bins=50)
plt.show()
mask = diff <= 20
plt.hist(error[mask],bins=50)
plt.show()

mask = diff > 20
new_error = error[mask]
mask2 = diff[mask] <= 35
plt.hist(new_error[mask2],bins=50)
plt.show()

mask = diff > 35
new_error = error[mask]
mask2 = diff[mask] <= 50
plt.hist(new_error[mask2],bins=50)
plt.show()

mask = diff > 50
#new_error = error[mask]
#mask2 = diff[mask] <= 400
plt.hist(error[mask],bins=50)
plt.show()
```

%% Output






%% Cell type:code id:2f5ef010 tags:

``` python
image = Image.open(images[0])
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)
boundary = np.hstack((image[0,:],image[-1,:],image[1:-1,0],image[1:-1,-1]))
boundary = boundary - image[0,0]
boundary[0] = image[0,0]
print(image.shape)
```

%% Output

    (512, 640)

%% Cell type:code id:4860903b tags:

``` python
print(boundary)
```

%% Output

    [22554    -2   -35 ...   -16    40    19]

%% Cell type:code id:f145c221 tags:

``` python
```
+114 −290

File changed.

Preview size limit exceeded, changes collapsed.

Loading