# Error trying to manually create Gaussian Filter in Python

## Issue

I created a Python code based on a MATLAB code I already had to implement the Gaussian Filter. But when I run the project, I get the following error:

Traceback (most recent call last):
File "C:\Users\gisla\Scilab_PDI\gaussianFilter.py", line 37, in <module>
conv = np.multiply(temp, mascara);
ValueError: operands could not be broadcast together with shapes (4,4,7) (5,5)

The code is this below. The image ‘result.jpg’ is simply a color image that I am trying to filter on. It has no noise because it was just testing if the code would actually modify the image.

import cv2
import matplotlib as plt
from math import e;

I = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

sigma = 1;
# Máscara 5x5
mascara = np.zeros((5,5));
W = 0;

def getExp(n):
return e**n

#Filter
for i in range (1, 5):
for j in range (1, 5):
sq_dist = (i-3)^2+(j-3)^2;
mascara[i,j] = getExp(-1*(sq_dist)/(2*sigma*sigma));
W = W + mascara[i,j];

mascara = mascara/W;

[m,n] = np.shape(I);
saida = np.zeros((m,n), dtype=np.uint8);

for i in range(1, m):
for j in range(1, n):
temp = Im[i:i+4, j:j+4];
temp = np.double(temp);
conv = np.multiply(temp, mascara);
saida[i,j] = np.sum(conv[:])

I don’t know much about Python, so the changes made so far didn’t solve the problem.

## Solution

In the line Im = np.pad(img, [2,2]) you use the padding on the img variable, which is your color image with shape (X, Y, 3) (3 dimensions for R, G and B). If greyscale images is what you want to work with, I think instead you probably want to use your I variable with shape (X, Y), so Im = np.pad(I, [2,2]).

Also please also note that Python indexing works different than Matlab indexing. Indexing starts at 0, you have to change the lines

for i in range(1, m):
for j in range(1, n):
temp = Im[i:i+4, j:j+4]

to

for i in range(0, m):
for j in range(0, n):
temp = Im[i:i+5, j:j+5]