Search code examples
pythonimage-processingnoise-reduction

Image denoising - Performing a task on each element of image matrix


I have been doing image processing lately and I chose Python to be my implementation language.

The Issue

I have two sets of matrices, one being my data matrix (that holds the image's pixel-wise values) and the other is kernel matrix. My requirement is to run over each element of the data matrix (excluding the edges) and calculate the certain value (by using kernel matrix) and replace the original value in data matrix with the calculated value.

Explanation

I have to replace each element with the sum of all the neighbors multiplied by the element in kernel matrix. i.e., d[i][j] = d[i-1][j-1] * k[0][0] + d[i][j-1] * k[0][1]....+ d[i+1][j+1] * k[1][1] considering k to be a 3 x 3 matrix.

My code snippet

data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
kernelMat = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]

rowCount = len(data)
colCount = len(data[0])

for i in range(1, rowCount-1):
    for j in range(1, colCount-1):
        sum = 0
        for x in range(0, 3):
            for y in range(0, 3):
                sum = sum + data[i+x-1][j+y-1] * kernelMat[x][y]
        data[i][j] = sum


Expected output: [[1, 2, 3, 4],
            [5, 0, 0, 8],
            [9, 0, 0, 12],
            [13, 14, 15, 16]] but returning different set of values.

Where I am going wrong? I am new to programming, so pardon me if the question is silly.


Solution

  • To get expected output you just need to change the following line:

    sum = sum + data[i+x-1][j+y-1] * kernelMat[x][y]
    

    to:

    sum = data[i+x-1][j+y-1] * kernelMat[x][y]
    

    Hope it helps!