Exemple #1
0
void HuffmanOp::operator()(const imagein::Image* image, const std::map<const imagein::Image*, std::string>&) {
    Huffman huff;
    GrayscaleImage* grayImg = Converter<GrayscaleImage>::convert(*image);
    string res = huff.execute(grayImg);
    outText(res);
    delete grayImg;
}
Exemple #2
0
int main(int argc, char *argv[]){
  //start a clock for poor mans profiling
  clock_t start = clock();
  //print out an error if there no file is provided
  if (argc <= 1) {
    cout << "Usage: " << argv[0] << " <Filename>" << endl;
    exit(1);
  }
  //Open file
  char* in_filename = argv[1];
  ifstream ifs (in_filename);
  //print error if file is not found
  if(!ifs.good()){
    cout<< "File " << argv[1] << " not found" << endl;
    exit(1);
  }
  //if the file is good load the whole thing into a string called content
  string file_content( (std::istreambuf_iterator<char>(ifs) ),(std::istreambuf_iterator<char>()    ) );
  ifs.close();
  Huffman* h = new Huffman();
  //determine our output file name
  string temp = in_filename;
  int pos = temp.find('.');
  string out_filename =  temp.substr(0, pos) + ".zip301";
  //compress and save out file
  h->compress_zip301(file_content, out_filename);
  clock_t end = clock();
  cout << "Time Elapsed:" << (double)(end-start)/CLOCKS_PER_SEC<< "s" << endl;
  return 0;
}
Exemple #3
0
void testobject::test<1>()
{
	Huffman huffman;
 	ensure("no strings in", huffman.getStrings()->size()==0 );
 	string str("Hello World!");
 	huffman.addString(str);
 	ensure("added 1 string", huffman.getStrings()->size()==1 );
 	huffman.finalize();
 	ensure("dict should contain something", huffman.getDict()->size()>0 );
 	ensure("dict should contain something", huffman.getDictRev()->size()>0 );
 	char buf[300];
 	int ul = str.length();
 	int pl = huffman.encryptString(str,buf);
 	string s = huffman.decryptString(buf, pl, ul);
 	ensure("decrypt(encrypt(s))==s", s==str);
 	
 	short serializee[300];
 	int size = huffman.serialize( serializee );
 	ensure("serializee should contain something", size>0 );
 	
 	Huffman h2;
 	h2.deserialize(serializee, size, 1 );
 	s = h2.decryptString(buf, pl, ul);

 	ensure("decrypt(encrypt(s))==s", s==str);
}
Exemple #4
0
int main(int argc, char **argv) {
    
    // Read the huffman tree at the beginning of the file
    Huffman<char> huff;
    huff.read_tree(std::cin);
    // huff.dump_tree(std::cerr);

    // read the encoded file bit by bit. With every new bit,
    // move one level down the huffman tree. When we reach a leaf,
    // emit the symbol and start over. The process expects to
    // be terminated by an explicit sentinel.
    BitReader bit_reader(std::cin);
    Huffman<char>::Node* state = nullptr;
    char symbol;
    while ( bit_reader ) {
        int bit = bit_reader.read_bit();
        bool symbol_complete = huff.read_huff_bit(bit, state, symbol);
        // std::cerr << bit << " -> " << state->bits;
        // if ( symbol_complete ) {
        //     std::cerr << " \"" << symbol << "\"";
        // }
        // std::cerr << std::endl;
        
        if ( symbol_complete ) {
            if ( symbol == '\0' ) {
                // we've reached the sentinel value, stop immediately.
                return 0;
            } else {
                std::cout << symbol;
            }
        }
    }
    
    return 1;
}
Exemple #5
0
int main()
{
    char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'k'};
    int freq[] = {5, 9, 12, 13, 16, 45, 21};
    int size = sizeof(arr)/sizeof(arr[0]);
    Huffman huff;
    huff.HuffmanCodes(arr, freq, size);
    return 0;
}
Exemple #6
0
void Compressor::compress(string in, string out)
{
    size = Utils::getFileSize(in);
    //cout << "size : " << size << endl;
    char c;
    string temp = "";
    ifstream infile;
    infile.open(in, ios::binary | ios::in);
    while(!infile.eof()) {
        infile.read(&c, 1);
        charCpt++;

        float f = (float)charCpt / (float)size;
        if( f * 100 > nbBar) {
            nbBar++;
            Utils::drawProgressBar("compressing : ", nbBar);
        }

        if(index >= pow(2, ENCODING_LENGTH)) {
            m->clear();
            initDico();
            index = 256;
        }
        temp = pair(w, c);
        if(m->find(temp) != m->end()) {
            w = temp;
        } else {
            m->insert(std::pair<string, long>(temp, (long)index));
            index++;
            long n = m->at(w);
            //cout << "c : " << n << endl;
            if(huffman) {
                chars->push_back(n);
                computeOufman(n);
            } else {
                result += std::bitset<ENCODING_LENGTH>(n).to_string();
            }
            w = pair("", c);
        }
    }
    if(huffman) {
        computeOufman(m->at(w));
        chars->push_back(m->at(w));
        Huffman *h = new Huffman(oufman);
        result = h->convertToString(chars);
    } else {
        result += std::bitset<ENCODING_LENGTH>(m->at(w)).to_string();
        string encodingLength = std::bitset<8>(ENCODING_LENGTH).to_string();
        result = encodingLength + result;
    }
    writeResult(out);
}
Exemple #7
0
int main(){

	string frase = "how i met your mother";
	
	Huffman coder = new Huffman(frase);

	coder.showDictionary();

	cout << coder.codedSentence() << endl;


	return 0;
}
Exemple #8
0
int main() {
  Huffman h;
  Encoded e = h.encode("MISSISSIPPI");

  std::cout << "Input: MISSISSIPPI" << std::endl;
  std::cout << e.encoded_string << std::endl;
  std::cout << e.serialized_tree << std::endl;

  std::cout << "Input: A man a plan, a canal, Panama!" << std::endl;
  Encoded a = h.encode("A man a plan, a canal, Panama!");
  std::cout << a.encoded_string << std::endl;
  std::cout << a.serialized_tree << std::endl;

}
Exemple #9
0
int main(int argc, char * argv[], char * envp[])
{
	int i;
	int cflag = 0;
	int eflag = 0;

	while((i = getopt(argc, argv, "c:e:h")) != -1) {
		switch(i) {
			case 'c':
				cflag = 1;
				break;

			case 'e':
				eflag = 1;
				break;

			default:
				usage();
				exit(1);
		}
	}

	if(cflag ^ eflag) {

		try
		{
			if(cflag)
			{
				Huffman *file = new Huffman();
				file->compress(argv[2]);
			} else {
				Huffman *file = new Huffman();
				file->extract(argv[2]);
			}
		} catch(std::exception &e)
		{
			std::cout << e.what() << std::endl;
		}
	} else {
		usage();
		exit(1);
	}

	exit(0);
}
Exemple #10
0
int main(int argc, char *argv[]) {
    if (argc != 4 || ((strcmp(argv[1], "-c") != 0) && (strcmp(argv[1], "-r") != 0))) {
        cout << "Usage:" << endl;
        cout << "To compress:" << "nscomp -c input_file output_file" << endl;
        cout << "To uncompress:" << "nscomp -r input_file output_file" << endl;
        return 0;
    }

    if (strcmp(argv[1], "-c") == 0) {
        Huffman hf(argv[2]);
        hf.Compress(argv[2], argv[3]);
    }

    if (strcmp(argv[1], "-r") == 0) {
        Huffman hf;
        hf.Uncompress(argv[2], argv[3]);
    }
}
Exemple #11
0
void DropArea::dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();

    QString text1;
    QList<QUrl> urlList = mimeData->urls();
    for (int i = 0; i < urlList.size() && i < 32; ++i)
        text1.append(urlList.at(i).toString() + QLatin1Char(' '));
    /*!
    \brief File adress is attached to the text.
    */
    char direccionEntradaTemp [1024];
    char direccionEntrada [1024];
    strcpy(direccionEntradaTemp, text1.toStdString().c_str() );
    /*!
    \brief Then it is converted to a c String so the Huffman.cpp can process it correctly, when given to it.
    */
    size_t i;
    for( i = 7; i < text1.toStdString().length() - 1; i++ )
    {
        direccionEntrada[i-7] = direccionEntradaTemp[i];
    }
    direccionEntrada[i-7] = '\0';
    /*!
    \brief Before accepting a compression, the Adress is checked to be valid.
    */
    if( isValid(direccionEntrada) )
    {
        text1 =direccionEntrada;
        Huffman huffmanCom;
        huffmanCom.start(direccionEntrada);
    }else
    {
        text1 ="Data extension is invalid";
    }

    setText( text1 );
    setTextFormat(Qt::PlainText);
    setBackgroundRole(QPalette::Dark);
    event->acceptProposedAction();
}
Exemple #12
0
int main(int argc, char **argv) {
    char c;
    std::ifstream ifs(argv[1], std::ifstream::in);
    std::vector<int> *samples = new std::vector<int>(26, 0);

    while (ifs.good()) {
        c = ifs.get();

        (*samples)[c-'A']++;
    }

    ifs.close();

    Huffman huff;

    huff.generate_tree(samples);

    huff.print_codes();

    return 0;
}
Exemple #13
0
int main(int argc, char *argv[]) {
  if(argc < 4) {
    showHelp();
    return 1;
  }

  Huffman* hm = new Huffman();

  if(string(argv[1]) == string("-e")) {
    string* input = new string();
    ifstream file;
    file.open(argv[2], ios::in);

    stringstream buffer;
    buffer << file.rdbuf();
    *input = buffer.str();

    if(input->size() == 0)
      return 0;

    input->erase(input->end() - 1, input->end());

    hm->compress(input->c_str(), input->size());
    hm->writeToFile(argv[3]);

    if(input != NULL)
      delete input;
  }else if(string(argv[1]) == string("-d")) {
    string header;
    unsigned int overflow;
    std::vector<bool>* input = new std::vector<bool>();

    Huffman::prepareCompressed(header, input, overflow, argv[2]);

    hm->setOverflow(overflow);
    hm->setEncoding(hm->parseEncoding(header));
    hm->decompress(input);

    hm->writeToStringFile(argv[3]);
    if(input != NULL)
      delete input;
  }else{
    showHelp();
    return 1;
  }

  delete hm;

  return 0;
}
Exemple #14
0
int main(int argc, char **argv) {
    
    // read everything from stdin
    std::vector<char> input(
       (std::istreambuf_iterator<char>(std::cin.rdbuf())),
       std::istreambuf_iterator<char>()
    ); 
    
    // add a null terminator as a sentinal
    input.push_back('\0');
    
    // calculate the Huffman encoding tree
    Huffman<char> huff;
    for ( auto& c : input ) {
        huff.add_symbol(c);
    }
    huff.build_tree();
    // huff.dump_tree(std::cerr);

    huff.write_tree(std::cout);

    // write out the encoded file
    BitWriter bit_writer(std::cout);
    for ( auto& c : input ) {
        auto bits = huff.symbol_to_bits(c);
        // std::cerr << "symbol \"" << c << "\" -> " << bits << std::endl;
        for ( auto& b : bits ) {
            if ( b == '0' ) {
                bit_writer.write_bit(0);
            } else {
                bit_writer.write_bit(1);
            }
        }
    }
    bit_writer.flush();
    
    return 0;
}
int main () {
    Huffman H;
    char Table[26];
    memset(Table, 0, sizeof(Table));
    cout << "enter a sentence: \n";

    string line;
    getline(cin, line);
    for (auto ch:line) {
        ch = tolower(ch);
        if (ch >= 'a' && ch <= 'z') {
            ++Table[ch - 'a'];
        }
    }

    H.build(Table);
    H.print();
    H.draw();
    cout << "Press q to quit: ";
    string usr_input;
    getline(cin,usr_input);
    if (usr_input == "q") exit(0);
}
Exemple #16
0
int main(int argc, char ** argv){

	if (argc != 3){
		cout << "Usage:"<< endl;
		cout << "   huff (-e|-d) <filename>" << endl;
    cout << "     -e     encode <filename>" << endl;
    cout << "     -d     decode <filename>" << endl;
		return -1;
	}

	int table[256];
	Huffman *huff = new Huffman();

	string option = argv[1];
	cout << "Option: " << option << endl;

	if (option.compare("-e") == 0){

		Node * nodes[256];

		//Calculate the frequencies of each possible character. 
		huff->calcFreqs(argv[2], table);

		//Convert this table to nodes representing each character and it's frequency. 
		huff->freqsToNodes(table, nodes);

		SortNodes(nodes);

		huff->BuildTree(nodes);

		huff->calcEncodings(nodes[255]);
		/*
			 for (int i = 0; i < 256; i++){
			 cout << i << ": " << encodings[i] << endl;
			 }		
			 */
		huff->Compress(argv[2]);
		for (int i = 0; i < 256; i++){
			cout << i << ": " << encodings[i] << endl;
		}

	}else if (option.compare("-d") == 0){
		string filename = argv[2];
		cout << filename << endl;
		huff->Decode(filename);
	}
}
Exemple #17
0
int derp()
{
	//testing huffmanqueue
	cout << "what";

	HuffmanQueue<HuffmanTreeNode, NodeComp> queue;
	
	Huffman tm;

	map<char, int> TextMap = tm.GetMap();
	map<char, int>::iterator it = tm.GetIterator();
	//priority_queue<HuffmanTreeNode*, deque<HuffmanTreeNode*>, NodeComp> queue;
	HuffmanTreeNode *t;

	for(it = TextMap.begin(); it!=TextMap.end(); it++)
	{
		t = new HuffmanTreeNode(it->first, it->second);
		queue.push(t);
	}

	do
	{

		HuffmanTreeNode *temp;
		HuffmanTreeNode * ref1 = queue.top();
		queue.pop();
		if(!queue.empty())
		{
			HuffmanTreeNode * ref2 = queue.top();
			queue.pop();
			temp = new HuffmanTreeNode(NULL, ref1->getFreq() + ref2->getFreq());
			temp->SetLeftNode(ref1);
			temp->SetRightNode(ref2);
		}else
		{
			temp = new HuffmanTreeNode(NULL, ref1->getFreq());
			temp->SetLeftNode(ref1);
			temp->SetRightNode(NULL);
		}

		queue.push(temp);

	}while(queue.size()!=1);

	HuffmanTree* tree = new HuffmanTree(queue.top());

	tree->BuildMap(queue.top());
	//tree->GetChars(queue.top());

	cout << "Printing Map \n";
	tree->printMap();

	string x = tree->Encrypt("go go gophers");

	cout<<"Encrypting 'go go gophers' . :: "<<x<<endl<<endl;

	tree->Compress(x);


	cout<<"Decrypting '"<<x<<"' . :: "<<tree->Decrypt(x)<<endl;

	system("pause");
	return 0;
}
int main(){
	Huffman test;
	while(test.Read())
		test.Solve();
	return 0;
}
Exemple #19
0
int main(int argc, char *argv[]){
    QTime t;
    t.start();
    //START APP
    QApplication app(argc,argv);
    app.setWindowIcon(QIcon(":/data/img/11412394_407750046078820_6932822019341529347_n.jpg"));
    QApplication::setApplicationName("Huffman");
    QApplication::setApplicationVersion("ÚNICO");
    QQmlApplicationEngine engine;
    QQmlContext *interpreter = engine.rootContext();
    Huffman huff;
    DHuffman deHuff;
    QCommandLineParser parser;
    //Parser
    parser.addHelpOption();
    parser.addVersionOption();
    parser.setApplicationDescription("Huffman Parsers");
    parser.addPositionalArgument("in-file.x", QCoreApplication::translate("main", "File being compressed."));
    parser.addPositionalArgument("out-name.huff", QCoreApplication::translate("main", "Name to save archive."));
    //parser.addPositionalArgument("dir", QCoreApplication::translate("main", "Dir being compressed"));
    parser.addPositionalArgument("local", QCoreApplication::translate("main", "Local to save archive."));
    QCommandLineOption compress("c",QApplication::translate("main","Compress <in-file.x>."),
                                QApplication::translate("main","in-file.x"));
    parser.addOption(compress);
    QCommandLineOption outName("o",QApplication::translate("main","Save as <out-name.huff>."),
                               QApplication::translate("main","out-file.huff"));
    parser.addOption(outName);
    QCommandLineOption local("d",QApplication::translate("main","Decompress in <local>."),
                             QApplication::translate("main","local"));
    parser.addOption(local);
    QCommandLineOption startGui({"g", "gui"},QApplication::translate("main","Start gui."));
    parser.addOption(startGui);
    parser.process(app);

    //ARGUMENTS
    if(parser.isSet(startGui)){
        interpreter->setContextProperty("_huff",&huff);
        interpreter->setContextProperty("_dehuff",&deHuff);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    }
    else if(parser.isSet(compress) && parser.isSet(outName))
    {
        cout << "case 1" << endl;
        huff.Huff(parser.value(compress),parser.value(outName));
    }
    else if(parser.isSet(compress))
    {
        cout << "case 2" << endl;
        huff.Huff(parser.value(compress),parser.value(compress));
    }
    else{
        if(app.arguments().size() == 1)
            qDebug() << qPrintable(parser.helpText());
        else if(parser.isSet(local))
            deHuff.DHuff(app.arguments().at(1),parser.value(local));
        else
            deHuff.DHuff(app.arguments().at(1),app.arguments().at(1));
    }
    //END APP
    qDebug("%s <> Tempo de execução: %d ms",Q_FUNC_INFO,t.elapsed());
    return app.exec();
}
Exemple #20
0
int wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ])
{
  printf("Start....\n");
  x_sys_print_compiler();
  xCpuInfo CpuInfo;
  CpuInfo.checkCPIUD();
  CpuInfo.printCpuInfo();
  CpuInfo.checkCompatibility();

  /*
  Bossy.
  Wejscie:
  Obraz w formacie .bmp o rozmiarach podzielnych przez 8.
  */

  //Wczytywanie pliku i sprawdzenie wymiarow. 
  FILE_HANDLE InputFile = x_fopen(TEXT("samochody_1920x1080_0538.bmp"), TEXT("r"));
  xImg* InputImage = new xImg;
  InputImage->getBMP(InputFile);

  int SizeX = InputImage->m_Cmp[0]->m_SizeX;
  int SizeY = InputImage->m_Cmp[0]->m_SizeY;

  if (SizeX % 8 || SizeY % 8)
  {
	  cout << "Error";
	  return 0;
  }

  //Konwersja z RGB na YUV.
  xImg* ImageYUV = new xImg;
  ImageYUV->create(SizeX, SizeY, 0, 8, ImgTp_YUV, CrF_444, ClrSpc_BT709, 0);
  ImageYUV->convertRGB2YUV(InputImage);

  //Pozbywanie sie wartosci sredniej.
  for (int i = 0; i < SizeX; i++)
  {
	  for (int j = 0; j < SizeY; j++)
	  {
		  ImageYUV->m_Cmp[0]->m_Pel[j][i] -= 128;
		  ImageYUV->m_Cmp[1]->m_Pel[j][i] -= 128;
		  ImageYUV->m_Cmp[2]->m_Pel[j][i] -= 128;
	  }
  }

  //Tworzenie makroblokow 8x8: obraz, po DCT, po kwantyzacji.
  //Luma
  xCmp* macroblock = new xCmp;
  xCmp* macroblockDCT = new xCmp;
  xCmp* macroblockQuant = new xCmp;
  macroblock->create(8, 8, 0, 8);
  macroblockDCT->create(8, 8, 0, 11);
  macroblockQuant->create(8, 8, 0, 11);

  //cb
  xCmp* cb_macroblock = new xCmp;
  xCmp* cb_macroblockDCT = new xCmp;
  xCmp* cb_macroblockQuant = new xCmp;
  cb_macroblock->create(8, 8, 0, 8);
  cb_macroblockDCT->create(8, 8, 0, 11);
  cb_macroblockQuant->create(8, 8, 0, 11);

  //cr
  xCmp* cr_macroblock = new xCmp;
  xCmp* cr_macroblockDCT = new xCmp;
  xCmp* cr_macroblockQuant = new xCmp;
  cr_macroblock->create(8, 8, 0, 8);
  cr_macroblockDCT->create(8, 8, 0, 11);
  cr_macroblockQuant->create(8, 8, 0, 11);

  //Tablice kwantyzacji, pobieranie z pliku.
  xCmp* quantLuma = new xCmp();
  xCmp* quantChroma = new xCmp();

  quantLuma->create(8, 8, 0, 8);
  quantChroma->create(8, 8, 0, 8);

  ifstream fileQuantLuma;
  ifstream fileQuantChroma;
  fileQuantLuma.open("QuantLuma.txt", ios::binary);
  fileQuantChroma.open("QuantChroma.txt", ios::binary);

  int tempQuant;
  for (int i = 0; i < 8; i++)
  {
	  for (int j = 0; j < 8; j++)
	  {
		  fileQuantLuma >> tempQuant;
		  quantLuma->m_Pel[i][j] = tempQuant;
		  fileQuantChroma >> tempQuant;
		  quantChroma->m_Pel[i][j] = tempQuant;
	  }
  }
  
  int prevDC = 0;
  int prevDC_cb = 0;
  int prevDC_cr = 0;

  int tempPrevDC = 0;
  int tempPrevDC_cb = 0;
  int tempPrevDC_cr = 0;
  Huffman* huff = new Huffman();
  //Podzial obrazu na makrobloki 8x8.
  for (int y = 0; y < SizeY/8; y++)
  {
	  for (int x = 0; x < SizeX/8; x++)
	  {
		  for (int i = 8*y; i < (8*y)+8; i++)
		  {
			  for (int j = 8*x; j < (8*x)+8; j++)
			  {
				  macroblock->m_Pel[i % 8][j % 8] = ImageYUV->m_Cmp[0]->m_Pel[i][j];
				  cb_macroblock->m_Pel[i % 8][j % 8] = ImageYUV->m_Cmp[1]->m_Pel[i][j];
				  cr_macroblock->m_Pel[i % 8][j % 8] = ImageYUV->m_Cmp[2]->m_Pel[i][j];
			  }
		  }
		  //Wyliczanie DCT dla kazdego makrobloku, dla kazdej skladowej.
		  DCT(macroblock, macroblockDCT);
		  DCT(cb_macroblock, cb_macroblockDCT);
		  DCT(cr_macroblock, cr_macroblockDCT);

		  //Kwantowanie.
		  Quant(macroblockDCT, macroblockQuant, quantLuma);
		  Quant(cb_macroblockDCT, cb_macroblockQuant, quantChroma);
		  Quant(cr_macroblockDCT, cr_macroblockQuant, quantChroma);
			
		  //ZigZag.
		  int tabRL[64];
		  int cb_tabRL[64];
		  int cr_tabRL[64];
		  ZygZak2RL(macroblockQuant, tabRL);
		  ZygZak2RL(cb_macroblockQuant, cb_tabRL);
		  ZygZak2RL(cr_macroblockQuant, cr_tabRL);
		  /*
		  Bossy.
		  Wyjscie:
		  Tablcia int 64 - elementowa dla kazdego makrobloku i dla kazdej skladowej.
		  Uporzadowanie zygzakowate zgodne z rys. 7.3. na stronie 356 w ksiazce "Obraz cyfrowy"
		  */

		  //RL
		  int tabRL2[64 * 2] = { 0 };
		  int tabRL2_cb[64 * 2] = { 0 };
		  int tabRL2_cr[64 * 2] = { 0 };
		  int numOfData, numOfDataCB, numOfDataCR;

		  numOfData = RL(tabRL, tabRL2);
		  numOfDataCB = RL(cb_tabRL, tabRL2_cb);
		  numOfDataCR = RL(cr_tabRL, tabRL2_cr);

		  //Kodowanie DC ró¿nicowe
		  tempPrevDC = tabRL2[0];
		  tabRL2[0] =tabRL2[0] - prevDC;
		  prevDC = tempPrevDC;

		  tempPrevDC_cb = tabRL2_cb[0];
		  tabRL2_cb[0] = tabRL2_cb[0] - prevDC_cb;
		  prevDC_cb = tempPrevDC_cb;

		  tempPrevDC_cr = tabRL2_cr[0];
		  tabRL2_cr[0] = tabRL2_cr[0] - prevDC_cr;
		  prevDC_cr = tempPrevDC_cr;

		  //Kodowanie Huffman 
		  //DC luma
		  int bitLen = 0;
		  string* encodeData=new string();
		  huff->encodeDC(tabRL2[0], encodeData,bitLen);
		  //AC luma
		  for (int i = 1; i < numOfData; i += 2)
		  {
 			  huff->encodeAC(tabRL2[i], tabRL2[i + 1], encodeData, bitLen);
		  }
		 
		  //DC CB
		  huff->encodeDC(tabRL2_cb[0], encodeData, bitLen);
		  //AC CB
		  for (int i = 1; i < numOfDataCB; i += 2)
		  {
			  huff->encodeAC(tabRL2_cb[i], tabRL2_cb[i + 1], encodeData, bitLen);
		  }
		 
		  //DC CR
		  huff->encodeDC(tabRL2_cr[0], encodeData, bitLen);
		  //AC CR
		  for (int i = 1; i < numOfDataCR; i += 2)
		  {
			  huff->encodeAC(tabRL2_cr[i], tabRL2_cr[i + 1], encodeData, bitLen);
		  }
		//Dekodowanie Huffman
		  int DecodetabRL2[64 * 2] = { 0 };
		  int DecodetabRL2_cb[64 * 2] = { 0 };
		  int DecodetabRL2_cr[64 * 2] = { 0 };
		//DC Luma
		  if (encodeData->size() != 0)
		  huff->decodeDC(*encodeData,DecodetabRL2);
		//AC Luma
		  if (encodeData->size() != 0)
		  huff->decodeAC(*encodeData, DecodetabRL2);
		//DC CB
		  if (encodeData->size()!=0)
		  huff->decodeDC(*encodeData, DecodetabRL2_cb);
		//AC CB
		  if (encodeData->size() != 0)
		  huff->decodeAC(*encodeData, DecodetabRL2_cb);
		//DC CR
		  if (encodeData->size() != 0)
		  huff->decodeDC(*encodeData, DecodetabRL2_cr);
		//AC CR
		  if (encodeData->size() != 0)
		  huff->decodeAC(*encodeData, DecodetabRL2_cr);
		 //D_RL
		  
	  }
  }



  system("pause");
  return EXIT_SUCCESS;
}
Exemple #21
0
/**
  * Saves a DWT file
  */
