# Image Smoother in C++

C++Server Side ProgrammingProgramming

Suppose we have a 2D matrix M representing the gray scale of an image, we have to design a smoother to make the gray scale of each pixel becomes the average gray scale (rounding down) of all the 8 surrounding pixels and itself. If a cell has less than 8 surrounding cells, convert all possible pixels.

So, if the input is like

 1 1 1 1 0 1 1 1 1

then the output will be

 0 0 0 0 0 0 0 0 0

To solve this, we will follow these steps −

• R := row count of M

• C := column count of

• Define an array d = { -1, 0, 1 }

• Define one 2D array res of size (R x C)

• for initialize i := 0, when i < R, update (increase i by 1), do −

• for initialize j := 0, when j < C, update (increase j by 1), do −

• sum := 0, count := 0

• for initialize k := 0, when k < 3, update (increase k by 1), do −

• for initialize l := 0, when l − 3, update (increase l by 1), do −

• m := i + d[k], n := j + d[l]

• if m >= 0 and m < R and n >= 0 and n < C, then −

• increase count by 1 and sum = sum + M[m, n]

• res[i, j] := sum / count

• return res

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
int R = M.size();
int C = M.size();
vector<int> d{ -1, 0, 1 };
vector<vector<int> > res(R, vector<int>(C, 0));
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
int sum = 0, count = 0;
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
int m = i + d[k], n = j + d[l];
if (m >= 0 && m < R && n >= 0 && n < C) ++count, sum += M[m][n];
}
}
res[i][j] = sum / count;
}
}
return res;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{1,1,1},{1,0,1},{1,1,1}};
print_vector(ob.imageSmoother(v));
}

## Input

{{1,1,1},{1,0,1},{1,1,1}}

## Output

[[0, 0, 0, ],[0, 0, 0, ],[0, 0, 0, ],]