from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltdef main(): im = Image.open("D:\\temp\\img\\bw.jpg") res=conv2(im,kv).astype(dtype="uint8") print(res) img2=Image.fromarray(res) img2.show()#计算结果可能不在[0,255]之间def Relu2(a): if a<0: return 0 if a>255: return 255#被卷积的图片,卷积核def conv2(im,kk): matrix = np.asarray(im) m1 = matrix[:, :, 0] m2 = matrix[:, :, 1] m3 = matrix[:, :, 2] matrix1=conv(m1,kk) matrix2=conv(m2,kk) matrix3=conv(m3,kk) return np.dstack((matrix1,matrix2,matrix3))#整体边缘滤波器ke=np.array([ [0,-4,0],[-4,16,-4],[0,-4,0]])#水平边缘滤波器kh=np.array([ [1,2,1],[0,0,0],[-1,-2,-1]])#垂直边缘滤波器kv=np.array([ [1,0,-1],[2,0,-2],[1,0,-1]])#被卷积一维矩阵,卷积核def conv(mx,kmx): v1=mx.shape[0] v2=mx.shape[1] kv1=kmx.shape[0] kv2=kmx.shape[1] l1=v1-kv1 l2=v2-kv2 res=np.zeros((l1,l2)) for i in range(l1): for j in range(l2): res[i][j]=Relu2((mx[i:i+kv1,j:j+kv2]*kmx).sum()) return resmain()
图像读出来是个三维矩阵,对每个通道使用不同卷积核卷积,观察效果
效果:
整体边缘滤波器:
水平边缘滤波器:
垂直边缘滤波器: