An image is represented by an m x n integer matrix img where img[i][j] represents the grayscale value of a pixel.
You are tasked with designing a smoother that makes the grayscale of each cell become the average gray scale, rounded down, of the cell itself and the 8 cells surrounding it. If one or more of the surrounding cells of a cell is not present, it is left out of the average.
Return the resulting image matrix after applying the smoother on each cell of img.
Function Signature
def smooth_image(img: list[list[int]]) -> list[list[int]]:
Rules
-
The neighborhood of cell
(i, j)
is the 3x3 window centered on it: every cell
(i + di, j + dj)
with
di
and
dj
in
{-1, 0, 1}
that lies inside the matrix. A corner cell has 4 cells in its window, a non-corner border cell has 6, and an interior cell has 9 (fewer when
m
or
n
is below 3).
-
The new value is
sum // count
over the cells in the window, using integer division that rounds down.
-
Every output cell is computed from the original values of
img
, never from cells that were already smoothed. Return a new
m x n
matrix.
Constraints
-
m == img.length
-
n == img[i].length
-
1 <= m, n <= 200
-
0 <= img[i][j] <= 255
Examples
Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
For corner (0,0) the window is [1,1,1,0], so the value is 3 // 4 = 0. For edge (0,1) it is [1,1,1,1,0,1], so 5 // 6 = 0. For center (1,1) all 9 cells sum to 8, and 8 // 9 = 0.
Input: img = [[100,200,100],[200,50,200],[100,200,100]]
Output: [[137,141,137],[141,138,141],[137,141,137]]
Corner (0,0) averages 100, 200, 200 and 50, giving 550 // 4 = 137. Edge (0,1) averages the top two rows, giving 850 // 6 = 141. Center cell (1,1) becomes (100+200+100+200+50+200+100+200+100) // 9 = 1250 // 9 = 138.
Input: img = [[1,2,3]]
Output: [[1,2,2]]
With a single row, each window has at most 3 cells. The left cell gives (1+2) // 2 = 1, the middle gives (1+2+3) // 3 = 2, and the right gives (2+3) // 2 = 2.