void DWT::save(const string &fileName)
{
	FILE *fHan = fopen(fileName.data(), "wb");

	// Header
	fwrite(&magic, 1, 2, fHan);
#ifdef __BIG_ENDIAN__
	// Correct endianness for writing
	bpp = swap_endian32(bpp);
	realWidth = swap_endian32(realWidth);
	realHeight = swap_endian32(realHeight);
#endif
	fwrite(&bpp, sizeof(bpp), 1, fHan);
	fwrite(&realWidth, sizeof(int), 1, fHan);
	fwrite(&realHeight, sizeof(int), 1, fHan);
#ifdef __BIG_ENDIAN__
	// Revert endianness
	bpp = swap_endian32(bpp);
	realWidth = swap_endian32(realWidth);
	realHeight = swap_endian32(realHeight);
#endif

	// Drops half of the padding when writing
	unsigned int stopHeight = height - (height - realHeight)/2;
	unsigned int stopWidth = width - (width - realWidth)/2;
	unsigned int stopPrHeight = stopHeight * PREVIEW / height;
	unsigned int stopPrWidth = stopWidth * PREVIEW / width;

	// Looking for the highest absolute value in the transformation, used for quantization
	float maxAbsValF = 0;
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++){
			if (i >= PREVIEW || j >= PREVIEW) {
				if (abs(coeff[i*width+j]) > maxAbsValF) maxAbsValF = abs(coeff[i*width+j]);
			}
		}
	}
	int maxAbsVal = round(maxAbsValF);
	cout << "maxValue: " << maxAbsVal << endl;
	fwrite(&maxAbsVal, sizeof(int), 1, fHan);

	const float C = ((1 << (bpp-1))-1)/(float)(maxAbsVal);	// Range value
	const float M = (1 << (bpp-1));							// Added to get only positive values
	float W = 1, w = 1/sqrt(2);							// Factor of multiplication for preview
	for (unsigned int i = PREVIEW; i < height; i <<= 1) W *= w;
	for (unsigned int i = PREVIEW; i < width; i <<= 1) W *= w;

	// Huffman, searching for occurrences in the quantization
	unsigned int *occ = new unsigned int[1 << bpp];
	memset(occ, 0, (1 << bpp)*sizeof(int));
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++){
			if (i >= PREVIEW || j >= PREVIEW) {
				float quant = coeff[i * width + j] * C;
				if (abs(quant) >= .5f)
					occ[range(round(quant + M))]++;
			}
		}
	}
	Huffman *huffman = new Huffman(bpp);
	huffman->buildTree(occ, 1<<bpp);
	delete[] occ;

	// Encoding of the preview
	for (unsigned int i = 0; i < stopPrHeight && i < PREVIEW; i++) {
		for (unsigned int j = 0; j < stopPrWidth && j < PREVIEW; j++) {
			unsigned char l = coeff[i*width + j] * W;
			fwrite(&l, 1, 1, fHan);
		}
	}

	// Encoding of the rest of the transform, using Huffman and RLE
	int zeros = 0;
	bit_file_t *bf = MakeBitFile(fHan, BF_APPEND);
	huffman->setFile(bf);
	huffman->writeTree();
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++) {
			if (i >= PREVIEW || j >= PREVIEW) {
				bool zero = abs(coeff[i*width + j]*C) < .5f;
				if (zero) zeros++;
				if (!zero || (i==stopHeight-1 && j==stopWidth-1)) {
					if (zeros != 0) {
						// RLE: a sequence of zeros has been found
						if (zeros <= 8) {
							unsigned int n = zeros-1;
							BitFilePutBit(1, bf);
							BitFilePutBit(0, bf);
							BitFilePutBitsInt(bf, &n, 3, sizeof(n));
						} else {
							while (zeros > 0) {
								unsigned int n = zeros > 256 ? 255 : zeros-1;
								BitFilePutBit(1, bf);
								BitFilePutBit(1, bf);
								BitFilePutBitsInt(bf, &n, 8, sizeof(n));
								zeros -= 256;
							}
						}
						zeros = 0;
					}
					if (i!=stopHeight-1 || j!=stopWidth-1) {
						// Huffman: write a quantized and then Huffman-encoded value
						unsigned int l = range(round(coeff[i*width + j]*C + M));
						BitFilePutBit(0, bf);
						huffman->writeSymbol(l);
					}
				}
			}
		}
	}
	BitFileFlushOutput(bf, 0);
	delete huffman;

	fclose(fHan);
}
Exemple #22
0
/**
  * Loads a DWT file
  */
