def convo(x,k):
return np.array([sum(x[i:i+len(k)]*k) for i in range(len(x)-len(k)+1)])
x = np.array([1,3,2,5,1,0,7])
k = np.array([3,1,2])
print(convo(x,k)) # ได้ [10 21 13 16 17]
def convo(x,k,s=1,p=0):
if(p):
x = np.hstack([np.zeros(p),x,np.zeros(p)])
return np.array([sum(x[i:i+len(k)]*k) for i in range(0,len(x)-len(k)+1,s)])
x = np.array([3,5,7,1,2.1,0,3,4])
k = np.array([4,1,3])
print(convo(x,k,1,0)) # ได้ [38. 30. 35.3 6.1 17.4 15. ]
print(convo(x,k,2,0)) # ได้ [38. 35.3 17.4]
print(convo(x,k,1,1)) # ได้ [18. 38. 30. 35.3 6.1 17.4 15. 16. ]
full | ตัวกรองจะวิ่งตั้งแต่จุดที่เริ่มซ้อนกันแค่ช่องเดียว โดยมีการเพิ่มช่อง ผลที่ได้จะเป็นอาเรย์ขนาดใหญ่ขึ้น |
valid | ตัวกรองจะวิ่งแค่ภายในขอบเขตที่ซ้อนกันทุกช่อง ไม่มีการเพิ่มช่อง ผลที่ได้จะเป็นอาเรย์ขนาดเล็กลง |
same | ตัวกรองจะเริ่มวิ่งจากที่ซ้อนกันส่วนหนึ่ง โดยจะเพิ่มช่องเพื่อรักษาให้จำนวนอาเรย์ที่ได้เท่ากับอาเรย์ที่ป้อนเข้า |
x = np.array([2,0,-1,-2,3,2,-1])
k = np.array([1,3,4,2])
print(np.correlate(x,k,'full')) # ได้ [ 4 8 4 -6 -5 9 13 5 -1 -1]
print(np.correlate(x,k,'valid')) # ได้ [-6 -5 9 13]
print(np.correlate(x,k,'same')) # ได้ [ 8 4 -6 -5 9 13 5]
print(np.convolve(x,k,'full')) # ได้ [ 2 6 7 -1 -7 1 13 11 0 -2]
print(np.convolve(x,k,'valid')) # ได้ [-1 -7 1 13]
print(np.convolve(x,k,'same')) # ได้ [ 6 7 -1 -7 1 13 11]
def convo2d(x,k,s=1,p=0):
nx = x.shape
nk = k.shape
if(p):
if(type(p)==int):
p = p,p
nx = nx[0]+2*p[0],nx[1]+2*p[1]
x0 = np.zeros(nx)
x0[p[0]:nx[0]-p[0],p[1]:nx[1]-p[1]] = x
x = x0
if(type(s)==int):
s = s,s
return np.array([[(x[i:i+nk[0],j:j+nk[1]]*k).sum()
for j in range(0,nx[1]-nk[1]+1,s[1])]
for i in range(0,nx[0]-nk[0]+1,s[0])])
x = imageio.imread('c40a08.png')[:,:,0]
k = np.ones([5,5])
y = convo2d(x,k)
plt.figure(figsize=[5,6])
plt.axes([0,0,1,1])
plt.imshow(y,cmap='gray')
plt.axis('off')
plt.show()
from scipy.signal import correlate2d
x = np.random.random([100,100])
k = np.random.random([20,20])
plt.figure(figsize=[6,6])
plt.subplot(221)
plt.imshow(x,cmap='coolwarm')
plt.subplot(222)
plt.imshow(correlate2d(x,k,'full'),cmap='coolwarm')
plt.subplot(223)
plt.imshow(correlate2d(x,k,'valid'),cmap='coolwarm')
plt.subplot(224)
plt.imshow(correlate2d(x,k,'same'),cmap='coolwarm')
plt.tight_layout()
plt.show()
import imageio
def laiconvo(c,x,k,s=1,p=0):
if(p):
x = np.hstack([np.zeros(p),x,np.zeros(p)])
nx = len(x)
nk = len(k)
phap = []
for j in range(0,nx-nk+1,s):
fig = plt.figure(figsize=[(nx*3+2)/5.,3])
ax = plt.axes([0,0,1,1],aspect=1,xlim=[0,nx*3+0.1],ylim=[-6,9])
for i in range(nx):
if(j<=i<nk+j):
fc = '#ccbbff'
else:
fc = '#eeeeff'
pad = (i<p)|(nx-i<=p)
ax.add_patch(plt.Rectangle([i*3,0],3,3-pad*0.5,ec='k',fc=fc))
ax.text(i*3+1.5,1.5-pad*0.25,'%d'%x[i],va='center',ha='center',size=25)
for i in range(nk):
ax.add_patch(plt.Rectangle([(i+j)*3,5],3,3,ec='k',fc='#ccffcc'))
ax.text((i+j)*3+1.5,6.5,'%d'%k[i],va='center',ha='center',size=25)
ax.text((i+j)*3+1.5,4,r'$\times$',va='center',ha='center',size=25)
plt.arrow((i+j)*3+1.5,-0.2,((1.5*(nk-1))-i*3)*0.8,-1.7,head_width=0.5,length_includes_head=1)
for i in range(0,j+1,s):
if(i==j):
fc = '#ff6666'
else:
fc = '#ff9999'
v = (x[i:i+nk]*k).sum()
ax.add_patch(plt.Rectangle([i*3+(1.5*(nk-1)),-5],3,3,ec='k',fc=fc))
ax.text((i*3+1.5*(nk-1))+1.5,-3.5,'%d'%v,va='center',ha='center',size=25)
plt.axis('off')
fig.canvas.draw()
phap.append(np.array(fig.canvas.renderer._renderer))
plt.close()
imageio.mimsave(c,phap,fps=2.5)
x = np.random.randint(0,7,10)
k = np.random.randint(0,7,3)
laiconvo('e01.gif',x,k,1,0)
def senconvo(c,x,k):
nx = len(x)
nk = len(k)
x2 = np.array([sum(x[i:i+nk]*k) for i in range(0,nx-nk+1)])
nx2 = len(x2)
phap = []
for i in range(0,nx2,max(1,int(nx2/50))):
fig = plt.figure(figsize=[5,3])
ax = plt.axes([0.1,0.3,0.9,0.7],xlim=[0,nx-1],ylim=[x.min()-x.std()*0.2,x.max()+x.std()*0.2],xticks=[])
ax.spines['top'].set_visible(0)
ax.spines['right'].set_visible(0)
plt.plot(np.arange(nx),x,'#6677aa',alpha=0.2)
plt.plot(np.arange(nx)[:i+nk],x[:i+nk],'#6677aa')
plt.plot(np.arange(i,i+nk),k,'#66aa66')
plt.axvspan(i,i+nk-1,alpha=0.2,fc='#ddffdd',lw=3,ec='k')
ax = plt.axes([0.1,0,0.9,0.3],xlim=[0,nx-1],ylim=[x2.min()-x2.std()*0.2,x2.max()+x2.std()*0.2],xticks=[])
ax.spines['right'].set_visible(0)
ax.spines['bottom'].set_visible(0)
plt.plot((np.arange(0,i+1)),x2[:i+1],'#aa3333')
plt.plot([i,i],[x2[i],x2.max()+x2.std()*0.2],'k',lw=3,alpha=0.2)
fig.canvas.draw()
phap.append(np.array(fig.canvas.renderer._renderer))
plt.close()
imageio.mimsave(c,phap,duration=0.04)
x = np.random.normal(0,0.1,100).cumsum()
x -= np.linspace(0,x[-1],100)
x **= 3
k = np.random.normal(0,0.01,10).cumsum()
senconvo('e02.gif',x,k)
def laiconvo2d(c,x,k,s=1,p=0):
nx = x.shape
nk = k.shape
if(p):
if(type(p)==int):
p = p,p
nx = nx[0]+2*p[0],nx[1]+2*p[1]
x0 = np.zeros(nx)
x0[p[0]:nx[0]-p[0],p[1]:nx[1]-p[1]] = x
x = x0
if(type(s)==int):
s = s,s
nx2 = nx[0]-nk[0]+1,nx[1]-nk[1]+1
phap = []
for n in range(0,nx2[0],s[0]):
for m in range(0,nx2[1],s[1]):
fig = plt.figure(figsize=[nx[1],nx[0]+nx2[0]])
ax = plt.axes([0,(nx2[0]+0.5)/(nx[0]+nx2[0]+0.5),1,nx[0]/(nx[0]+nx2[0]+0.5)],aspect=1,xlim=[0,nx[1]*3+0.1],ylim=[-nx[0]*3-0.1,0])
ax2 =plt.axes([0,0,1,nx2[0]/(nx[0]+nx2[0]+0.5)],aspect=1,xlim=[0,nx2[1]*3+0.1],ylim=[-nx2[0]*3-0.1,0])
for j in range(nx[0]):
for i in range(nx[1]):
if(m<=i<nk[1]+m and n<=j<nk[0]+n):
fc = '#ccbbff'
else:
fc = '#eeeeff'
ax.add_patch(plt.Rectangle([i*3,-j*3-3],3,3,ec='k',fc=fc))
ax.text(i*3+1.5,-j*3-1.5,'%d'%x[j,i],va='center',ha='center',size=25)
for j in range(nk[0]):
for i in range(nk[1]):
ax.text((m+i)*3+2.25,-(n+j)*3-2.25,'$\\times%d$'%k[j,i],va='center',ha='center',size=18)
for j in range(0,nx2[0],s[0]):
for i in range(0,nx2[1],s[1]):
if(nx2[1]*j+i>nx2[1]*n+m):
break
if(i==m and j==n):
fc = '#ff6666'
else:
fc = '#ff9999'
ax2.add_patch(plt.Rectangle([i*3,-j*3-3],3,3,ec='k',fc=fc))
ax2.text(i*3+1.5,-j*3-1.5,'%d'%((x[j:j+nk[0],i:i+nk[1]]*k).sum()),va='center',ha='center',size=25)
ax.axis('off')
ax2.axis('off')
fig.canvas.draw()
phap.append(np.array(fig.canvas.renderer._renderer))
plt.close()
imageio.mimsave(c,phap,fps=2.5)
x = np.random.randint(0,10,[5,6])
k = np.random.randint(0,10,[3,3])
laiconvo2d('e09.gif',x,k,1,[0,0])
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