compress_start.py 5.53 KB
Newer Older
Nathaniel Callens's avatar
Nathaniel Callens committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
'''
Created on Jan 11, 2022

@author: nathanielc

python file located in the Image Compression project
folder under nathanielc user. This python file is for
exploring possible image compression techniques and is by 
no means a final product. Goal is to learn how to download 
images and extract important statistics from them.
'''

import numpy as np
from matplotlib import pyplot as plt
Nathaniel Callens's avatar
Nathaniel Callens committed
15
from itertools import product
Nathaniel Callens's avatar
Nathaniel Callens committed
16 17 18
import os
import sys
from PIL import Image
Kelly Chang's avatar
Kelly Chang committed
19

Nathaniel Callens's avatar
Nathaniel Callens committed
20

21
def file_extractor(dirname="images"):
Nathaniel Callens's avatar
Nathaniel Callens committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    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

Nathaniel Callens's avatar
Nathaniel Callens committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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:-6] == num:
            tiff.append(im)
    return tiff
67
    
68
    
Nathaniel Callens's avatar
Nathaniel Callens committed
69 70 71 72 73 74
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
    """
Kelly Chang's avatar
Kelly Chang committed
75
    '''jj = 0
Nathaniel Callens's avatar
Nathaniel Callens committed
76 77 78
    fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15,12))
    for cam, ax in zip(cameras, axs.ravel()):
        diff = []
79 80 81 82 83 84 85 86 87 88 89 90 91 92
        for ii in range(len(cam)):
            image = Image.open(cam[ii])    #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
            ar1, ar2 = image.shape
            ind1, ind2 = np.random.randint(1,ar1-1), np.random.randint(1,ar2-1) #ind1 randomly selects a row, ind2 randomly selects a column, 
                                                                            #this is now a random pixel selection within the image
            
            surrounding = []                                                #initialize a list to be filled the 8 surrounding pixels
            for i,j in product(np.arange(-1,2), repeat=2):                  #Iterate through the combinations of surrounding pixel indices
                if i == 0 and j == 0:                                       #Avoid the target pixel
                    continue
                else:
                    surrounding.append(image[ind1+i, ind1+j])               #Add the other 8 pixels to the list
            diff.append(np.max(surrounding)-np.min(surrounding))
Nathaniel Callens's avatar
Nathaniel Callens committed
93
        ax.hist(diff)
Nathaniel Callens's avatar
Nathaniel Callens committed
94 95
        ax.set_title(f"tiff {jj}")
        jj += 1
96 97
    plt.tight_layout()
    plt.show()
Kelly Chang's avatar
Kelly Chang committed
98 99 100 101 102 103
    return '''

    image = tiff_list[0]
    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
    row, col = image.shape
Kelly Chang's avatar
Kelly Chang committed
104 105 106 107
    predict = np.empty([row-1,col-1])     # create a empty matrix to update prediction
    temp = image.copy
    diff = np.empty([row-1,col-1])
    
108 109
    for r in range(1,row-1):                  # loop through the rth row
        for c in range(1,col-1):              # loop through the cth column
Kelly Chang's avatar
Kelly Chang committed
110
            surrounding = np.array([temp[r-1,c-1], temp[r-1,c], temp[r-1,c+1], temp[r,c-1]])
Kelly Chang's avatar
Kelly Chang committed
111
            predict[r,c] = np.mean(surrounding)       # take the mean of the previous 4 pixels
Kelly Chang's avatar
Kelly Chang committed
112
            temp[r,c] = np.mean(surrounding)
Kelly Chang's avatar
Kelly Chang committed
113
            diff[r,c] = (np.max(surrounding)-np.min(surrounding))
Nathaniel Callens's avatar
Nathaniel Callens committed
114

Kelly Chang's avatar
Kelly Chang committed
115 116 117 118 119 120 121 122 123 124 125
    predict = np.ravel(predict)
    diff = np.ravel(diff)
    n = len(predict)
    fig = plt.figure()

    ax1 = fig.add_subplot(111, projection='3d')
    z3 = np.zeros(n)
    
    dx = np.ones(n)
    dy = np.ones(n)
    dz = np.arange(n)
Kelly Chang's avatar
Kelly Chang committed
126
    
Kelly Chang's avatar
Kelly Chang committed
127 128 129
    ax1.bar3d(predict, diff, z3, dx, dy, dz, color="red")
    ax1.axis('off')
    plt.show()
130
    return image, predict, diff
131 132 133 134 135 136 137 138


if __name__ == '__main__':

    """For boundary cases: Start by grabbing the shape of the images and saving those
    as variables. Then, if statements for if row == 0 or row == maximum and if
    col == 0 or col == maximum. Then grab corresponding open pixels. Then proceed to do
    an and statement that handles the corners"""
139
    
Nathaniel Callens's avatar
Nathaniel Callens committed
140
    
141 142
    scenes = file_extractor()
    images = image_extractor(scenes)
Nathaniel Callens's avatar
d  
Nathaniel Callens committed
143 144 145
    #image, predict, difference = plot_hist(images)
    #error = np.abs(image-predict)
    
146
    
Kelly Chang's avatar
Kelly Chang committed
147
    plot_hist(images)
Nathaniel Callens's avatar
Nathaniel Callens committed
148

Nathaniel Callens's avatar
Nathaniel Callens committed
149