Loading .DS_Storedeleted 100644 → 0 −8 KiB File deleted. View file .ipynb_checkpoints/Error_to_Image-checkpoint.ipynb +28 −1 Original line number Diff line number Diff line %% Cell type:code id:dbef8759 tags: ``` python import numpy as np from prediction_MSE_Scout import file_extractor, image_extractor, im_distribution 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 from scipy.stats import gaussian_kde import seaborn as sns import pywt #import pywt from collections import Counter ``` %% Output --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) /var/folders/z2/plvrsqjs023g1cmx7k19mhzr0000gn/T/ipykernel_21377/741789573.py in <module> 1 import numpy as np ----> 2 from prediction_MSE_Scout import file_extractor, image_extractor, im_distribution 3 from matplotlib import pyplot as plt 4 from itertools import product 5 import os ~/Documents/Elphel/image-compression/prediction_MSE_Scout.py in <module> 16 from scipy.stats import gaussian_kde, entropy 17 import seaborn as sns ---> 18 import pywt 19 import math 20 #import cv2 ModuleNotFoundError: No module named 'pywt' %% Cell type:code id:9ed20f84 tags: ``` python def plot_hist(tiff_list, i=0): """ 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_int = image.astype(int) A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]]) # the matrix for system of equation z0 = image_int[0:-2,0:-2] # get all the first pixel for the entire image z1 = image_int[0:-2,1:-1] # get all the second pixel for the entire image z2 = image_int[0:-2,2::] # get all the third pixel for the entire image z3 = image_int[1:-1,0:-2] # get all the fourth 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.linalg.solve(A,y)[-1] predict = np.floor(np.linalg.solve(A,y)[-1]).astype(int) #predict = [] # flatten the neighbor pixels 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) diff = np.pad(diff.reshape(510,638), pad_width=1) # flatten the image to a vector small_image = image_int[1:-1,1:-1] #Reshape the predictions to be a 2D array predict = np.pad(predict.reshape(510,638), pad_width=1) """predict[0,:] = image[0,:] predict[:,0] = image[:,0] predict[:,-1] = image[:,-1] predict[-1,:] = image[-1,:]""" #Calculate the error between the original image and our predictions #Note that we only predicted on the inside square of the original image, excluding #The first row, column and last row, column #error = (image_int - predict).astype(int) #Experiment #this one works error = image_int - predict return predict, diff, image_int, error, A ``` %% Cell type:code id:ba2881d9 tags: ``` python scenes = file_extractor() images = image_extractor(scenes) num_images = im_distribution(images, "11") ``` %% Cell type:code id:11e95c34 tags: ``` python predict, diff, im, err, A = plot_hist(images, 2) ``` %% Output --------------------------------------------------------------------------- NameError Traceback (most recent call last) /var/folders/z2/plvrsqjs023g1cmx7k19mhzr0000gn/T/ipykernel_21377/1723356297.py in <module> ----> 1 predict, diff, im, err, A = plot_hist(images, 2) NameError: name 'plot_hist' is not defined %% Cell type:code id:434e4d2f tags: ``` python def reconstruct(error, A): """ Function that reconstructs the original image from the error matrix and using the predictive algorithm developed in the encoding. Parameters: error (array): matrix of errors computed in encoding. Same shape as the original image (512, 640) in this case A (array): Matrix used for the system of equations to create predictions Returns: cd cdcd image (array): The reconstructed image """ new_e = error.copy() rows, columns = new_e.shape for r in range(1, rows-1): for c in range(1, columns-1): z0, z1, z2, z3 = new_e[r-1][c-1], new_e[r-1][c], new_e[r-1][c+1], new_e[r][c-1] y = np.vstack((-z0+z2-z3, z0+z1+z2, -z0-z1-z2-z3)) if r == 1 and c == 1: print(np.linalg.solve(A,y)[-1]) #Real solution that works, DO NOT DELETE #new_e[r][c] = int(np.ceil(new_e[r][c] + np.linalg.solve(A,y)[-1])) new_e[r][c] = np.round(new_e[r][c] + np.linalg.solve(A,y)[-1], 1) return new_e.astype(int) ``` %% Cell type:code id:3cc609dc tags: ``` python new_error = reconstruct(err, A) ``` %% Output [22471.5] %% Cell type:code id:5d290a0c tags: ``` python err ``` %% Output array([[22546, 22514, 22513, ..., 22581, 22576, 22587], [22488, 67, -21, ..., -1, -1, 22576], [22514, -15, -3, ..., 10, -45, 22575], ..., [22317, 82, -2, ..., -64, 5, 22937], [22335, -33, 18, ..., 47, -16, 22932], [22333, 22339, 22362, ..., 22952, 22947, 22961]]) %% Cell type:code id:706f2816 tags: ``` python first = [] second = [] third = [] fourth = [] for i in range(1,diff.shape[0]-1): for j in range(1,diff.shape[1]-1): if diff[i][j] <= 50: first.append(np.abs(err[i][j])) elif diff[i][j] > 50 and diff[i][j] <= 100: second.append(np.abs(err[i][j])) elif diff[i][j] > 100 and diff[i][j] <= 200: third.append(np.abs(err[i][j])) else: fourth.append(np.abs(err[i][j])) ``` %% Cell type:code id:530d2cab tags: ``` python plt.hist(first) plt.show() print(np.max(first)) plt.hist(second) plt.show() print(np.max(second)) plt.hist(third) plt.show() print(np.max(third)) plt.hist(fourth) plt.show() print(np.max(fourth)) ``` %% Output 124 181 216 251 %% Cell type:code id:bb11dcd0 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:c01fda28 tags: ``` python def enc_experiment(images, plot=True): origin, predict, diff, error, A = plot_hist(images, 2) image = Image.open(images[0]) #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) new_error = np.copy(image) #new_error[1:-1,1:-1] = np.reshape(error[1:-1,1:-1],(510, 638)) new_error[1:-1, 1:-1] = error[1:-1, 1:-1] 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) if plot: plt.hist(new_error[1:],bins=100) plt.show() #ab_error = np.abs(new_error) #string = [str(i) for i in ab_error] string = [str(i) for i in new_error] #string = [str(i) for i in np.arange(0,5)] + [str(i) for i in np.arange(0,5)] + [str(i) for i in np.arange(0,2)]*2 freq = dict(Counter(string)) freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) node = make_tree(freq) encoding_dict = huffman_code_tree(node) #encoded = ["1"+encoding[str(-i)] if i < 0 else "0"+encoding[str(i)] for i in error] #print(time.time()-start) encoded = new_error.reshape((512,640)).copy().astype(str).astype(object) for i in range(encoded.shape[0]): for j in range(encoded.shape[1]): if i == 0 and j == 0: encoded[i][j] = encoded[i][j] else: #print(encoding_dict[encoded[i][j]]) encoded[i][j] = encoding_dict[encoded[i][j]] #print(encoded[i][j]) return encoding_dict, encoded, new_error.reshape((512,640)), image #print(encoding) ``` %% Cell type:code id:ffa858e8 tags: ``` python encode_dict, encoding, error, orig_image = enc_experiment(images, plot=False) ``` %% Cell type:code id:8dfdedc6 tags: ``` python print(orig_image) ``` %% Output [[22541 22531 22555 ... 22573 22589 22574] [22548 22544 22530 ... 22607 22612 22618] [22548 22544 22560 ... 22603 22605 22599] ... [22590 22593 22596 ... 22586 22627 22692] [22568 22575 22555 ... 22625 22702 22749] [22558 22541 22536 ... 22679 22748 22767]] %% Cell type:code id:825cc48c 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(encoded_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: if j == 1 and i == 1: 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)) #Real solution that works, DO NOT DELETE #new_e[r][c] = int(np.ceil(new_e[r][c] + np.linalg.solve(A,y)[-1])) print(int(the_keys[the_values.index(error_matrix[i,j])])) print(np.linalg.solve(A,y)[-1]) error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) + \ np.linalg.solve(A,y)[-1][0] #error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) break return error_matrix ``` %% Cell type:code id:ba1d2c2c tags: ``` python em = decoder(A, encoding, encode_dict) ``` %% Output 67 [22555.] %% Cell type:code id:b2cdce6d tags: ``` python ``` Loading
.ipynb_checkpoints/Error_to_Image-checkpoint.ipynb +28 −1 Original line number Diff line number Diff line %% Cell type:code id:dbef8759 tags: ``` python import numpy as np from prediction_MSE_Scout import file_extractor, image_extractor, im_distribution 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 from scipy.stats import gaussian_kde import seaborn as sns import pywt #import pywt from collections import Counter ``` %% Output --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) /var/folders/z2/plvrsqjs023g1cmx7k19mhzr0000gn/T/ipykernel_21377/741789573.py in <module> 1 import numpy as np ----> 2 from prediction_MSE_Scout import file_extractor, image_extractor, im_distribution 3 from matplotlib import pyplot as plt 4 from itertools import product 5 import os ~/Documents/Elphel/image-compression/prediction_MSE_Scout.py in <module> 16 from scipy.stats import gaussian_kde, entropy 17 import seaborn as sns ---> 18 import pywt 19 import math 20 #import cv2 ModuleNotFoundError: No module named 'pywt' %% Cell type:code id:9ed20f84 tags: ``` python def plot_hist(tiff_list, i=0): """ 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_int = image.astype(int) A = np.array([[3,0,-1],[0,3,3],[1,-3,-4]]) # the matrix for system of equation z0 = image_int[0:-2,0:-2] # get all the first pixel for the entire image z1 = image_int[0:-2,1:-1] # get all the second pixel for the entire image z2 = image_int[0:-2,2::] # get all the third pixel for the entire image z3 = image_int[1:-1,0:-2] # get all the fourth 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.linalg.solve(A,y)[-1] predict = np.floor(np.linalg.solve(A,y)[-1]).astype(int) #predict = [] # flatten the neighbor pixels 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) diff = np.pad(diff.reshape(510,638), pad_width=1) # flatten the image to a vector small_image = image_int[1:-1,1:-1] #Reshape the predictions to be a 2D array predict = np.pad(predict.reshape(510,638), pad_width=1) """predict[0,:] = image[0,:] predict[:,0] = image[:,0] predict[:,-1] = image[:,-1] predict[-1,:] = image[-1,:]""" #Calculate the error between the original image and our predictions #Note that we only predicted on the inside square of the original image, excluding #The first row, column and last row, column #error = (image_int - predict).astype(int) #Experiment #this one works error = image_int - predict return predict, diff, image_int, error, A ``` %% Cell type:code id:ba2881d9 tags: ``` python scenes = file_extractor() images = image_extractor(scenes) num_images = im_distribution(images, "11") ``` %% Cell type:code id:11e95c34 tags: ``` python predict, diff, im, err, A = plot_hist(images, 2) ``` %% Output --------------------------------------------------------------------------- NameError Traceback (most recent call last) /var/folders/z2/plvrsqjs023g1cmx7k19mhzr0000gn/T/ipykernel_21377/1723356297.py in <module> ----> 1 predict, diff, im, err, A = plot_hist(images, 2) NameError: name 'plot_hist' is not defined %% Cell type:code id:434e4d2f tags: ``` python def reconstruct(error, A): """ Function that reconstructs the original image from the error matrix and using the predictive algorithm developed in the encoding. Parameters: error (array): matrix of errors computed in encoding. Same shape as the original image (512, 640) in this case A (array): Matrix used for the system of equations to create predictions Returns: cd cdcd image (array): The reconstructed image """ new_e = error.copy() rows, columns = new_e.shape for r in range(1, rows-1): for c in range(1, columns-1): z0, z1, z2, z3 = new_e[r-1][c-1], new_e[r-1][c], new_e[r-1][c+1], new_e[r][c-1] y = np.vstack((-z0+z2-z3, z0+z1+z2, -z0-z1-z2-z3)) if r == 1 and c == 1: print(np.linalg.solve(A,y)[-1]) #Real solution that works, DO NOT DELETE #new_e[r][c] = int(np.ceil(new_e[r][c] + np.linalg.solve(A,y)[-1])) new_e[r][c] = np.round(new_e[r][c] + np.linalg.solve(A,y)[-1], 1) return new_e.astype(int) ``` %% Cell type:code id:3cc609dc tags: ``` python new_error = reconstruct(err, A) ``` %% Output [22471.5] %% Cell type:code id:5d290a0c tags: ``` python err ``` %% Output array([[22546, 22514, 22513, ..., 22581, 22576, 22587], [22488, 67, -21, ..., -1, -1, 22576], [22514, -15, -3, ..., 10, -45, 22575], ..., [22317, 82, -2, ..., -64, 5, 22937], [22335, -33, 18, ..., 47, -16, 22932], [22333, 22339, 22362, ..., 22952, 22947, 22961]]) %% Cell type:code id:706f2816 tags: ``` python first = [] second = [] third = [] fourth = [] for i in range(1,diff.shape[0]-1): for j in range(1,diff.shape[1]-1): if diff[i][j] <= 50: first.append(np.abs(err[i][j])) elif diff[i][j] > 50 and diff[i][j] <= 100: second.append(np.abs(err[i][j])) elif diff[i][j] > 100 and diff[i][j] <= 200: third.append(np.abs(err[i][j])) else: fourth.append(np.abs(err[i][j])) ``` %% Cell type:code id:530d2cab tags: ``` python plt.hist(first) plt.show() print(np.max(first)) plt.hist(second) plt.show() print(np.max(second)) plt.hist(third) plt.show() print(np.max(third)) plt.hist(fourth) plt.show() print(np.max(fourth)) ``` %% Output 124 181 216 251 %% Cell type:code id:bb11dcd0 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:c01fda28 tags: ``` python def enc_experiment(images, plot=True): origin, predict, diff, error, A = plot_hist(images, 2) image = Image.open(images[0]) #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) new_error = np.copy(image) #new_error[1:-1,1:-1] = np.reshape(error[1:-1,1:-1],(510, 638)) new_error[1:-1, 1:-1] = error[1:-1, 1:-1] 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) if plot: plt.hist(new_error[1:],bins=100) plt.show() #ab_error = np.abs(new_error) #string = [str(i) for i in ab_error] string = [str(i) for i in new_error] #string = [str(i) for i in np.arange(0,5)] + [str(i) for i in np.arange(0,5)] + [str(i) for i in np.arange(0,2)]*2 freq = dict(Counter(string)) freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) node = make_tree(freq) encoding_dict = huffman_code_tree(node) #encoded = ["1"+encoding[str(-i)] if i < 0 else "0"+encoding[str(i)] for i in error] #print(time.time()-start) encoded = new_error.reshape((512,640)).copy().astype(str).astype(object) for i in range(encoded.shape[0]): for j in range(encoded.shape[1]): if i == 0 and j == 0: encoded[i][j] = encoded[i][j] else: #print(encoding_dict[encoded[i][j]]) encoded[i][j] = encoding_dict[encoded[i][j]] #print(encoded[i][j]) return encoding_dict, encoded, new_error.reshape((512,640)), image #print(encoding) ``` %% Cell type:code id:ffa858e8 tags: ``` python encode_dict, encoding, error, orig_image = enc_experiment(images, plot=False) ``` %% Cell type:code id:8dfdedc6 tags: ``` python print(orig_image) ``` %% Output [[22541 22531 22555 ... 22573 22589 22574] [22548 22544 22530 ... 22607 22612 22618] [22548 22544 22560 ... 22603 22605 22599] ... [22590 22593 22596 ... 22586 22627 22692] [22568 22575 22555 ... 22625 22702 22749] [22558 22541 22536 ... 22679 22748 22767]] %% Cell type:code id:825cc48c 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(encoded_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: if j == 1 and i == 1: 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)) #Real solution that works, DO NOT DELETE #new_e[r][c] = int(np.ceil(new_e[r][c] + np.linalg.solve(A,y)[-1])) print(int(the_keys[the_values.index(error_matrix[i,j])])) print(np.linalg.solve(A,y)[-1]) error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) + \ np.linalg.solve(A,y)[-1][0] #error_matrix[i][j] = int(the_keys[the_values.index(error_matrix[i,j])]) break return error_matrix ``` %% Cell type:code id:ba1d2c2c tags: ``` python em = decoder(A, encoding, encode_dict) ``` %% Output 67 [22555.] %% Cell type:code id:b2cdce6d tags: ``` python ```