16
Nov
07

Run-Length Encoding

Questo è il primo di una serie di articoli (forse, se ne avrò voglia e tempo) inerenti alla compressione dei dati. La cosa verrà trattata nel modo più pragmatico possibile riducendo all’osso i simbolini matematici.

Per iniziare ho scelto una forma di codifica senza perdita usata generalmente nei fax (insieme ad altra “roba” che vedremo in seguito). L’idea alla base è molto semplice: sequenze di dati contigue ripetute vengono trasformate in una coppia (simbolo, #occorrenze). Ad esempio la stringa aaabbccccc sarà rappresentata da (a,3)(b,2)(c,5). Tra i formati basati su questo principio ricordiamo PackBits di Apple, introdotta con il MacPaint ed usata a volte nei file tiff. Vediamone ora una semplice implementazione in Python.


"""
Created by Jonathan Masci @ Casapiddu.
Copyright (c) 2007. All rights reserved.
"""

import sys

class RLE:
	def encode(self, inputte, outputte):
	 	f = open(inputte, 'r')
		o = open(outputte, 'w')
		t = f.read()
		counter = 0
		lastChar = t[0]
		strout = ""
		for c in t:
			if lastChar == c:
				counter += 1
			else:
				strout += lastChar + str(counter) + ";"
				lastChar = c
				counter = 1
		strout += lastChar + str(counter) + ";"
		lastChar = c
		counter = 1
		o.write(strout)
		o.close()
		f.close()

	def decode(self, inputte, outputte):
		f = open(inputte, 'r')
		o = open(outputte, 'w')
		t = f.read()
		lastChar = ""
		strout = ""
		char = ""
		counter = 0
		state = 0
		for c in t:
			if state == 0: #read the symbol
				char = c
				state = 1
			else:
				if state == 1: #read the occurrences
					if c == ';':
						counter = int(lastChar)
						i = 0
						while i < counter:
							strout += char
							i += 1
						lastChar = ""
						char = ""
						state = 0;
					else:
						lastChar += c
		o.write(strout)
		o.close()
		f.close()		

def main():
	erle = RLE()
	erle.encode('inputte.txt', 'outputte.txt')
	drle = RLE()
	drle.decode('outputte.txt', 'decoded.txt')

if __name__ == '__main__':
    main()

Per provarlo basta copiare il codice e creare un file di input che deve necessariamente chiamarsi inputte.txt (ovviamente sto scherzando però inputte è un bel nome) ed eseguire il comando

python nomesorgente.py

Come vedrete non è che comprima gran che, anzi a volte la dimensione del file aumenta, ma forse con la prossima puntata riusciremo a fare di meglio preprocessando l’input.

Have fun!


4 Risposte a “Run-Length Encoding”


  1. 17 Novembre 2007 alle 0:30:15

    Forse un pochino meglio è la codifica di Huffman

  2. 17 Novembre 2007 alle 0:59:57

    Volevo iniziare in modo soft, con Huffman c’è già il problema della statistica. Se poi vogliamo esagerare parliamo di PPM che è quanto di più sofisticato si possa richiedere da un compressore. Il problema è che dubito di riuscire ad implementarlo in poche righe (eheh).

  3. 17 Novembre 2007 alle 10:46:40

    vorrei sottolineare come ogni compressore sia allo stesso tempo sofisticato e non banale. El ferro.

  4. 17 Novembre 2007 alle 10:50:48

    Eheh, non dimentichiamoci che sono tutti smart.


Lascia una Risposta




Difendi Rebeldia!

Aggiungi ai tuoi feed

 RSS Feed
Add to Google
Add to My Yahoo!
Add to Technorati Favorites!
Add to netvibes

Blog Stats

  • 151,257 hits

Pidduisti on-line

hit counters


Made on a Mac
Last.fm

SocialVibe


Giveaway of the Day
highlightInterests("ProfileMusica");
Musicatable.lfmWidget8f0839bdbf919d97305135788e54986d td {margin:0 !important;padding:0 !important;border:0 !important;}table.lfmWidget8f0839bdbf919d97305135788e54986d tr.lfmHead a:hover {background:url(http://cdn.last.fm/widgets/images/en/header/chart/weeklytracks_regular_blue.png) no-repeat 0 0 !important;}table.lfmWidget8f0839bdbf919d97305135788e54986d tr.lfmEmbed object {float:left;}table.lfmWidget8f0839bdbf919d97305135788e54986d tr.lfmFoot td.lfmConfig a:hover {background:url(http://cdn.last.fm/widgets/images/en/footer/blue.png) no-repeat 0px 0 !important;;}table.lfmWidget8f0839bdbf919d97305135788e54986d tr.lfmFoot td.lfmView a:hover {background:url(http://cdn.last.fm/widgets/images/en/footer/blue.png) no-repeat -85px 0 !important;}table.lfmWidget8f0839bdbf919d97305135788e54986d tr.lfmFoot td.lfmPopup a:hover {background:url(http://cdn.last.fm/widgets/images/en/footer/blue.png) no-repeat -159px 0 !important;}

pages

 

Novembre 2007
L M M G V S D
« Ott   Dic »
 1234
567891011
12131415161718
19202122232425
2627282930