---
# System prepended metadata

title: Image Processing Classwork

---

# Image Processing Classwork

## 0. Setup
For our library, the image is stored in a 1D array instead of a 2D array. The dimension is 120(width), 160(height)

You can change the image here
![](https://i.imgur.com/RSNzVX8.png)
Any change to the img array will be reflected in the tft

### Modularise the code
It is recommended that your image processing code to be seperated from the main file. To do this, create a seperated header file in inc and source file in src with your prefered name. Then include the header file in the main file and new source file.

After that, make a function in the new files and call it.
![](https://i.imgur.com/JYUjlS8.png)

## 1. Pixel getter
It would be convenient to have a fucntion to get the pixel you wanted. Try to implement it yourself.
```
uint16_t* getPixel(uint16_t img[120*160],uint8_t x, uint8_t y);
```
Try drawing a cross after implementing this function
## 2. Grayscale value
Great, we can access the pixel easily now, time to do some real iamge processing.

Since greyscale is so useful, we may first inplement a function to get the value we need.
<img width="480" alt="RGB565" src="https://www.newton.com.tw/img/7/e01/cGcq5SM0YDM5ADMkJGNxQmZ5QWM0UzMjJjN4AzLtVGdp9yYpB3LltWahJ2Lt92YuUHZpFmYuMmczdWbp9yL6MHc0RHa.jpg">

Bitwise operator would be very useful here.
```
x << 1;     //shift x by 1 bit to the left
x >> 1;     //shift x by 1 bit to the right
x | y;      //bitwise or
x & y;      //bitwise and
```

You can use this template for the function

```
uint8_t colorToGrey(uint16_t pixelValue){

}
```
After implementing this function, modify img so that the printed image on the tft is gray
Hint: You need to tranform the value back to RGB565

## 3. Sobel filter
Now, we have the grayscale value, time to implement a cool filter.
<img width="640" alt="colored" src="https://slideplayer.com/slide/14419272/90/images/8/Sobel+operator+In+practice%2C+it+is+common+to+use%3A+Magnitude%3A.jpg">
```
void sobelFilter(uint16_t img[120*160]){

}
```
Print the edge detection image on the tft

Hints:
Before we do the convolution, we need to save the original value of the image. Otherwise the covolution would be messed up.
However, the image is very big, making a entire copy of the image will crash the program because we dont have a lot of memory for embedded system.
Turns out, you only need to save 2 rows of pixel during the convolution.

Notes:
It is a bad idea to use a filter on every pixels, it takes a lot of time to compute them. Only use filter on the pixel that you need.
