User talk:Tsahal

pghu
using namespace std;
 * 1) include
 * 2) include
 * 3) include
 * 4) include "imagePgm.h"

typedef unsigned char byte;

int main{ //carico l'immagine fstream fin("image.huf", fstream::in | fstream::binary); //controllo che l'immagine esista if(!fin.good){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }	//leggo la larghezza e l'altezza short larghezza, altezza; fin.read((char*)&larghezza, 2); if(fin.eof){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }

fin.read((char*)&altezza, 2); //controllo sul file if(fin.eof){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }	//controllo sui valori della dimensione dell'immagine if(larghezza==0 || altezza==0){ cout << "Errore nella dimensione dell'immagine" << endl; return 0; }	cout << "Largezza: " < huff; //variabile che indica la lunghezza dei simboli byte num; //variabile che indica il simboli byte val; //lunghezza precedente, utile per calcolare l'huffman canonico unsigned lun_prec = 0; unsigned lun_att = 1; //il codice di huffman calcolato unsigned cod = 0; while(true){ fin.read((char*)&num,1); if(fin.eof) break; //se trofo FF esco dal calcolo di huffman if(num == 0xFF) break; //codifico num codici di huffman for(unsigned i=0; i<(unsigned)num; ++i){ fin.read((char*)&val,1); if(fin.eof) break; //se non sono al primo valore di huffman if(num > 1){ //se sono al primo valore effettuo uno shift a sinistra if(i == 0) cod = (cod+1) << (lun_att - lun_prec); else ++cod; }			//inserimento nella mappa huff.insert(pair(cod,val)); lun_prec = lun_att; }		++lun_att; }

imagePgm img(larghezza,altezza);

cod = 0; unsigned pxl = 0; while(true){ fin.read((char*)&val,1); if(fin.eof) break; for(unsigned i=0; i<8; ++i){ //leggo un bit alla volta cod = cod << 1; cod = cod + ((val >> (7-i))&1); //se ho trovato il codice e non ho raggiunto la dimensione massima dell'immagine //inserisco il codice di huffman trovato nell'immagine pgm if(huff.count(cod) >0){ if(pxl < (unsigned)img.getDim) img(pxl) = huff[cod]; cod = 0; ++pxl; }		}	}	//salvo l'immagine img.savePgm("fragola.pgm"); }

hupg
--*/

using namespace std;
 * 1) include
 * 2) include
 * 3) include
 * 4) include "imagePgm.h"

typedef unsigned char byte;

int main{ //carico l'immagine fstream fin("image.huf", fstream::in | fstream::binary); //controllo che l'immagine esista if(!fin.good){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }	//leggo la larghezza e l'altezza short larghezza, altezza; fin.read((char*)&larghezza, 2); if(fin.eof){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }

fin.read((char*)&altezza, 2); //controllo sul file if(fin.eof){ cout << "Errore nel caricamento dell'immagine" << endl; return 0; }	//controllo sui valori della dimensione dell'immagine if(larghezza==0 || altezza==0){ cout << "Errore nella dimensione dell'immagine" << endl; return 0; }	cout << "Largezza: " < huff; //variabile che indica la lunghezza dei simboli byte num; //variabile che indica il simboli byte val; //lunghezza precedente, utile per calcolare l'huffman canonico unsigned lun_prec = 0; unsigned lun_att = 1; //il codice di huffman calcolato unsigned cod = 0; while(true){ fin.read((char*)&num,1); if(fin.eof) break; //se trofo FF esco dal calcolo di huffman if(num == 0xFF) break; //codifico num codici di huffman for(unsigned i=0; i<(unsigned)num; ++i){ fin.read((char*)&val,1); if(fin.eof) break; //se non sono al primo valore di huffman if(num > 1){ //se sono al primo valore effettuo uno shift a sinistra if(i == 0) cod = (cod+1) << (lun_att - lun_prec); else ++cod; }			//inserimento nella mappa huff.insert(pair(cod,val)); lun_prec = lun_att; }		++lun_att; }

imagePgm img(larghezza,altezza);

cod = 0; unsigned pxl = 0; while(true){ fin.read((char*)&val,1); if(fin.eof) break; for(unsigned i=0; i<8; ++i){ //leggo un bit alla volta cod = cod << 1; cod = cod + ((val >> (7-i))&1); //se ho trovato il codice e non ho raggiunto la dimensione massima dell'immagine //inserisco il codice di huffman trovato nell'immagine pgm if(huff.count(cod) >0){ if(pxl < (unsigned)img.getDim) img(pxl) = huff[cod]; cod = 0; ++pxl; }		}	}	//salvo l'immagine img.savePgm("fragola.pgm"); }

hutxt
using namespace std;
 * 1) include
 * 2) include
 * 3) include
 * 4) include

typedef unsigned char byte;

