You can implement a simple 2D convolution function in Python using nested loops to apply the kernel to the image. This function will not handle edge cases (literally), so the output image will be smaller than the input image by the kernel size - 1 on each side.
Here's a simple implementation example using pure Python and numpy arrays:
import numpy as np
from scipy.signal import convolve2d
from PIL import Image
import matplotlib.pyplot as plt
def 2D_convolution(img, kernel):
# Flip the kernel because convolution is actually cross-correlation
kernel = np.flipud(np.fliplr(kernel))
# Get the dimensions of the image and the kernel
image_h, image_w = img.shape
kernel_h, kernel_w = kernel.shape
# Determine the size of the output image
output_h = image_h - kernel_h + 1
output_w = image_w - kernel_w + 1
# Initialize the output image with zeros
new_image = np.zeros((output_h, output_w))
# Apply the kernel to the image
for y in range(output_h):
for x in range(output_w):
new_image[y, x] = np.sum(img[y:y+kernel_h, x:x+kernel_w] * kernel).astype(np.uint8)
return new_image
# The following code is used to test the convolution function
# Opening the image (assuming the image is grayscale)
img = Image.open('path_to_your_image').convert('L')
# Converting the image into a numpy array
img_array = np.array(img)
# Define a kernel
kernel = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]])
# Perform the convolution
convoluted_img_array = 2D_convolution(img_array, kernel)
# Convert the result to an image and show it
plt.imshow(convoluted_img_array, cmap='gray')
plt.show()
Here I've used a simple sharpening kernel. The 2D_convolution function takes an image array and a kernel array as input, applies the convolution, and returns a new image array. Please replace 'path_to_your_image' with the actual path to your image.
Additionally, I've imported functions from other Python libraries to demonstrate how to handle images. This code shows the image after convolution. The PIL.Image library is used to read and handle image files, and matplotlib.pyplot is used to display images within a Jupyter notebook.
Remember that this simple implementation does not handle padding or strides, which are common in convolutional operations (especially in neural networks). For more advanced functionality, you would typically use libraries such as scipy, opencv, or deep learning frameworks like tensorflow or pytorch which have highly optimized implementations of convolution.