import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from matplotlib import patches
Convolution Operation
Interactive tutorial on convolution operation with practical implementations and visualizations
= np.random.choice(range(10), (5, 5))
inp = np.array([
filter_conv 1, 0, -1],
[1, 0, -1],
[1, 0, -1]
[ ])
='Greys') plt.imshow(inp, cmap
= plt.subplots(ncols=3, figsize=(12, 4))
fig, ax
=True, cbar=None, ax=ax[0], cmap='Purples')
sns.heatmap(inp, annot=True, cbar=None, ax=ax[1], cmap='Purples')
sns.heatmap(filter_conv, annot= ax[0]
g = patches.Rectangle((0,0),3,3,linewidth=5,edgecolor='grey',facecolor='black', alpha=0.5)
rect
# Add the patch to the Axes
g.add_patch(rect)
0].set_title("Input")
ax[1].set_title("Filter") ax[
Text(0.5, 1.0, 'Filter')
from scipy.signal import convolve2d
='valid') convolve2d(inp, filter_conv, mode
array([[ 2, -3, -4],
[ 4, 8, -9],
[ 0, 14, -1]])
>>> from scipy import signal
>>> from scipy.misc import lena as lena
>>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j],
-10+0j, 0+ 0j, +10 +0j],
... [-3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy
... [ >>> grad = signal.convolve2d(lena, scharr, boundary='symm', mode='same')
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-37-70a7c69e1898> in <module> 1 from scipy import signal ----> 2 from scipy.misc import lena as lena 3 4 scharr = np.array([[ -3-3j, 0-10j, +3 -3j], 5 [-10+0j, 0+ 0j, +10 +0j], ImportError: cannot import name 'lena' from 'scipy.misc' (/home/nipunbatra-pc/anaconda3/lib/python3.7/site-packages/scipy/misc/__init__.py)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.animation
#####################
# Array preparation
#####################
#input array
= 6
n = 1
p = np.random.randint(0, 5, size=(n, n))
a # kernel
= np.array([[ 1,0, -1], [1, 0,-1], [ 1,0, -1]])
kernel = kernel.shape[0]
f
= True
padding
if padding:
# visualization array (2 bigger in each direction)
= np.zeros((a.shape[0]+2*p, a.shape[1]+2*p), dtype=int)
va -p,p:-p] = a
va[p:= np.zeros((a.shape[0]+2*p, a.shape[1]+2*p))
va_color -p,p:-p] = 0.5
va_color[p:else:
= a
va = np.zeros_like(a)
va_color
#output array
= np.zeros((n-f+1+2*p, n-f+1+2*p))
res
#####################
# Create inital plot
#####################
= plt.figure(figsize=(8,4))
fig
def add_axes_inches(fig, rect):
= fig.get_size_inches()
w,h return fig.add_axes([rect[0]/w, rect[1]/h, rect[2]/w, rect[3]/h])
= 3.
axwidth = axwidth/va.shape[1]
cellsize = cellsize*va.shape[0]
axheight
= add_axes_inches(fig, [cellsize, cellsize, axwidth, axheight])
ax_va = add_axes_inches(fig, [cellsize*2+axwidth,
ax_kernel 2+res.shape[0])*cellsize-kernel.shape[0]*cellsize,
(1]*cellsize,
kernel.shape[0]*cellsize])
kernel.shape[= add_axes_inches(fig, [cellsize*3+axwidth+kernel.shape[1]*cellsize,
ax_res 2*cellsize,
1]*cellsize,
res.shape[0]*cellsize])
res.shape["Kernel", size=12)
ax_kernel.set_title(
= ax_va.imshow(va_color, vmin=0., vmax=1.3, cmap="Blues")
im_va "Image size: {}X{}\n Padding: {}".format(n, n, p))
ax_va.set_title(for i in range(va.shape[0]):
for j in range(va.shape[1]):
="center", ha="center")
ax_va.text(j,i, va[i,j], va
=-1, vmax=1, cmap="Pastel1")
ax_kernel.imshow(np.zeros_like(kernel), vminfor i in range(kernel.shape[0]):
for j in range(kernel.shape[1]):
="center", ha="center")
ax_kernel.text(j,i, kernel[i,j], va
= ax_res.imshow(res, vmin=0, vmax=1.3, cmap="Greens")
im_res = []
res_texts for i in range(res.shape[0]):
= []
row for j in range(res.shape[1]):
"", va="center", ha="center"))
row.append(ax_res.text(j,i,
res_texts.append(row)
"Output size: {}X{}".format(n+2*p-f+1, n+2*p-f+1))
ax_res.set_title(
for ax in [ax_va, ax_kernel, ax_res]:
=False, bottom=False, labelleft=False, labelbottom=False)
ax.tick_params(left1,0))
ax.yaxis.set_major_locator(mticker.IndexLocator(1,0))
ax.xaxis.set_major_locator(mticker.IndexLocator(="k")
ax.grid(color
###############
# Animation
###############
def init():
for row in res_texts:
for text in row:
"")
text.set_text(
def animate(ij):
=ij
i,j= kernel.shape[1]//2
o # calculate result
= (kernel*va[1+i-o:1+i+o+1, 1+j-o:1+j+o+1]).sum()
res_ij
res_texts[i][j].set_text(res_ij)# make colors
= va_color.copy()
c 1+i-o:1+i+o+1, 1+j-o:1+j+o+1] = 1.
c[
im_va.set_array(c)
= res.copy()
r = 1
r[i,j]
im_res.set_array(r)
= np.indices(res.shape)
i,j = matplotlib.animation.FuncAnimation(fig, animate, init_func=init,
ani =zip(i.flat, j.flat), interval=5)
frames"algo.gif", writer="imagemagick") ani.save(
va
array([[0, 2, 2, 2, 0],
[4, 3, 0, 2, 2],
[1, 3, 3, 4, 2],
[3, 0, 0, 0, 2],
[0, 3, 4, 2, 3]])
i
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
= 0
i = 3
j =kernel.shape[1]//2
o *va[1+i-o:1+i+o+1, 1+j-o:1+j+o+1]) (kernel
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-127-a06f9a5b2501> in <module> 2 j = 3 3 o =kernel.shape[1]//2 ----> 4 (kernel*va[1+i-o:1+i+o+1, 1+j-o:1+j+o+1]) ValueError: operands could not be broadcast together with shapes (3,3) (3,2)
(kernel)
array([[ 1, 0, -1],
[ 1, 0, -1],
[ 1, 0, -1]])
1+i-o:1+i+o+1, 1+j-o:1+j+o+1] va[
array([[3, 2],
[2, 1],
[3, 0]])