Image Smoother - Problem
Imagine you're working with image processing software and need to implement a blur effect! An image smoother is a filter that reduces noise and creates a softer appearance by averaging pixel values.
Given an m x n integer matrix img representing the grayscale values of an image, you need to apply a 3x3 smoothing filter to each cell:
- For each cell, calculate the average of the cell itself and its 8 surrounding neighbors
- If some neighbors don't exist (edge/corner cells), only use the available cells in the average
- Round down the result using integer division
Return the smoothed image matrix where each cell contains the averaged value of its neighborhood.
Think of it like applying a blur effect in photo editing software - each pixel becomes the average of itself and its neighbors!
Input & Output
example_1.py โ Basic 3x3 Matrix
$
Input:
img = [[1,1,1],[1,0,1],[1,1,1]]
โบ
Output:
[[0,0,0],[0,0,0],[0,0,0]]
๐ก Note:
For the center cell (1,1) with value 0: neighbors are [1,1,1,1,0,1,1,1,1], sum=8, count=9, average=8//9=0. Corner cells have fewer neighbors but follow same logic.
example_2.py โ Different Values
$
Input:
img = [[100,200,100],[200,50,200],[100,200,100]]
โบ
Output:
[[137,141,137],[141,138,141],[137,141,137]]
๐ก Note:
Center cell: (100+200+100+200+50+200+100+200+100)/9 = 1250/9 = 138. Corner cells average 4 neighbors, edge cells average 6 neighbors.
example_3.py โ Single Cell Edge Case
$
Input:
img = [[36]]
โบ
Output:
[[36]]
๐ก Note:
Single cell has no neighbors, so it averages only itself: 36/1 = 36. This demonstrates proper handling of matrices with no actual neighbors.
Constraints
- m == img.length
- n == img[i].length
- 1 โค m, n โค 200
- 0 โค img[i][j] โค 255
- Each cell value represents a grayscale pixel (0-255)
Visualization
Tap to expand
Understanding the Visualization
1
Select Target Pixel
Choose the pixel to smooth (center of 3x3 window)
2
Gather Neighborhood
Collect values from the 3x3 grid around the target pixel
3
Handle Boundaries
For edge/corner pixels, only use available neighbors
4
Calculate Average
Sum all valid neighbors and divide by count, rounding down
5
Apply to All Pixels
Repeat this process for every pixel in the image
Key Takeaway
๐ฏ Key Insight: Image smoothing is essentially a convolution operation with a 3x3 averaging filter. The algorithm naturally handles edge cases through boundary checking, and the O(mรn) time complexity is optimal since every pixel must be processed exactly once.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code