Question: 7. Complete this program, using functions and dynamic memory allocation. The program will create a negative of the image in the original PGM image (providing

7. Complete this program, using functions and dynamic memory allocation. The program will create a negative of the image in the original PGM image (providing that your readPGM and writePGM functions work properly!). Be sure to delete [ ] the array before exiting.

Question: How is it that the function negatePGM(...) can change the actual pixel array, even though the pointer pix is passed by value?

To test your program, I recommend testing initially with a small PGM, such as your initials.pgm from the beginning of the semester. When you have verified that it is working, try it on some of the images from the image archive, available on the course materials web page.

PROGRAM:

#include  #include  #include  #include  using namespace std; string get_filename( ); void readPGM(string fname, int &nc, int &nr, int &mv, int * &pix); void negatePGM(int nc, int nr, int mv, int *pix); void writePGM(string fname, int nc, int nr, int mv, int *pix); //....................................... int main( ) { int ncols=0, nrows=0, maxval=255; int *pix = NULL; // instead of static int pix[1024*1024]; string filename = get_filename( ); readPGM(filename, ncols, nrows, maxval, pix); negatePGM(ncols, nrows, maxval, pix); writePGM("neg_"+filename, ncols, nrows, maxval, pix); // add code to delete the pixel array here! } //....................................... // get the filename of an existing file. string get_filename( ) { bool ok = false; string fn = ""; do { if (fn.size()==0) cout << "filename? "; else cout << "can't open "<> fn; ifstream ifs(fn); // make sure we can open the file. if (ifs) ok = true; } while (!ok); ifs.close(); return fn; } //............................write these two functions: //readPGM: opens file, reads header, allocates pixel array, reads in pixels. //note that nc, nr, mv and pix are all passed by reference. void readPGM(string fname, int &nc, int &nr, int &mv, int * &pix) { // you need to write this! } //....................................... //writePGM: opens output file, outputs header line, outputs pixel array. void writePGM(string fname, int nc, int nr, int mv, int *pix) { // you need to write this ! } //....................................... //negatePGM: note that pix is passed by value. but since it is a pointer, //we can still modify the pixel array by indexing it. why? void negatePGM(int nc, int nr, int maxval, int *pix) { for (int r=0;r 

Name your program pgm_negate.cpp

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!