struct tabella{ byte lung; byte simbolo; };

int main{ fstream fin("esempio.txt.huf", fstream::in | fstream::binary); byte n;	unsigned tabelems; unsigned numcodici;

fin.read((char*)&n,1); tabelems = (unsigned)n + 1; if(fin.eof) return 0; vector cod(tabelems);

cout << "Numero elementi: "<< (int)tabelems << endl; cout << "Codici:" << endl; for(int i=0; i>24) | ((numcodici<<8) & 0x00FF0000) | ((numcodici>>8) & 0x0000FF00) | (numcodici<<24); cout << "Numero codici: " << numcodici << endl;

//generazione codici huffman canonici map huff; unsigned tmp = 0; huff.insert(pair(tmp, cod[0].simbolo)); for(int i=1; i(tmp,cod[i].simbolo)); }

int num = 0; unsigned val = 0; fstream fout("esempio.txt", fstream::out); cout << "Output:" << endl; while(true){ byte x;		fin.read((char*)&x,1); if(fin.eof) break; for(int i=0; i<8; ++i){ val = val << 1; val = val + ((x >> (7-i))&1); if(huff[val]){ cout << huff[val]; fout << huff[val]; val = 0; ++num; if(num == numcodici) break; }		}	}	fout.close; cout << endl; } /**********************************************************************************/

Hufftxt2 /**********************************************************
 * 1) include
 * 2) include
 * 3) include
 * 4) include
 * 5) include


 * 1) include"bitstreams.h"

using namespace std;

typedef unsigned char byte; typedef unsigned int uint;

struct elem{ byte _sym; uint _len, _code;

elem(byte sym = 0, uint len = 0) :_len(len), _sym(sym), _code(0){}

};

string to_binary(uint code, uint len){ string s;	while (len-- > 0){ if ((code >> len) & 1) s += '1'; else s += '0'; }	return s; }

// ordinamento della struttura bool greater_len(const elem& x, const elem& y){ return x._len < y._len; }

int decompress(const string& inputFilename, const string& outputFilename){

ifstream is(inputFilename,ios::binary); if (!is){ cout << "cannot open the file " << inputFilename << "\n"; return EXIT_FAILURE; }

bitreader br(is);

unsigned num_elems = br(8); ++num_elems;

elem t;	vector leaves; // lettura della coppia (simbolo,lunghezza) for (unsigned i = 0; i < num_elems; ++i){ t._len = br(8); t._sym = br(8);

leaves.emplace_back(t); }

// generazione dei codici canonici di Huffman // ordinamento della struttura sort(leaves.begin,leaves.end,greater_len);

unsigned cur_code = 0; unsigned cur_len = 0; for (unsigned i = 0; i<leaves.size; ++i){ cur_code <<= leaves[i]._len - cur_len; leaves[i]._code = cur_code; cur_code++;

cur_len = leaves[i]._len; }

{		ofstream os("canonical.txt"); for (unsigned i = 0; i<leaves.size; ++i){ os << leaves[i]._sym << "(" << uint(leaves[i]._sym) << ")" << "\t" << "len=" << leaves[i]._len; os << "\t" << to_binary(leaves[i]._code, leaves[i]._len) << "\n"; }	}

// numero di codici unsigned num_codici = br(32);

// file di output ofstream os(outputFilename,ios::binary); bitwriter bw(os);

for (unsigned i = 0; i < num_codici; ++i){ unsigned cur = 0; unsigned len = 0; unsigned code = 0; while (cur < leaves.size){ while (len < leaves[cur]._len){ code = (code << 1) | br(1); ++len; }			if (code == leaves[cur]._code){ bw(leaves[cur]._sym, 8); break; }			++cur; }

if (cur == leaves.size){ cout << "cannot find huffman code\n"; return EXIT_FAILURE; }	}	return EXIT_SUCCESS; }

void Syntax{ cout << "Syntax:\n"; cout << "huff \n"; cout << "\n"; }

int main(int argc, char* argv[]){

if (argc != 3){ Syntax; return EXIT_FAILURE; }

return decompress(argv[1],argv[2]); } /*******************************************************************************/ //convert colori///////////

using namespace std;
 * 1) include "imagePpm.h"
 * 2) include "image.h"
 * 3) include

typedef unsigned char byte;

