Applying a Filter to an Image

Instructions

In this activity, you must write a program in RISC-V assembly language that reads an image in PGM format from a file, applies an edge detection filter and shows the result on screen using the canvas peripheral.

The first step of this exercise is to read an image in the PGM format and store its content in a matrix (exactly as done in exercise 6.4). After that, you must apply the following filter on the image:

$$ w = \begin{bmatrix} -1 & -1 & -1 \\\ -1 & 8 & -1 \\\ -1 & -1 & -1 \end{bmatrix} $$

Assuming \(w\) the filter matrix above, \(M_{in}\) the matrix representing the input image, and \(M_{out}\) the matrix representing the output image. The basic idea of applying the filter is that each \(M_{out}\) pixel[i, j] is defined as:

$$ M_{out}[i][j] = \sum_{k=0}^{2} \sum_{q=0}^{2} w[k][q] * M_{in}[i+k-1][j + q - 1] $$

Note that this can lead to the \(M_{in}\) matrix to be indexed with invalid indices (negative or out of bounds). In order to avoid these cases, the border pixels of the image \(M_{out}\) must be initialized with black and it is not necessary to compute the filter value for them. You can visualize how this filter works in Image Kernels explained visually (select the "outline" filter). This filter is also known as the Laplacian operator for edge detection.

Also note that the image pixels must have values between 0 (black) and 255 (white). If the result of the equation presented above is not in this interval, you must use the closest value in the interval (i.e., values lower than 0 become 0, and values greater than 255 become 255).

Input

Your program must read a file called "image.pgm" that will be in the same directory as the executable file, as explained in Exercise 6.4.

Output

Your program must show the result image on the screen, using the Canvas peripheral, as explained in Exercise 6.4.

Notes and Tips

  • You need to resize the canvas (setCanvasSize syscall) according to the file header.
  • Remember to correctly concatenate the pixel's colors in register a2 when using the setPixel syscall, as explained in Exercise 6.4. The output will be in gray scale, so use the same values for the colors (R = G = B) and alpha = 255.
  • You can test your code using the simulator's assistant from this link.