So once the novice programmer is comfortable with dealing with small pieces of data, the purview of problems can be extended to say deal with 2D data such as simple monochromatic images. So let’s look at the “noise” problem. Some images can contain a type of noise called “impulse” or salt-and-pepper noise – random black (0) and white (255) pixels. Below is an (extreme) example of noise on a small image of a dome:
In this case, the algorithm is again a simple one, based on median filtering the image. This involves looking at each pixel in the image, calculating the median value of some region around that pixel, and then assigning this value to a new image in the same location. This could be explained i using some form of diagram showing how a picture is made up of individual pixels. Basically a median filter removes “extreme” pixels, which could represent the noise.
- Read in a monochrome image called noisyimage.txt (it’s a simple text image), and store it in a 2D array (matrix).
- Find the size of the [image] array, and create a new array to store the “cleaned” image.
- For every element (pixel) in the 2D array, select a 3×3 neighbourhood around the pixel, and calculate the median value.
- Assign this median value as the new pixel in the output image.
- Write the output image in a file called cleanimage.txt.
An important part of experiential learning with respect to programming is also program comprehension. So instead of creating the code, from the algorithm it is also possible to provide the code and allow students to read the code and try and associate the parts of the code with the parts of the algorithm. The Julia program to perform this noise suppression is only 9 lines in length. Here is what the program looks like:
imgIn = readdlm("noisyimage.txt",Int16::Type) dx, dy = size(imgIn) imgOut = zeros(dx,dy) for i=2:dx-1, j=2:dy-1 block = imgIn[i-1:i+1,j-1:j+1] newPixel = median(block) imgOut[i,j] = trunc(UInt8,newPixel) end writedlm("cleanimage.txt",imgOut)
Colour-coding helps to associate like regions of code. For example, the code in red here is associated with input/output, blue with setting data up, and purple with actually performing the median filtering.