void DWT::load(const string &fileName)
{
	// Open file and read magic number
	FILE *fHan = fopen(fileName.data(), "rb");
	char thisMagic[2];
	fread(thisMagic, 1, 2, fHan);
	if (magic[0] != thisMagic[0] || magic[1] != thisMagic[1]) {
		cerr << "Unrecognized file format for " << fileName << endl;
		exit(1);
	}

	// Read header
	fread(&bpp, sizeof(bpp), 1, fHan);
	fread(&realWidth, sizeof(int), 1, fHan);
	fread(&realHeight, sizeof(int), 1, fHan);
#ifdef __BIG_ENDIAN__
	bpp = swap_endian32(bpp);
	realWidth = swap_endian32(realWidth);
	realHeight = swap_endian32(realHeight);
#endif

	// Calculate padded width and height
	width = 1;
	while (width < realWidth) width <<= 1;
	height = 1;
	while (height < realHeight) height <<= 1;

	// Drops half of the padding when reading
	unsigned int stopHeight = height - (height - realHeight)/2;
	unsigned int stopWidth = width - (width - realWidth)/2;
	unsigned int stopPrHeight = stopHeight * PREVIEW / height;
	unsigned int stopPrWidth = stopWidth * PREVIEW / width;

	cout	<< "bpp: " << bpp << endl
			<< "width: " << width << endl
			<< "height: " << height << endl
			<< "realWidth: " << realWidth << endl
			<< "realHeight: " << realHeight << endl;

	coeff = new float[width * height];
	int maxAbsVal;
	fread(&maxAbsVal, sizeof(int), 1, fHan);
	cout << "maxValue: " << maxAbsVal << endl;

	const float C = ((1 << (bpp-1))-1)/(float)(maxAbsVal);	// Range value
	const float M = (1 << (bpp-1));							// Added to get only positive values
	float W = 1, w = 1/sqrt(2);							// Factor of multiplication for preview
	for (unsigned int i = PREVIEW; i < height; i <<= 1) W *= w;
	for (unsigned int i = PREVIEW; i < width; i <<= 1) W *= w;

	// Reading the preview
	for (unsigned int i = 0; i < stopPrHeight && i < PREVIEW; i++) {
		for (unsigned int j = 0; j < stopPrWidth && j < PREVIEW; j++) {
			unsigned char l;
			fread(&l, 1, 1, fHan);
			coeff[i*width + j] = l/W;
		}
	}

	// Reading the rest of the transform, decoding Huffman and RLE
	unsigned int zeros = 0;
	bit_file_t *bf = MakeBitFile(fHan, BF_READ);
	Huffman *huffman = new Huffman(bpp);
	huffman->setFile(bf);
	huffman->readTree();
	for (unsigned int i = 0; i < stopHeight; i++) {
		for (unsigned int j = 0; j < stopWidth; j++) {
			if (i >= PREVIEW || j >= PREVIEW) {
				int l = 0;
				if (zeros > 0) {
					coeff[i * width + j] = 0;
					zeros--;
				} else {
					bool seq0 = BitFileGetBit(bf);
					if (seq0) {
						// RLE: read the number of coefficents to set to 0 and set the first
						coeff[i * width + j] = 0;
						bool cod8 = BitFileGetBit(bf);
						if (cod8) {
							BitFileGetBitsInt(bf, &zeros, 8, sizeof(zeros));
						} else {
							BitFileGetBitsInt(bf, &zeros, 3, sizeof(zeros));
						}
					} else {
						// Huffman: read coefficent and dequantize it
						l = huffman->readSymbol();
						coeff[i*width + j] = (l-M)/C;
					}
				}
			}
		}
	}
	delete huffman;

	fclose(fHan);
}
int main(int argc, char ** argv) {
    /*Estruturas utilizadas para contar o tempo de execução do programa*/
    struct timeval inicio;
    struct timeval fim;
    /* Verifica se os argumentos (argc e argv) foram digitados corretamente */
    if ((argc < 3) || (argc > 4)) {
        cout << "Uso: huffman [opção] [arq_origem] [arq_destino]" << endl;

        return 1;
    }

    /* Verifica se existe arquivo de origem */
    if (verificaArquivo(argv[2])) {
        return 1;
    }
    gettimeofday(&inicio, NULL);
    if (strcmp(argv[1], "-c") == 0) {
        /* Instancia o objeto a compactar */
        Arquivo * compactar;

        compactar = new Arquivo(argv[2]);
        int k = 0;
        char* fileName = argv[2];
        char* original;
        while (argv[2][k]!= '\0')
            k++;
        original = (char*) malloc(k+1);
        k=0;
        while (argv[2][k]!= '\0'){
            original[k] = argv[2][k];
            k++;
        }
        k++;
        original[k] = '\0';
        k = 0;
        /* Conta caracteres do arquivo */
        compactar -> contaCaracteres();
        /*Cria objeto para a classe Estatistica e retira as frequencias de valor 0 da lista
         * de frequencia */
        Estatistica * estatistica = new Estatistica();
        estatistica -> filtraFrequencia(compactar -> getTamanhoVetorAscii(), compactar -> getFrequenciaCaracteres());

        Huffman * codifica = new Huffman(compactar->getTamanhoArquivoOrigem());
        codifica -> encodeHuffman(estatistica -> getFrequenciaAscii());
        codifica -> criaCodigo(codifica -> getRoot(), codifica -> getCodigoBinario());
        codifica->imprimeTeste(compactar->getTextoOriginal(), compactar->getTamanhoArquivoOrigem());
        if (argc == 3) {
            while (fileName[k] != '\0') {
                k++;
                if (fileName[k] == '.') {
                    fileName[++k] = 'h';
                    fileName[++k] = 'u';
                    fileName[++k] = 'f';
                    fileName[++k] = '\0';
                }
            }
        } else if (argc == 4) {
            fileName = argv[3];
        }
        compactar->gravaArquivoDestino(codifica->getTextoArquivoDestino(), fileName, original);
        gettimeofday(&fim, NULL);
        // Calculando tempo de execução em microsegundos
        double tI = inicio.tv_sec*1000000 + (inicio.tv_usec);
        double tF = fim.tv_sec*1000000  + (fim.tv_usec);
        int comp = ((float)compactar -> getTamanhoArquivoDestino()/(float)compactar -> getTamanhoArquivoOrigem())*100;
        //Informações mostradas ao usuário
        cout << "Arquivo compactado........... : " << fileName << endl;
        cout << "Tamanho do arquivo original.. : " << compactar -> getTamanhoArquivoOrigem() << " bytes" << endl;
        cout << "Tamanho do arquivo compactado : " << compactar -> getTamanhoArquivoDestino() << " bytes" << endl;
        cout << "Taxa de compactação.......... : " << comp << "%" << endl;
        cout << "Média de bits por caractere.. : " << codifica -> getMediaBits() << endl;
        printf("Tempo consumido.............. : %.f ms", (tF-tI)/1000);
        cout << endl;
    }/*Descompacta arquivo*/
    else if (strcmp(argv[1], "-d") == 0) {
        Arquivo * descompactar;
        int k = 0;
        descompactar = new Arquivo(argv[2]);
        char* fileName = argv[2];


        descompactar->leArquivoDestino(fileName);
        /*Cria objeto para a classe Estatistica e retira as frequencias de valor 0 da lista
         * de frequencia */
        Estatistica * estatistica = new Estatistica();
        estatistica -> filtraFrequencia(descompactar -> getTamanhoVetorAscii(), descompactar -> getFrequenciaCaracteres());

        Huffman * decodifica = new Huffman(descompactar->getTamanhoArquivoOrigem());
        //cout << "encode" << endl;
        decodifica -> encodeHuffman(estatistica -> getFrequenciaAscii());
        //cout << "cria codigo" << endl;
        decodifica -> criaCodigo(decodifica -> getRoot(), decodifica -> getCodigoBinario());
        //cout << "decodifica" << endl;
        float z = 0;
        while (decodifica->getStringSize() < descompactar->getTamanhoCaracteresBinarios()) {
            decodifica -> decodeHuffman(decodifica -> getRoot(), descompactar -> getArquivoDescompactado());
            //cout << (z++ / descompactar->getTamanhoCaracteresBinarios())*100 << "%" << endl;
        }
        if (argc == 3) {
            descompactar->gravaArquivoTxt(decodifica->getTextoArquivoDestino());
            gettimeofday(&fim, NULL);
            // Calculando tempo de execução em microsegundos
            double tI = inicio.tv_sec * 1000000 + (inicio.tv_usec);
            double tF = fim.tv_sec * 1000000 + (fim.tv_usec);
            printf("Tempo consumido.............. : %.f ms", (tF - tI) / 1000);
            cout << endl;
        } else {
            cout << "Uso: huffman [opção] [arq_origem] [arq_destino]" << endl;
            return 1;
        }
    } else {
        cout << "Uso: huffman [opção] [arq_origem] [arq_destino]" << endl;
        return 1;
    }
    return 0;
}