Loading .ipynb_checkpoints/Encoding_decoding-checkpoint.ipynb 0 → 100644 +318 −0 Original line number Diff line number Diff line %% Cell type:code id:14f74f21 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:c16af61f 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:aceba613 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:6b965751 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:code id:b7561883 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) bins = [25,40,70] # return the huffman dictionary return encode1, encode2, encode3, encode4, encode5, np.ravel(image), error, new_error, diff, boundary, bins scenes = file_extractor() images = image_extractor(scenes) encode1, encode2, encode3, encode4, encode5, image, error, new_error, diff, boundary, bins = huffman(images[0]) ``` %% Cell type:code id:2eb774d2 tags: ``` python def encoder(error, list_dic, diff, bound, bins): encoded = np.copy(error).astype(int).astype(str).astype(object) diff = np.reshape(diff,(510,638)) for i in range(encoded.shape[0]): for j in range(encoded.shape[1]): if i == 0 or i == encoded.shape[0]-1 or j == 0 or j == encoded.shape[1]-1: encoded[i][j] = list_dic[0][encoded[i][j]] elif diff[i-1][j-1] <= bins[0]: encoded[i][j] = list_dic[1][encoded[i][j]] elif diff[i-1][j-1] <= bins[1] and diff[i-1][j-1] > bins[0]: encoded[i][j] = list_dic[2][encoded[i][j]] elif diff[i-1][j-1] <= bins[2] and diff[i-1][j-1] > bins[1]: encoded[i][j] = list_dic[3][encoded[i][j]] else: encoded[i][j] = list_dic[4][encoded[i][j]] return encoded ``` %% Cell type:code id:8eeb40d0 tags: ``` python def decoder(A, encoded_matrix, encoding_dict): """ Function that accecpts the prediction matrix A for the linear system, the encoded matrix of error values, and the encoding dicitonary. """ the_keys = list(encode_dict.keys()) the_values = list(encode_dict.values()) error_matrix = encoded_matrix.copy() for i in range(error_matrix.shape[0]): for j in range(error_matrix.shape[1]): if i == 0 and j == 0: error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) elif i == 0 or i == error_matrix.shape[0]-1 or j == 0 or j == error_matrix.shape[1]-1: error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) + error_matrix[0][0] else: """z0, z1, z2, z3 = error_matrix[i-1][j-1], error_matrix[i-1][j], \ error_matrix[i-1][j+1], error_matrix[i][j-1] y = np.vstack((-z0+z2-z3, z0+z1+z2, -z0-z1-z2-z3))""" error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) return error_matrix.astype(int) ``` %% Cell type:code id:3e0e9742 tags: ``` python encode1, encode2, encode3, encode4, encode5, image, error, new_error, diff, bound, bins = huffman(images[0]) encoded_matrix = encoder(np.reshape(new_error,(512,640)), [encode1, encode2, encode3, encode4, encode5], diff, bound, bins) ``` %% Cell type:code id:e6ea4f99 tags: ``` python print(encoded_matrix) ``` %% Output [['01100010001' '11000110' '100101010' ... '101110011' '00010100' '1111000100'] ['10011100' '100001' '111000' ... '10111011' '00111' '1111001101'] ['10101111' '100100' '100000' ... '111100' '111000' '00010100'] ... ['110001000' '100001' '111011' ... '1010010' '100000' '10011000'] ['0100011101' '111010' '00110' ... '1000101' '1100100' '10011010'] ['00100010' '110111101' '110110100' ... '00010010' '10100000' '110110101']] %% Cell type:code id:0c07a23e tags: ``` python ``` Loading
.ipynb_checkpoints/Encoding_decoding-checkpoint.ipynb 0 → 100644 +318 −0 Original line number Diff line number Diff line %% Cell type:code id:14f74f21 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:c16af61f 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:aceba613 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:6b965751 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:code id:b7561883 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) bins = [25,40,70] # return the huffman dictionary return encode1, encode2, encode3, encode4, encode5, np.ravel(image), error, new_error, diff, boundary, bins scenes = file_extractor() images = image_extractor(scenes) encode1, encode2, encode3, encode4, encode5, image, error, new_error, diff, boundary, bins = huffman(images[0]) ``` %% Cell type:code id:2eb774d2 tags: ``` python def encoder(error, list_dic, diff, bound, bins): encoded = np.copy(error).astype(int).astype(str).astype(object) diff = np.reshape(diff,(510,638)) for i in range(encoded.shape[0]): for j in range(encoded.shape[1]): if i == 0 or i == encoded.shape[0]-1 or j == 0 or j == encoded.shape[1]-1: encoded[i][j] = list_dic[0][encoded[i][j]] elif diff[i-1][j-1] <= bins[0]: encoded[i][j] = list_dic[1][encoded[i][j]] elif diff[i-1][j-1] <= bins[1] and diff[i-1][j-1] > bins[0]: encoded[i][j] = list_dic[2][encoded[i][j]] elif diff[i-1][j-1] <= bins[2] and diff[i-1][j-1] > bins[1]: encoded[i][j] = list_dic[3][encoded[i][j]] else: encoded[i][j] = list_dic[4][encoded[i][j]] return encoded ``` %% Cell type:code id:8eeb40d0 tags: ``` python def decoder(A, encoded_matrix, encoding_dict): """ Function that accecpts the prediction matrix A for the linear system, the encoded matrix of error values, and the encoding dicitonary. """ the_keys = list(encode_dict.keys()) the_values = list(encode_dict.values()) error_matrix = encoded_matrix.copy() for i in range(error_matrix.shape[0]): for j in range(error_matrix.shape[1]): if i == 0 and j == 0: error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) elif i == 0 or i == error_matrix.shape[0]-1 or j == 0 or j == error_matrix.shape[1]-1: error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) + error_matrix[0][0] else: """z0, z1, z2, z3 = error_matrix[i-1][j-1], error_matrix[i-1][j], \ error_matrix[i-1][j+1], error_matrix[i][j-1] y = np.vstack((-z0+z2-z3, z0+z1+z2, -z0-z1-z2-z3))""" error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) return error_matrix.astype(int) ``` %% Cell type:code id:3e0e9742 tags: ``` python encode1, encode2, encode3, encode4, encode5, image, error, new_error, diff, bound, bins = huffman(images[0]) encoded_matrix = encoder(np.reshape(new_error,(512,640)), [encode1, encode2, encode3, encode4, encode5], diff, bound, bins) ``` %% Cell type:code id:e6ea4f99 tags: ``` python print(encoded_matrix) ``` %% Output [['01100010001' '11000110' '100101010' ... '101110011' '00010100' '1111000100'] ['10011100' '100001' '111000' ... '10111011' '00111' '1111001101'] ['10101111' '100100' '100000' ... '111100' '111000' '00010100'] ... ['110001000' '100001' '111011' ... '1010010' '100000' '10011000'] ['0100011101' '111010' '00110' ... '1000101' '1100100' '10011010'] ['00100010' '110111101' '110110100' ... '00010010' '10100000' '110110101']] %% Cell type:code id:0c07a23e tags: ``` python ```