import numpy as npimport os
def conv_naive(x, w):N,H,W,C &#61; x.shapeKh, Kw, _C, Kc &#61; w.shapeassert(C&#61;&#61;_C), (x.shape, w.shape)y&#61; np.zeros([N, H-Kh &#43;1, W-Kw&#43;1, Kc])for i0 in range(N):for i1 in range(H - Kh &#43; 1):for i2 in range(W - Kw &#43; 1):for i3 in range(Kh):for i4 in range(Kw):for i5 in range(C):for i6 in range(Kc):if i1 - i3 < 0 or i2 - i4 < 0 or i1 - i3 >&#61; H or i2 - i4 >&#61; W: continuey[i0, i1, i2, i6] &#43;&#61; x[i0, i1 &#43; i3, i2 &#43; i4, i5] * w[i3, i4, i5, i6]return y
import pylab as pl
import PIL.Image as Image
import sys
import subprocess
img_path&#61;"cat.jpg"
if not os.path.isfile(img_path):cmd &#61; f"""wget -O - &#39;https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Felis_silvestris_catus_lying_on_rice_straw.jpg/220px-Felis_silvestris_catus_lying_on_rice_straw.jpg&#39; > {img_path}"""
im&#61;Image.open(img_path)
im.show()
img &#61; pl.imread(img_path)kernel &#61; np.array([[-1, -1, -1],[0, 0, 0],[1, 1, 1],
])
x &#61; img[np.newaxis,:,:,:1].astype("float32")
w &#61; kernel[:,:,np.newaxis,np.newaxis].astype("float32")y &#61; conv_naive(x, w)
print (x.shape, y.shape) img &#61; Image.fromarray(y[0,:,:,:], mode&#61;&#39;RGB&#39;)
img.show()
输出&#xff1a;
(1, 147, 220, 1) (1, 145, 218, 1)