Hands-on 2b

Reading Data (Image)

In this exercise we will write a C++ program that reads a data file and interprets its data. representing an image. To help you with the program development, a program reading a data file with a similar, but different format is provided. Your task is to adapt the provided program to read the image data.

The image data file image.txt, that will be processed in this exercise, is defined as a simple text file (called ASCII) and it contains the description of a single image on the screen. The image data contains the values of grayness level for each pixel on the screen. See an example:

Example of an image

The size of an image may vary that’s why we have to read the width and the height of the image first in order to know the number of pixels to be read:

  • The width of the image follows the format:
WIDTH number
  • The height of the image follows the format:
HEIGHT number
  • The pixels of the image follow the format:
p[0][0]  p[1][0]  p[2][0] ...
p[0][1]  p[1][1]  p[2][1] ...
p[0][2]  p[1][2]  p[2][2] ...
  • In addition, the image description is framed between keywords IMAGE and END_IMAGE.

Reading a file word by word

  • Open readCar_v0.cxx in your editor, compile it and run the program. Open also the provided files car.txt and image.txt and observe the data formats.

  • Copy readCar_v0.cxx in a new file readImage.cxx, modify the code so that the program opens image.txt dat, build and run the program.

Add a function

  • Open readCar_v1.cxx in your editor, compile it and run the program.

  • In this new version, the code for reading a file was moved in a function. Modify your readImage.cxx and add a function in a similar way.

Interpreting data

  • Open readCar_v2.cxx in your editor, compile it and run the program.

  • In this new version, there are introduced variables in readCar() which are suitable to represent the data in the car.txt file. Note also the meaning of key which is used to intrepret the data.

  • Modify your readImage.cxx, introduce variables to represent the data in the image.txt file.

The result of reading

  • Add a new data line in car.txt just before the line with END_CAR key word and run your program again. For example

    OWNER Your name

The added data were just read in without being saved in any variable.

  • Open ‘readCar_v3.cxx` in your editor, compile it and run the program. The new program will detect that the new data are preceded with an unknown key word. Inspect the code which was added on the top of the previous version for this:

    • The return type of readCar() was changed from void to bool

    • Two else{ } code blocks were added in the if statement

    • A boolean variable result was added in main() and according to its value a message about a success or a failure is issued.

  • Update you readImage.cxx in a similar way and run your program with both the original and modified versions of the data file.