Grayscale Filter Convolution
MediumMatrix · Apple
A grayscale image is given as image, a grid of integer pixel values from 0 to 255. kernel is a 3x3 grid of integer weights.
Produce a new image of the same size. Each output pixel at (r, c) is the weighted sum of the 3x3 neighbourhood centred on (r, c):
out[r][c] = sum of kernel[i][j] * image[r + i - 1][c + j - 1] for i, j in 0..2
- Neighbours that fall outside the image count as
0(zero padding). - The kernel is applied as written, without flipping it (this is the "filter" or cross-correlation convention used by most image libraries):
kernel[0][0]weighs the pixel up and to the left. - Finally clamp each sum to the valid pixel range: values below
0become0and values above255become255.
Return the new image; do not modify image.
Example 1
- Input:
- image = [[10, 20, 30], [40, 50, 60]], kernel = [[0, 0, 0], [1, 1, 0], [0, 0, 0]]
- Output:
- [[10, 30, 50], [40, 90, 110]]
- Explanation
- This kernel adds each pixel to the pixel on its left. The first column has nothing to its left (zero padding), so it is unchanged; for example
out[1][2] = 50 + 60 = 110.
Example 2
- Input:
- image = [[100, 100, 100], [100, 120, 100], [100, 100, 100]], kernel = [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]
- Output:
- [[255, 255, 255], [255, 160, 255], [255, 255, 255]]
- Explanation
- This edge detector computes 8 times the pixel minus its neighbours. In the middle that is
8 * 120 - 8 * 100 = 160. A corner has only three real neighbours, so8 * 100 - (100 + 100 + 120) = 480, which clamps to 255.
Example 3
- Input:
- image = [[1, 2], [3, 4]], kernel = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
- Output:
- [[1, 2], [3, 4]]
- Explanation
- The identity kernel only weighs the centre pixel, so every pixel is copied unchanged.
Constraints
1 <= image.length, image[i].length <= 1000 <= image[i][j] <= 255kernelis 3x3 and-10 <= kernel[i][j] <= 10