Convolutions - Computational Thinking

Hello, I’m trying to follow the computational thinking course to learn Julia unfortunately I am stuck at question 2.2 in homework 2.

This is the exercise is this :


Implement a new method convolve(M, K) that applies a convolution to a 2D array M, using a 2D kernel K. Use your new method extend from the last exercise.
We already have the extend() function :

function extend(M, i, j)
	num_rows, num_columns = size(M)

	i = clamp(i, 1, num_rows)
	j = clamp(j, 1, num_columns)

	return M[i,j]
end

Unfortunately my function convole doesn’t seem to work properly. Here is what I have written so far :

function convolve(M::AbstractMatrix, K::AbstractMatrix)
  
  num_rows_K, num_columns_K = size(K)
  num_rows_M, num_columns_M = size(M)

  length_row = Int((num_rows_K-1)/2)
  length_col = Int((num_columns_K-1)/2)
	
  final = zeros(num_rows_M,num_columns_M)
    
  for row in 1:num_rows_M, col in 1:num_columns_M
    nearest_values = [extend(M, i, j) for i in row - length_row:row + length_row, 
										  j in col - length_col:col + length_col]
    weighted = nearest_values .* K
    total = sum(weighted)
    final[row, col] = total
  end
  return final
end

But is doesn’t work

I have tried to make the same thing in VSCode to make sure that it is working as it should, and I can’t figure out why it is not working since In VSCode

m = [1 1 1; 1 1 1; 1 1 1]
k = [1 1 1; 1 1 1; 1 1 1]

function extend(M, i, j)
	num_rows, num_columns = size(M)

	i = clamp(i, 1, num_rows)
	j = clamp(j, 1, num_columns)

	return M[i,j]
end

function convolve(M::AbstractMatrix, K::AbstractMatrix)
  
  num_rows_K, num_columns_K = size(K)
  num_rows_M, num_columns_M = size(M)

  length_row = Int((num_rows_K-1)/2)
  length_col = Int((num_columns_K-1)/2)
  final = zeros(num_rows_M,num_columns_M)
    
  for row in 1:num_rows_M, col in 1:num_columns_M
    nearest_values = [extend(M, i, j) for i in row - length_row:row + length_row, j in col - length_col:col+length_col]
    weighted = nearest_values .* K
    total = sum(weighted)
    final[row, col] = total
  end
  return final
end

convolve(m, k)

Results in a 3x3 matrix (which is what is expect):
9.0 9.0 9.0
9.0 9.0 9.0
9.0 9.0 9.0

Thank you in advance !

1 Like