Doubt in the logic of convolution function(topic CNN)

Can you tell me how exactly these lines of code functions and create a filter?
for row in range(W-F+1):
for col in range(H-F+1):
for i in range(F):
for j in range(F):
new_img[row][col] += img[row+i
[col+j]*img_filter[i][j]

hey @Sid10 ,
Just think of any image to be as a matrix of size rows x columns. and along with it we have another small image ( our filter ) which we will be moving all over the image to get some touch of it on the actual image,
Assume , our filter to be of shape 2 x 2 .
Now what we gonna do ,
as we need to all over the image we need to iterate over it , and that can be done as by

for i in range(rows):
—> for j in range(columns):

But if we use this then at a time we will be either leaving the last column and last row or getting out the image. So , to correct it , we just change the code a bit.

for i in range(rows - num_rows_in_filter + 1):
—> for j in range(columns - num_columns_in_filter +1):

So we this we are iterating over each and every row and column .
Now as we want our filter to perform its task , we need to take out a part of actual image equal to size of filter to perform our filter task.
You can do this using numpy also, but we will be implementing it using loops.
So for that , we need to again iterate over a matrix , now a small one as same as filter.
We do it in the same way above :

for i in range(num_rows_in_filter):
—> for j in range(num_columns_in_filter):

Now we used directly the shape of filter as we we know we need to over the same shape.
now we perform our filter task and mulitply each value of this small matrix part of image to its corresponding value available in filter matrix at same position.

In this way we have applied our filter and similarly it goes on to other parts of the image and performs its task .

You can also check out this link, for some more help if needed.

I hope this would have helped you,
Thank You and Happy Learning :slightly_smiling_face:.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.