Question: Question: I have errors in my Python code and would need help fixing them. The instruction that I followed to complete the coding is given
Question: I have errors in my Python code and would need help fixing them. The instruction that I followed to complete the coding is given below which is followed by my code for the instruction.
Instructions implement 2-dimensional (2D) convolution in python. Your convolution function should have two input variables, 2D image, and 2D kernel (filter). It should accept any size 2D input image as well as any size 2D kernel as input. The kernel must be a square matrix and the dimensions of the kernel must be odd such as 3x3, 5x5, or 7x7. However, the input image can be in any size grayscale image.
I have the snippet already but I don't understand the snippet so with an example please explain.
Also the library I used to get the image is from skimage import data. Please do not use 'from scipy.ndimage.filters import convolve' library for the filter as the convolution program must be done from scratch.
I have come up with the code but have multiple errors and need help to fix it.
One of those error was: index 3 is out of bounds for axis 0 with size 3 ---- on line 41: kernal_value = kernel_size[m][n]
from skimage import data from skimage import filters from scipy.ndimage.filters import convolve import numpy import cv2 import numpy as np import matplotlib.pyplot as plt import math
#Step 1: get the image image = data.camera()
#display the image plt.figure(1) plt.imshow(image, cmap='gray') plt.title("Input image")
def convolve(image, kernel): #kernel = np.flipud(np.fliplr(kernel)) #flip an array up and down image_value = np.zeros_like(image) #Return an array of zeros with the same shape and type as a given array. #Step 2: Padding the image based on the kernel filter size (3x3) image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2)) image_padded[1:-1, 1:-1] = image windsize = 3 half_windsize = math.floor(windsize/2) kernel_size = np.array([[3,3,3],[3,3,3],[3,3,3]]) kernel = kernel_size/2 value = 0 #for image for i in range(0, image.shape[1]): for k in range(0, image.shape[0]): #for kernel for m in range (0, windsize**2): for n in range (0, windsize**2): # element-wise multiplication of the kernel and the image image_value = image[i+m-half_windsize][k*n-half_windsize] kernal_value = kernel_size[m][n] value+=image_value*kernal_value #imagefilter[i,j] = (kernel * image_padded[k: k+3, i: i+3]).sum() return value
kernel_size = np.array([[3,3,3],[3,3,3],[3,3,3]]) img = convolve(image, kernel_size) plt.figure(2) plt.imshow(img, cmap = "gray") plt.title("Output image")
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