int main{ imagePpm img; if(img.loadImage("rana.ppm")) cout << "Caricamento immagine completata!" << endl << endl; else cout << "Errore nel caricamento dell'immagine" << endl << endl; //conversione dei colori vector y, cb, cr; for(int i=0; i 255) tmp_y = 255; double tmp_cb = -0.1687*(int)img(0,i) + -0.3313*(int)img(1,i) + 0.5*(int)img(2,i) + 128; if(tmp_cb < 0) tmp_cb = 0; if(tmp_cb > 255) tmp_cb = 255; double tmp_cr = 0.5*(int)img(0,i) - 0.4187*(int)img(1,i) - 0.0813*(int)img(2,i) + 128; if(tmp_cr < 0) tmp_cr = 0; if(tmp_cr > 255) tmp_cr = 255; y.push_back((byte)tmp_y); cb.push_back((byte)tmp_cb); cr.push_back((byte)tmp_cr); }	cout << "Conversione da RGB a YCbCr effettuata!" << endl; //salvataggio file ycbcr.bin fstream fout("ycbcr.bin", fstream::out | fstream::binary); for(unsigned i=0; i<y.size; ++i){ fout << y[i] << cb[i] << cr[i]; }	fout.close; cout << "Salvataggio file YCbCr.bin effettuato con successo!" << endl;

//salvataggio file y.pgm, cb.pgm, cr.pgm imagePgm img_y(img.getWidth, img.getHeight); imagePgm img_cb(img.getWidth, img.getHeight); imagePgm img_cr(img.getWidth, img.getHeight); for(int i=0; i<img.getDim; ++i){ img_y(i) = y[i]; img_cb(i) = cb[i]; img_cr(i) = cr[i]; }	img_y.savePgm("img_y.pgm"); img_cb.savePgm("img_cb.pgm"); img_cr.savePgm("img_cr.pgm"); cout << "Creazione immagini y.pgm, cb.pgm, cr.pgm completata!" << endl << endl;

//sottocampionamento Cb Cr con matrici 2x2 imagePpm tmp(img.getWidth, img.getHeight); for(int i=0; i<img.getDim; ++i){ tmp(0,i) = cb[i]; tmp(1,i) = cr[i]; tmp(2,i) = y[i]; }	tmp.resize(2); vector cb2,cr2; for(int i=0; i<tmp.getHeight; i+=2){ for(int k=0; k<tmp.getWidth; k+=2){ double media_cb = tmp(0,k,i) + tmp(0,k+1,i) + tmp(0,k,i+1) + tmp(0,k+1,i+1); double media_cr = tmp(1,k,i) + tmp(1,k+1,i) + tmp(1,k,i+1) + tmp(1,k+1,i+1); media_cb /= 4; media_cr /= 4; cb2.push_back((byte)media_cb); cr2.push_back((byte)media_cr); }	}	cout << "Sottocampionamento di Cb e Cr in matrici 2x2 effettuato!" << endl; fstream fy("y.bin", fstream::out | fstream::binary); fstream fcb("cb.bin", fstream::out | fstream::binary); fstream fcr("cr.bin", fstream::out | fstream::binary); for(unsigned i=0; i<y.size; ++i){ fy << (byte)y[i]; }	fy.close; for(unsigned i=0; i<cb2.size; ++i){ fcb << (byte)cb2[i]; fcr << (byte)cr2[i]; }	fy.close; fcr.close; fcb.close; cout << "Salvataggio file y.bin, cb.bin, cr.bin completato!" << endl << endl;

//ricostruzione immagine int k=0; imagePpm imgrec(tmp.getWidth, tmp.getHeight); for(int i=0; i<imgrec.getDim; ++i) imgrec(0,i) = tmp(2,i); for(int y=0; y<imgrec.getHeight; y+=2){ for(int x=0; x<imgrec.getWidth; x+=2){ for(int j=0; j<2; ++j){ for(int i=0; i<2; ++i){ imgrec(1,x+i,y+j) = cb2[k]; imgrec(2,x+i,y+j) = cr2[k]; }			}			++k; }	}	cout << "Ricostruzione immagini con valori sottocampionati conclusa!" << endl; fstream frec("ycbcr_rec.bin", fstream::out | fstream::binary); for(int i=0; i 255) tmp = 255; if(tmp < 0) tmp = 0; imgfin(0,i) = (byte)tmp; tmp = imgrec(0,i) - 0.34414*((int)imgrec(1,i)-128) - 0.71414*((int)imgrec(2,i)-128); if(tmp > 255) tmp = 255; if(tmp < 0) tmp = 0; imgfin(1,i) = (byte)tmp; tmp = imgrec(0,i) + 1.772*((int)imgrec(1,i)-128); if(tmp > 255) tmp = 255; if(tmp < 0) tmp = 0; imgfin(2,i) = (byte)tmp; }	cout << "Conversione da YCbCr a RGB completata!" << endl; imgfin.savePpm("output.ppm"); cout << "Salvataggio immagine finale completato con successo!" << endl << endl; }

/***************************************************************************/

Huff compress
 * 1) include
 * 2) include
 * 3) include
 * 4) include
 * 5) include
 * 6) include
 * 7) include
 * 8) include


 * 1) include"bitstreams.h"

using namespace std;

typedef unsigned int uint; typedef unsigned char byte;

