[conv2d] - add 2D convolution function and test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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]")
|
||||
Reference in New Issue
Block a user