以下是具体实现代码
import numpy as np import os from PIL import Image import matplotlib.pyplot as plt #卷积函数 def conv(img, weight): #img为输入图像 weight为卷积核 wei_h, wei_w = weight.shape img_h, img_w = img.shape # 经滑动卷积操作后得到的新的图像的尺寸 conv_h = img_h - wei_h + 1 conv_w = img_w - wei_w + 1 convimage = np.zeros((conv_h, conv_w), dtype=np.float) # 进行卷积操作,实则是对应的窗口覆盖下的矩阵对应元素值相乘,卷积操作 for i in range(conv_w): #3*3大小矩阵对应点相乘求和 for j in range(conv_h): convimage[i, j] = np.sum(img[i:i + wei_h, j:j + wei_w]* weight) # 去掉矩阵乘法后的小于0的和大于255的原值,重置为0和255 convimage = convimage.clip(0, 255) convimage = np.rint(convimage).astype('uint8') return convimage if __name__ == "__main__": G = Image.open("CR.png") # 读取图像数据 在本代码中读取的是与代码同个文件目录下的CR.png图片 out_path = "./out/" if not os.path.exists(out_path): os.mkdir(out_path) #创建路径 graph = np.array(G) #转换为numpy数组 kernel = np.array(([-1, 0, 1], [-2, 0, 2], [-1, 0, 1])) # 设置卷积核 R = conv(graph[:, :, 0], eval('kernel')) #分三个通道进行卷积 G = conv(graph[:, :, 1], eval('kernel')) B = conv(graph[:, :, 2], eval('kernel')) IMAGE = np.stack((R, G, B), axis=2) #三个通道合并生成图像IMAGE Image.fromarray(IMAGE).save("%s//CR7.jpg" % (out_path)) #输出图片到out文件夹