struct frequences{

vector _f;

typedef vector ::iterator iterator; typedef vector ::const_iterator const_iterator;

frequences :_f(256){}

void operator(uint b){ _f[b]++; } uint& operator[](uint b){ return _f[b]; } const uint& operator[](uint b) const { return _f[b]; }

iterator begin{ return _f.begin; } const_iterator begin const { return _f.begin; } iterator end{ return _f.end; } const_iterator end const { return _f.end; } };

struct elem{

// dati uint _sym; uint _freq;

// structura dell'albero elem* _left; elem* _right;

// codifica uint _code; uint _len;

elem(uint sym = 0, uint freq = 0) :_sym(sym), _freq(freq), _code(0), _len(0), _left(nullptr), _right(nullptr){}

bool is_leaf const{ return _left == nullptr; }

bool operator<(elem& other) const{ return _freq < other._freq; } bool operator>(elem& other) const{ return _freq > other._freq; } bool operator==(elem& other) const{ return _freq == other._freq; } };

template struct ptr_less :binary_function{ bool operator(const T& x, const T& y) const{ return *x < *y; } };

template struct ptr_greater :binary_function{ bool operator(const T& x, const T& y) const{ return *x > *y; } };

bool greater_len(const elem& x, const elem& y){ return x._len < y._len; } bool ordina(const elem& x, const elem& y){ return x._sym < y._sym; }

void compute_codes(elem* node, uint code = 0, uint len = 0){ if (node->is_leaf){ node->_len = len; node->_code = code; }	else{ compute_codes(node->_left, (code << 1), len + 1); compute_codes(node->_right, (code << 1) + 1, len + 1); } }

string to_binary(uint code, uint len){

string s;	while (len-- > 0){ if ((code >> len) & 1) s += '1'; else s += '0'; }	return s; }

uint convert(float d){

uint i = static_cast (d+0.5); return i; }

struct coppia{ uint _len; uint _count;

coppia : _len(1), _count(0) {} };

vector counter(const vector & other) {

vector _v; coppia c;	uint count = 0; for (uint len = 1; len <= 254; ++len){ for (uint i = 0; i < other.size; ++i){ if (len==other[i]._len){ c._len = len; count++;; }		}		if (count > 0){ c._count = count; _v.emplace_back(c); count = 0; }	}	 return _v; }

int compress(const string& inputFilename, const string& outputFilename){

ifstream is(inputFilename, ios::binary); if (!is){ cout << "cannot open the file" << inputFilename << "\"\n";		return EXIT_FAILURE;	}

vector _v; copy(istream_iterator (is), istream_iterator, inserter(_v, _v.end));

vector vettore; for (auto& x : _v){ vettore.push_back(convert(x * 100)); }

frequences freq; freq = for_each(vettore.begin, vettore.end, freq);

{		ofstream os("freq.txt"); copy(freq.begin, freq.end, ostream_iterator (os, "\n")); }

vector leaves; for (uint i = 0; i < 256; ++i){ if (freq[i]>0) leaves.emplace_back(i, freq[i]); }

priority_queue<elem*, vector<elem*>, ptr_greater<elem*>> lst; for (auto& x : leaves){ lst.push(&x); }

while (lst.size > 1){

elem* group = new elem; group->_left = lst.top; lst.pop; group->_right = lst.top; lst.pop;

group->_freq = group->_left->_freq + group->_right->_freq;

lst.push(group); }

elem* root = lst.top; lst.pop;

compute_codes(root);

sort(leaves.begin, leaves.end, greater_len);

{		ofstream os("codes.txt"); for (const auto& x : leaves){ os << x._sym << "\t" << "len = " << x._len << "\t" << "code =" << to_binary(x._code, x._len) << "\n"; }	}

// generazione dei codici canonici di huffman uint cur_code = 0; uint cur_len = 0;

for (auto& x : leaves){ cur_code <<= x._len - cur_len; x._code = cur_code;

cur_code++; cur_len = x._len; }

{		ofstream os("canonical.txt"); for (const auto& x : leaves){ os << x._sym << "\t" << "freq = " << x._freq << "\t" << "len =" << x._len << "\t" << "code =" << to_binary(x._code, x._len) << "\n"; }	}

vector c = counter(leaves);

// codifica ofstream os(outputFilename,ios::binary); bitwriter bw(os);

// fine della tabella bw(0xFF, 8); // numero di simboli codificati unsigned dim = vettore.size; os.write(reinterpret_cast<const char*>(&dim), 2); vector code_table(256); for (const auto& x : leaves){ code_table[x._sym] = x;	}

// dati for (const auto& b: vettore){ const auto& x = code_table[b]; bw(x._code, x._len); }

return EXIT_SUCCESS; }

void Syntax{ cout << "Huffman \n"; cout << "\n"; }

int main(int argc, char* argv[]){

if (argc != 3){ Syntax; return EXIT_FAILURE; }	else return compress(argv[1], argv[2]); }

