Created
September 27, 2022 17:40
-
-
Save 3zhang/bd8ac9636e91582bda0ec238bd6ef9ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"id": "e035b5f0", | |
"metadata": {}, | |
"source": [ | |
"2D convolution function based on Numpy's 1D convolution function:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"id": "58ac51c6", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import numpy as np\n", | |
"\n", | |
"def conv_2d(A, B):\n", | |
" n_A = A.shape[0]\n", | |
" n_B = B.shape[0]\n", | |
" B_p = np.pad(B, ((n_A-1, n_A-1), (0,0)))\n", | |
" n_G = n_A + n_B - 1\n", | |
" G = []\n", | |
" for i in range(n_G):\n", | |
" G_i = 0\n", | |
" for j in range(n_A):\n", | |
" G_i += np.convolve(A[j,], B_p[i-j+n_A-1,])\n", | |
" G.append(G_i)\n", | |
" G = np.vstack(G)\n", | |
" return G" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"id": "73e0a8ab", | |
"metadata": {}, | |
"source": [ | |
"Run the function:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"id": "de342c36", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"A = np.random.randint(0, 10, (5, 4))\n", | |
"B = np.random.randint(0, 10, (3, 7))\n", | |
"\n", | |
"G1 = conv_2d(A, B)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"id": "9a6289ec", | |
"metadata": {}, | |
"source": [ | |
"Check with Scipy's convolve function" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"id": "b4aab197", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"0.0\n" | |
] | |
} | |
], | |
"source": [ | |
"from scipy.signal import convolve\n", | |
"\n", | |
"G2 = convolve(A, B)\n", | |
"print(np.linalg.norm(G1 - G2)) #If difference norm is 0 then G1=G2" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3 (Spyder)", | |
"language": "python3", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.8.8" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment