Image Smoother

Given a 2D integer matrix M representing the grayscale of an image, you need to design a smoother to make the grayscale of each cell become the average grayscale (rounding down) of all the 8 surrounding cells and themselves. If a cell has less than 8 surrounding cells, then use as many as you can.

Example:

Input:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
Output:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool isValid(int xint yint nint m)
{
    if (x < 0 || x >= n || y < 0 || y >= m)
        return false;
    return true;
}
int dx[8] = {-1, -1, -101110};
int dy[8] = {-101110, -1, -1};
vector<vector<int>> imageSmoother(vector<vector<int>> &M)
{
    int n = M.size();
    if (n == 0)
        return M;
    int m = M[0].size();
    vector<vector<int>> res(nvector<int>(m0));

    for (int i = 0i < ni++)
    {
        for (int j = 0j < mj++)
        {
            int cnt = 0sum = 0;
            for (int k = 0k < 8k++)
            {
                if (isValid(i + dx[k], j + dy[k], nm))
                {
                    sum += M[i + dx[k]][j + dy[k]];
                    cnt++;
                }
            }
            cnt++;
            sum += M[i][j];

            res[i][j] = sum / cnt;
            cnt = 0;
        }
    }

    return res;
}

int main()
{
    vector<vector<int>> M = {{111},
                             {101},
                             {111}};
    M = imageSmoother(M);
    for (int i = 0i < M.size(); i++)
    {
        for (int j = 0j < M[i].size(); j++)
        {
            cout << M[i][j] << " ";
        }
        cout << "\n";
    }
}


No comments:

Post a Comment