/********************************************************************************************* bmp2ppm


 * 1) include
 * 2) include
 * 3) include
 * 4) include


 * 1) include"bitstreams.h"
 * 2) include"image.h"
 * 3) include"ppm.h"
 * 4) include"types.h"

using namespace std;

struct palette{

byte B, G, R, reserved; vector<pair<uint, palette>> Color;

bool read(istream& is, uint num_colors){

// inizia la color table is.seekg(54); for (uint i = 0; i < num_colors; ++i){ palette p;			is.read(reinterpret_cast<char*>(&p),sizeof(int)); Color.push_back(make_pair(i, p)); }		return true; }

};

int bmp2ppm(const string& inputFilename,const string& outputFilename){

ifstream is(inputFilename, ios::binary); if (!is){ cout << "cannot open the file \"" << inputFilename << "\"\n"; return EXIT_FAILURE; }

bitreader br(is); // estrazione dei dati dell'immagine

// dove iniziano i dati is.seekg(10, ios::beg); uint image_data; is.read(reinterpret_cast<char*>(&image_data), sizeof image_data); // larghezza e altezza is.seekg(18); uint w,h; is.read(reinterpret_cast<char*>(&w), sizeof w); is.read(reinterpret_cast<char*>(&h), sizeof h);

// immagine di uscita image img(w, h); // numero di bit/pixel is.seekg(28); short bpp; is.read(reinterpret_cast<char*>(&bpp), sizeof(short));

// ogni riga viene reso multiplo di 32 bit uint rowBits = w*bpp; while (rowBits % 32){ rowBits++; }

// la larghezza multipla di 32 bit uint _w = rowBits / bpp; // immagine con la riga multipla di 32 bit image imm(_w, h);

// Color table per quelli che ce l'hanno if (bpp != 24){ }

// i dati dell'immagine is.seekg(image_data); if (bpp == 24){

for (uint y = h-1; y < h; --y){ for (uint x = 0; x < _w; ++x){ is.read(reinterpret_cast<char*>(&imm(x, y)[2]),1); is.read(reinterpret_cast<char*>(&imm(x, y)[1]), 1); is.read(reinterpret_cast<char*>(&imm(x, y)[0]), 1);

if (x < w)					swap(img(x, y), imm(x, y)); }		}	}	else{

// Contiene la color table palette root; root.read(is, (1 << bpp)); // dati dell'immagine is.seekg(image_data); if (bpp == 8){ byte index; for (uint y = h - 1; y < h; --y){ for (uint x = 0; x < _w; ++x){ is.read(reinterpret_cast<char*>(&index), 1); for (auto& t : root.Color){ if (index == t.first){ imm(x, y)[2] = t.second.B;							imm(x, y)[1] = t.second.G;							imm(x, y)[0] = t.second.R;						} }                  if (x < w)					swap(img(x, y), imm(x, y)); }			}		}		else if (bpp == 4){

for (uint y = h - 1; y < h; --y){ for (uint x = 0; x < _w; ++x){ unsigned index=br(4); for (auto& t : root.Color){ if (index == t.first){ for (uint i = 0; i <= 1; ++i){ if (x + i >= 0 && x + i < w){ imm(x+i, y)[2] = t.second.B;									imm(x+i, y)[1] = t.second.G;									imm(x+i, y)[0] = t.second.R;								} }						}					}					if (x < w)						swap(img(x, y), imm(x, y)); }			}		}		else if (bpp == 1){

for (uint y = h - 1; y < h; --y){ for (uint x = 0; x < _w; ++x){ unsigned index = br(1); for (auto& t : root.Color){ if (index == t.first){ for (uint i = 0; i <= 7; ++i){ if (x + i >= 0 && x + i < w){ imm(x + i, y)[2] = t.second.B;									imm(x + i, y)[1] = t.second.G;									imm(x + i, y)[0] = t.second.R;								} }

}					}					if (x < w)						swap(img(x, y), imm(x, y)); }			}		}

}

writeP6(outputFilename, img);

return EXIT_SUCCESS; }

void Syntax{ cout << "Syntax:\n"; cout << "bmp2ppm <input file .BMP> <output file .PPM>\n"; cout << "\n"; }

int main(int argc, char* argv[]){

if (argc != 3){ Syntax; return EXIT_FAILURE; }	else return bmp2ppm(argv[1],argv[2]); }

lzw
int compress(const string& sInputFilename,const string& sOutputFilename) {

ifstream is(sInputFilename,ios::binary); if (!is) exit(EXIT_FAILURE); is.unsetf(ios::skipws);

ofstream os(sOutputFilename, ios::binary); bitwriter bw(os);

auto it = istream_iterator (is); vector c_v(it, istream_iterator ); unordered_map<string, int> compress_dictionary(MAX_DEF); //Dictionary initializing with ASCII for (int unsigned i = 0; i < 256; i++){ compress_dictionary[string(1, i)] = i;	} string current_string; unsigned int next_code = 256; //Output file for compressed data for (const auto& c: c_v){ current_string = current_string + c;		if (compress_dictionary.find(current_string) == compress_dictionary.end){ if (next_code <= MAX_DEF) compress_dictionary.insert(make_pair(current_string, next_code++)); current_string.erase(current_string.size - 1); bw.write((compress_dictionary[current_string]), 9); cout << compress_dictionary[current_string]<<"\n"; current_string = c;		} }	if (current_string.size){ bw.write((compress_dictionary[current_string]), 9); cout << compress_dictionary[current_string] << ","<<"\n"; }	os.close;

return EXIT_SUCCESS; }

void decompress(const string& sInputFilename,const string& sOutputFilename) {

ifstream is(sInputFilename, ios::binary); if (!is) exit(EXIT_FAILURE);

bitreader br(is);

ofstream os(sOutputFilename, ios::binary); bitwriter bw(os);

unordered_map<uint, string> dictionary(MAX_DEF); //Dictionary initializing with ASCII for (uint i = 0; i < 256; i++){ dictionary[i] = string(1, i); }	string previous_string; uint code; uint next_code = 256; while (!is.eof){

code = br(9); if (dictionary.find(code) == dictionary.end) dictionary.insert(make_pair(code, (previous_string + previous_string.substr(0, 1)))); os << dictionary[code]; if (previous_string.size) dictionary.insert(make_pair(next_code++, previous_string + dictionary[code][0])); previous_string = dictionary[code]; if (is.eof) break; }	os.close; }

dct/idct

 * 1) ifndef TRASFORMATA_H
 * 2) define TRASFORMATA_H


 * 1) include "image.h"


 * 1) include
 * 2) include

typedef unsigned char byte; using namespace std;
 * 1) define _USE_MATH_DEFINES
 * 2) include <math.h>

image DCT(image & img){ image coeff(img.width, img.height); //Scalo tutti i coefficenti di -128 for (size_t y = 0; y < img.height; y++){ for (size_t x = 0; x < img.width; x++){ img(x, y) -= 128; }	}

int offset = 0; int blocchi_letti = 0; int count = 0; unsigned num_blocco = img.width*img.height / 64; for (size_t i = 0; i <num_blocco; i++){ if (blocchi_letti == 64){ offset = offset + 7; blocchi_letti = 0; }		for (unsigned v = 0; v < 8; v++){ for (unsigned u = 0; u < 8; u++){ double Suv = 0; double Cu = (u == 0) ? 0.7071 : 1;				double Cv = (v == 0) ? 0.7071 : 1;				for (unsigned y = 0; y < 8; y++){ for (unsigned x = 0; x < 8; x++){ Suv += img(x + i * 8, y + offset)*cos(((2 * x + 1)*u*M_PI) / 16.0)*cos(((2 * y + 1)*v*M_PI) / 16.0);

}				}

Suv = 0.25*Cu*Cv*Suv; //Suv -= 128; coeff(u + i * 8, v + offset) = (int)Suv; //std::cout << '\r' << count++; }		}

++blocchi_letti; }

return coeff; }

image IDCT(image & img){ image imgant(img.width, img.height); int offset = 0; int blocchi_letti = 0; int count = 0; unsigned num_blocco = img.width*img.height / 64; for (size_t i = 0; i <num_blocco; i++){ if (blocchi_letti == 64){ offset = offset + 7; blocchi_letti = 0; }		for (unsigned y = 0; y < 8; y++){ for (unsigned x = 0; x < 8; x++){ double Sxy = 0.0;

for (unsigned v = 0; v < 8; v++){ for (unsigned u = 0; u < 8; u++){ double Cu = (u == 0) ? 0.7071 : 1;						double Cv = (v == 0) ? 0.7071 : 1;						Sxy += Cu*Cv*img(u + i * 8, v + offset)*cos(((2 * x + 1)*u*M_PI) / 16.0)*cos(((2 * y + 1)*v*M_PI) / 16.0); }				}

Sxy *= 0.25; //Sxy += 128; imgant(x + i * 8, y + offset) = (byte)Sxy;

std::cout << '\r' << count++;

}

}		++blocchi_letti; }

//Aggiungo 128 a tutti i coefficenti for (size_t y = 0; y < imgant.height; y++){ for (size_t x = 0; x < imgant.width; x++){ imgant(x, y) += 128; }	}

return imgant; }


 * 1) endif // TRASFORMATADCT_H

bitstreams

 * 1) ifndef BITSTREAMS_H
 * 2) define BITSTREAMS_H


 * 1) include

class bitwriter { std::ostream& _os; unsigned char _buffer; int _bits;

// Aggiunge il bit meno significativo di u al buffer void write_bit(unsigned u) { _buffer = (_buffer << 1) | (u & 1); if (++_bits == 8) { _os.put(_buffer); _bits = 0; }	}

// Non si deve né copiare né assegnare! bitwriter(const bitwriter&); bitwriter& operator= (const bitwriter&);

public: bitwriter(std::ostream& os) : _os(os), _bits(0) {}

// Scrive sul bitstream i count bit meno significativi di u	void operator (unsigned u, unsigned count) { while (count > 0) write_bit(u >> --count); }

// Svuota il buffer sul file void flush(unsigned fill_bit = 0) { while (_bits > 0) write_bit(fill_bit); }

/* Metodo per scrivere un unsigned int codificato con un numero di bits dato */ void write(unsigned num, unsigned bits) { while (bits) { --bits; write_bit((num >> bits) & 1); }	}

/* Metodo per scrivere un char */ void write(char car) { unsigned tmp = (unsigned)car; tmp = tmp & 0xff; write(tmp, 8); }

~bitwriter { flush; } };

class bitreader { std::istream& _is; unsigned char _buffer; int _bits;

// Aggiunge il bit meno significativo di u al buffer unsigned read_bit { if (_bits == 0) { _is.get(reinterpret_cast<char&>(_buffer)); _bits = 8; }		return (_buffer >> --_bits) & 1; }

// Non si deve né copiare né assegnare! bitreader(const bitreader&); bitreader& operator= (const bitreader&);

public: bitreader(std::istream& is) : _is(is), _bits(0) {}

operator std::istream& { return _is; }

// Legge dal bitstream i count bit richiesti e li mette nei bit meno significativi del risultato unsigned operator (unsigned count) { unsigned u = 0; while (count-- > 0) u = (u<<1) | read_bit; return u;	}

// Lettura in little endian template <class T>	void read_endian(T& n, unsigned len){ n = 0; T val = 0; for (unsigned i = 0; i < len; ++i){ val = _is.get; n += val << (8 * i); }	}

/* Metodo per leggere un unsigned int codificato con un numero di bits dato */ unsigned read(unsigned bits) { unsigned out = 0; while (bits) { --bits; unsigned bit = (unsigned)read_bit; bit = bit << bits; out += bit;

}		return out; }

/* Metodo per leggere un char */ unsigned char readChar { return (unsigned char)read(8); } };


 * 1) endif // BITSTREAMS_H

lz78
int LZ78encode(uint max_bits, const string& inputFilename, const string& outputFilename){

ifstream is(inputFilename, ios::binary); if (!is) return EXIT_FAILURE;

ofstream os(outputFilename, ios::binary); if (!os) return EXIT_FAILURE;

/* Lettura dati */ is.seekg(0, ios::end); unsigned size = (unsigned)is.tellg; is.seekg(0, ios::beg);

/* Scrittura header file destinazione */ bitwriter bw(os); os << "LZ78";

// numero massimo di bits da usare bw(max_bits,5);

/* Compressione */ unsigned cursor = 0; Trie* dictionary = new Trie; while (cursor < size) { unsigned pos = 0; unsigned dict_code = 0; unsigned temp = 0; string s;		unsigned char data_cursor = is.get; unsigned char data_cursor_pos = data_cursor; s.append(1, data_cursor); while ((temp = dictionary->search(s)) && size - (unsigned)is.tellg > 0) { pos++; dict_code = temp; data_cursor_pos = is.get; s.append(1, data_cursor_pos); }

bw.write(dict_code, num_bit(dictionary->getNum - 1)); bw.write(data_cursor_pos);

dictionary->add(s); cursor += pos + 1;

if (dictionary->getNum - 1 == (1<<max_bits)) { delete dictionary; dictionary = new Trie; }	}

/* Chiusura file */ bw.flush; return EXIT_SUCCESS; }

int LZ78decode(uint max_bits, const string& inputFilename, const string& outputFilename){

ifstream is(inputFilename, ios::binary); if (!is) return EXIT_FAILURE;

ofstream os(outputFilename, ios::binary); if (!os) return EXIT_FAILURE;

/* Lettura header file destinazione */ bitreader br(is); string sMagic(4, ' '); is.read(&sMagic[0], 4); /* Lettura dati */ is.seekg(0, ios::end); unsigned size = (unsigned)is.tellg; is.seekg(0, ios::beg);

uint m = br(5);

/* Decompressione */ unsigned cursor = 0; vector dictionary; string* null = new string; dictionary.push_back(*null);

while (cursor < size) { unsigned pos = 0; unsigned dict_code = br(num_bit(dictionary.size - 1)); if (dict_code > dictionary.size - 1) { cout << "Cercavo il codice " << dict_code << " ma il dizionario e' grande " << dictionary.size << endl; system("pause"); break; exit(11); }		string* s = new string(dictionary.at(dict_code)); unsigned char c = br.readChar; s->push_back(c);

os << *s;

dictionary.push_back(*s); cursor += s->length;

if (dictionary.size - 1 == (1 << max_bits)) { dictionary.clear; string* null = new string; dictionary.push_back(*null); }	}

return EXIT_SUCCESS; }

