A grayscale image is a rectangle of pixels, and each pixel is a single number: 0 is black, 255 is white,
and everything between is a shade of grey. A rectangle of numbers is exactly what a two-dimensional array
is, which is why image processing is the natural place to learn them.
Everything in this lab is the same small idea applied repeatedly: read the numbers in, change them, write
them back out. What differs from task to task is only which numbers you change and what you change them
to.
A two-dimensional array is declared with two size declarators, and an element is selected with two
subscripts:
const int MAX_H = 512;
const int MAX_W = 512;
int image[MAX_H][MAX_W];
image[row][col] = 255; // make one pixel white
Row first, column second. Row 0 is the top of the picture and column 0 is the left edge, so image[0][0]
is the top-left pixel. Getting these the wrong way round is the characteristic bug of this lab, and it
usually shows up as a picture that is mangled rather than a program that crashes.
Traversing all of it means a loop inside a loop — the outer one walking rows, the inner one walking the
columns of that row:
for (int row = 0; row < h; row++)
{
for (int col = 0; col < w; col++)
{
// do something with image[row][col]
}
}
We use PGM (portable graymap), because the code to read and write it is short enough to read in a
minute. A PGM file is plain text: the characters P2, then the width, the height, the maximum pixel value,
and then all the pixel values in order, row by row. Open inImage.pgm in a text editor and you will see
exactly that.
Download the image and the starter file:
To look at a .pgm file you need a viewer that understands it. On the lab machines, eog (Eye of Gnome)
works:
eog inImage.pgm
If you want to use your own picture instead, convert will turn an ordinary image into PGM and back:
convert -compress none dog.png inImage.pgm
convert outImage.pgm output-dog.png
lab-images.cpp contains two functions. Do not modify them — they work, and they are not what this lab
is about.
// Reads inImage.pgm into the array.
// height and width are passed by reference: the function fills them in.
void readImage(int image[MAX_H][MAX_W], int &height, int &width);
// Writes the first height x width elements of the array to outImage.pgm.
void writeImage(int image[MAX_H][MAX_W], int height, int width);
Look at the parameter lists. For a two-dimensional array parameter the column size must be given — the
compiler needs it to know where one row ends and the next begins. The row size may be left out, so
int image[][MAX_W] would work equally well. And as in Lab 6, the array is not copied: these functions write
into your array.
height and width are reference parameters, the technique from Lab 3, because readImage has to report
two values back and return only carries one.
Here is the fact that governs every task below. The array is always 512 × 512, because its size is fixed
when the program is compiled. The picture inside it is 250 × 194. The rest of the array is untouched
memory holding whatever was there before.
This is a partially filled array: a fixed container plus a count of how much of it is real. You met the
one-dimensional version in Lab 6, where a file of scores went into a 20-element array and count recorded
how many arrived. The rule is the same in two dimensions, and it is the reason h and w are passed to
every function and appear in every loop condition.
It is also why you must never hard-code 250 or 194. Your programs should work on any picture that fits.
Nothing to submit for this one.
Compile and run lab-images.cpp as given. Its main reads the picture, copies the array into a second
array, and writes that out. Look at outImage.pgm and confirm it is identical to the original.
That round trip is the skeleton of all six programs below. Each one replaces the copying loop with something
more interesting.
A note on the six copies. Every program in this lab needs
readImageandwriteImage, so you will be
pasting them into six files. That duplication is exactly the problem Lab 5 solved with a header file and
separate compilation, and if this were your own project that is how you would do it. We keep the copies
here only so each program can be submitted and compiled on its own.
Write invert.cpp, which turns the picture into its photographic negative. Black becomes white, white
becomes black, and every shade in between flips: 0 → 255, 1 → 254, … 255 → 0. That is one
expression; work out what it is.
Then write invert-half.cpp, which inverts only the right half of the picture and leaves the left
half alone. The dividing column is w / 2, not 125.
Write stats.cpp, which changes nothing and writes no output file. It reads the picture and reports on
it: the dimensions, the darkest pixel, the brightest pixel, and the average brightness.
These are the array algorithms from section 8.6 — scanning for a highest and lowest value, and accumulating
a running total — now applied to two dimensions. Remember that the average must divide by w * h and that
the sum is an int, so convert before dividing:
static_cast<double>(sum) / (w * h)
Also build a histogram: a 256-element array where count[v] is the number of pixels having the value
v. This is the tally technique from Lab 6, where the value is its own subscript:
int count[256] = {0};
// ... then, for each pixel:
count[img[row][col]]++;
Report the most common pixel value, and as a self-check, the histogram total — which must equal w * h.
for fits, and where it does notC++11 offers a loop that visits every element without you managing a subscript:
int total = 0;
for (int n : count)
{
total += n;
}
That is the right tool for the histogram total. Every one of the 256 elements is meaningful, and the body
does not need to know which element it is looking at.
It is the wrong tool twice over in this lab. Finding the most common value needs the subscript — the answer
is the index, not the value — so that loop stays an ordinary for. And a range-based for over img would
visit all 512 rows of 512 columns, not the h × w that hold the picture. A range-based for always
visits the whole array, which makes it unusable on a partially filled one.
$ ./stats
Image is 250 wide by 194 high (48500 pixels).
Darkest pixel: 0
Brightest pixel: 255
Average: 171.17
Histogram total: 48500
Most common value: 225 (686 pixels)
Write box.cpp, which paints a solid white rectangle in the middle of the picture, half the width and
half the height of the original.
The arithmetic is the task. The box is w / 2 wide and h / 2 high, and centring it means it starts at
column w / 4 and row h / 4. Derive those from w and h so the program works on any picture.
Then write frame.cpp, which draws the same rectangle as an outline exactly one pixel thick, leaving
the picture inside it visible.
An outline is four runs of pixels: the top edge, the bottom edge, and the two sides. Two loops will do it —
one walking columns, one walking rows.
Write scale.cpp, which doubles the picture in both directions. Each input pixel becomes a 2 × 2 block
of identical pixels in the output:
11 22 -> 11 11 22 22
33 44 11 11 22 22
33 33 44 44
33 33 44 44
(Real scaling interpolates between neighbouring colours. This does not, which is why the result looks
blocky when you zoom in.)
Two things make this task different from the others. You need a second array for the output, because the
result does not fit where the input was. And the call that writes it out must pass the new dimensions:
writeImage(out, 2 * h, 2 * w);
Work out which four elements of out each img[row][col] is responsible for before you write the loop.
Write pixelate.cpp, which replaces every non-overlapping 2 × 2 block with the average of its four
pixels, so all four come out the same:
10 20 30 40 16 16 36 36
11 21 31 41 -> 16 16 36 36
12 22 32 42 18 18 37 37
13 23 33 43 18 18 37 37
The 16 is the average of 10, 20, 11 and 21, rounded down by integer division.
The loops step by 2 rather than by 1, since you move a block at a time, not a pixel at a time. Assume the
width and height are even — ours are 250 and 194 — so the picture divides exactly into blocks.
A sliding window operator replaces each pixel with a function of its eight neighbours. Label the pixel
e and the 3 × 3 window around it:
. . . . . .
. a b c . .
. d e f . .
. g h i . .
. . . . . .
Write kernel.cpp, which detects horizontal edges using
f(a,b,c,d,e,f,g,h,i) = (g + 2h + i) − (a + 2b + c)
This compares the row below the pixel with the row above it. Where they are similar the result is near zero
and the output is black; where they differ sharply — an edge — the result is large and the output is bright.
It is one half of the Sobel operator.
Four things to get right:
img, later pixels will be computed fromwriteImage will stop with an error.Submit the seven source files, plus kernel.cpp if you did the bonus:
invert.cpp invert-half.cpp stats.cpp box.cpp
frame.cpp scale.cpp pixelate.cpp kernel.cpp (bonus)
Do not submit the images or the compiled executables. Each program should start with a comment containing
your name and a short description, for example:
/*
Author: your name
Course: CSCI-135
Instructor: their name
Assignment: Lab 9
Here, briefly, at least in one or a few sentences
describe what the program does.
*/