0

here I am reading a PGM format I want to construct a frequency table for Huffman compression and decompression in C++ how can I extract the output of the picture to make a frequency table with it? should i convert it to text file and read it again taking in consideration i may use this source code

https://github.com/cynricfu/huffman-coding

#include <iostream>
#include <string>
#include <fstream>
#include <sstream> 
using namespace std;

//----------------------------READ IMAGE--------------------------------
void ReadImage(char fname[], int ***fimage, int& M, int& N, int& Q)
{
    int i, j;
    char d;

    char header [100], *ptr;
    ifstream ifp;

    ifp.open(fname, ios::binary);

    if (!ifp)
    {
        cout << "Can't read image: <" << fname << '>' << endl;
        void getch();
        exit(1);
    }

    ifp.getline(header,100,'\n');
    if((header[0]!='P') || header[1]!='5')   /* 'P5' Format */
    {
        cout << "Image <" << fname << "> is not in binary PGM 'P5' format." << endl;
        void getch();
        exit(1);
    }

    ifp.getline(header,100,'\n');
    while(header[0]=='#')
        ifp.getline(header,100,'\n');

    M=strtol(header,&ptr,0);
    N=atoi(ptr);

    ifp.getline(header,100,'\n');

    Q=strtol(header,&ptr,0);

    fimage = new int [N];
    for(i=0; i<N; i++)
        (*fimage)[i] = new int[M];

    for(i=0; i<N; i++)
    {
        for(j=0; j<M; j++)
        {
            d = ifp.get();
            (*fimage)[i][j]= (int)d;
            cout <<j;
        }
        cout <<i;
        }
    }
//-----------------------------Main-------------------------------------
int main()
{
    int i, j;
    int N, M, Q;        // N=Rows   M=Cols   Q=GreyLevels
    int **fimage;       // int **I 2-D Array of Image
    char infile[40];        // name of input file
    char outfile[40];   // name of output image file

    cout << "Enter name of *.pgm INPUT image file: ? ";
    cin  >> infile;
    cout << i<<endl;
    cout <<j<<endl;

    ReadImage(infile, &fimage, M, N, Q);    // Memory created for fimage
}
  • `fimage = new int [N];` is wrong. What you want is an _array of `int*`_ but you allocate an _array of `int`_. Furthermore, you overwrite the passed address to `int **fimage` (from main). I recommend to change this to `*fimage = new int* [N];`. However, it's C++. Why not simply `std::vector` to get away from all this pointer horror? – Scheff's Cat Jun 04 '20 at 06:14
  • Concerning `std::vector`: A `std::vector>` may do the job but even nicer is to use a matrix wrapping just a `std::vector`: [SO: **C++ Matrix Class**](https://stackoverflow.com/a/2076668/7478597) – Scheff's Cat Jun 04 '20 at 06:17

0 Answers0