trie.h
using namespace std;
 * 1) include
 * 2) include
 * 3) include

class Node { private: char _mContent; unsigned _num; vector<Node*> _mChildren;

public: Node(unsigned num):_num(num),_mContent(' ') {} ~Node { for ( unsigned i = 0; i < _mChildren.size; i++ ) {			delete _mChildren.at(i); }		_mChildren.clear; }	char content { return _mContent; }

void setContent(char c) { _mContent = c; 	} Node* Node::findChild(char c)	{ for ( unsigned i = 0; i < _mChildren.size; i++ ) {			Node* tmp = _mChildren.at(i); if ( tmp->content == c ) {				return tmp; }		}

return NULL; }

void appendChild(Node* child) { _mChildren.push_back(child); }

vector<Node*> children { return _mChildren; }

unsigned num { return _num; } };

class Trie { private: Node* _root; unsigned _num;

public: Trie:_num(0) {		_root = new Node(_num); _num++; }	~Trie { delete _root; };

void add(string s)	{ Node* current = _root; if ( s.length == 0) return; for ( unsigned i = 0; i < s.length; i++ ) {       			Node* child = current->findChild(s[i]); if ( child != NULL ) {				current = child; }		   else {				Node* tmp = new Node(_num); _num++; tmp->setContent(s[i]); current->appendChild(tmp); current = tmp; }		}	}

unsigned search(string s)	{ Node* current = _root; for ( unsigned i = 0; i < s.length; i++ ) {			Node* tmp = current->findChild(s[i]); if ( tmp == NULL ) return false; current = tmp; }

return current->num; }

unsigned getNum { return _num; }

};

lz77_prof
int encode(size_t max_size, string infilename, string outfilename){

ifstream is(infilename, ios::binary); if (!is) exit(EXIT_FAILURE);

// Leggo l'input vector<uint8_t> input; uint8_t val; while (read(is, val)) input.push_back(val);

// Preparo il file di output ofstream os(outfilename, ios::binary); os << "LZ77"; bitwriter bw(os); bw(max_size, 16);

for (size_t cur = 0; cur < input.size; ++cur) { // Cerco l'occorrenza più lunga dell'input nel dizionario size_t max_match_len = 0; size_t max_pos = 0; size_t start = cur>max_size ? cur - max_size : 0; for (size_t pos = start; pos < cur; ++pos) { size_t match_len; for (match_len = 0; cur + match_len < input.size - 1; ++match_len) { if (input[pos + match_len] != input[cur + match_len]) break; }			if (match_len>0 && max_match_len <= match_len) { max_match_len = match_len; max_pos = pos; }		}

size_t P = max_match_len > 0 ? cur - max_pos : 0; size_t L = max_match_len; uint8_t C = input[cur + max_match_len];

cout << "(" << P << "," << L << "," << C << ")\n";

// Scrivo la posizione bw(P+1, eliasbits(P + 1)); // Se la posizione è maggiore di 0, scrivo la lunghezza if (P>0) bw(L, eliasbits(L)); // Scrivo il byte bw(C, 8);

cur += max_match_len; }

return EXIT_SUCCESS; }

struct terna{ size_t P=0; size_t L=0; unsigned char C;

size_t get_p{ return P; } size_t get_l{ return L; } unsigned char get_c{ return C; }

terna{}

vector leaves;

bool read(istream& is){ terna el; bitreader br(is); while (true){ el.P = read_elias(br); if (--el.P > 0) el.L = read_elias(br); el.C = br(8);

leaves.emplace_back(el);

if (is.eof) break; }		return true; } };

int decode(string infilename, string outfilename){

ifstream is(infilename,ios::binary); if (!is) exit(EXIT_FAILURE);

bitreader br(is);

string sMagic(4, ' '); is.read(const_cast<char*>(sMagic.data),4); uint16_t max_size = br(16); terna root; root.read(is); for (const auto& x : root.leaves){ cout << "(" << x.P << "," << x.L << "," << x.C << ")" << "\n"; }

unsigned cur = 0; vector<uint8_t> c_v; for (auto& x:root.leaves){ if (x.get_l==0) c_v.push_back(x.get_c); else{ for (size_t j = 0; j < x.get_l; ++j) c_v.push_back(c_v[cur - x.get_p + j]); c_v.push_back(x.get_c); }		cur = c_v.size; }	ofstream os(outfilename, ios::binary); for (const auto& x :c_v){ os << x;	}

return EXIT_SUCCESS; }