Multimediální technologie – Cvičení 5

Zadání

Naprogramujte kompresní a dekompresní metodu LZW a komprimujte a dekomprimujte její pomocí data (čísla) v souboru Cv05_LZW_data.bin, kde jsou jednotlivá čísla uložena jako uint8. Slovník dat je 5 čísel: 1, 2, 3, 4, 5.

Soubory


Řešení

# -*- coding: utf-8 -*-
import os
import numpy as np
import matplotlib.pyplot as plt

clear = lambda: os.system('cls')
clear()
plt.close('all')

def getCompressDictionary(size):
    dictionary = {}

    for i in range(0, size):
        dictionary[str(i)] = i

    return dictionary

def getDecommpressDictionary(size):
    dictionary = {}

    for i in range(0, size):
        dictionary[i] = str(i)

    return dictionary

def compress(data, size):
    result = []
    dictionary = getCompressDictionary(size)
    pW = ""

    for char in data:
        str = pW + char
        if str in dictionary:
          pW = str
        else:
          result.append(dictionary[pW])
          dictionary[str] = size
          size += 1
          pW = char

    if pW:
         result.append(dictionary[pW])

    return result

def decompress(data, size):
    dictionary = getDecommpressDictionary(size)

    pW = str(data.pop(0))
    result = [pW]

    for i in data:
        if i in dictionary:
            temp = dictionary[i]
        elif i == len(dictionary):
            temp = pW + pW[0]

        result.append(temp)
        dictionary[size] = pW + temp[0]
        pW = temp
        size += 1

    return result

def readFile(file_name):
    data = np.zeros

    with open(file_name,'rb') as file:
        data = np.fromfile(file, dtype=np.uint8)

    return data

def getStringData(fileData):
    result = ''

    for c in fileData:
        result += str(c)

    result = "".join(result)

    return result

def getCountOfUnique(text):
    from collections import OrderedDict
    unique  = "".join(OrderedDict.fromkeys(text))

    num = 0

    for c in unique:
        num += 1

    return num+1

def main():
    fileData = readFile('Cv05_LZW_data.bin')

    stringData = getStringData(fileData)
    print 'Original data: {0}'.format(stringData)

    uniqueChars = getCountOfUnique(stringData)
    print 'Počet unikátních zaků: {0}'.format(uniqueChars)

    compressed = compress(stringData, uniqueChars)
    print 'Komprimovaná data: {0}'.format(compressed)

    decompressed = decompress(compressed, uniqueChars)
    decompressed = ''.join(decompressed)
    print 'Dekomprimovaná data: {0}'.format(decompressed)

if __name__ == "__main__":
    main()

You may also like...

Napsat komentář

Vaše emailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *