From 95be9dd632c938cfd4695fe7481f2acb464ea8fe Mon Sep 17 00:00:00 2001 From: Jens Ahrensfeld Date: Fri, 29 May 2026 10:11:11 +0200 Subject: [PATCH] [conv2d] - add 2D convolution function and test Co-Authored-By: Claude Sonnet 4.6 --- src/rbm/image.py | 26 ++++++++++++++++++++++++++ src/tests/test_conv2d.py | 12 ++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/tests/test_conv2d.py diff --git a/src/rbm/image.py b/src/rbm/image.py index 83d8d44..05839af 100644 --- a/src/rbm/image.py +++ b/src/rbm/image.py @@ -48,3 +48,29 @@ class SubImage: k += 1 return result + +def conv2d(image: Mat, kernel: Mat, stride: tuple[int,int]): + pad_x = int((kernel.shape[0] - 1)/2) + pad_y = int((kernel.shape[1] - 1)/2) + image_padded = np.pad(image, pad_width=(pad_x, pad_y)) + + nx = (image_padded.shape[0] - kernel.shape[0]) + ny = (image_padded.shape[1] - kernel.shape[1]) + if nx % stride[0]: + raise ValueError + if ny % stride[1]: + raise ValueError + pass + + result = np.zeros((image_padded.shape[0] + kernel.shape[0] - 1, image_padded.shape[1] + kernel.shape[1] - 1)) + k = 0 + for r in range(pad_y, image_padded.shape[0]-pad_y): + result[r,:] = np.convolve(image_padded[r,:], kernel[k,:]) + k += 1 + + k = 0 + for c in range(pad_x, image_padded.shape[1]-pad_x): + result[:, c] += np.convolve(image_padded[:,c], kernel[:,k]) + k += 1 + + return result diff --git a/src/tests/test_conv2d.py b/src/tests/test_conv2d.py new file mode 100644 index 0000000..3bb30cb --- /dev/null +++ b/src/tests/test_conv2d.py @@ -0,0 +1,12 @@ +from rbm.image import conv2d +from rbm.matrix import np + + +if __name__ == "__main__": + A = np.random.rand(3, 3) + K = np.random.rand(3, 3) + + y = conv2d(A, K, (1,1)) + print(y) + + print("Test: [passed]")