学习《深度学习——入门与实践》一书,代码实现
卷积的目的在于将某些特征从图像中提取出来,正如视觉系统辨识具有方向性地物体边缘一样。
由于过滤后的新矩阵包含了原矩阵的特征,故又被称为特征图,而卷积核由于具有过滤特定特征的作用,又被称为滤波器。
不同的卷积核可以过滤出不同的特征。
图像边缘的像素点通过该卷积核将得到加强,而非边缘的像素点通过卷积核将被过滤掉,这也是卷积核被称为滤波器的原因。
#-*- coding:utf-8 -*- from PIL import Image import numpy as np import os im = np.array(Image.open('C:\\Users\\11491\\Desktop\\car.jpg'))# 将原图转入并转化为数组 print(im) print(im[0][0]) print(len(im)) # 行数 print(len(im[0])) # 列数 print(len(im[0][0])) # 维度 im_grey = Image.open('C:/Users/11491/Desktop/car.jpg') # 读入原图并转化为灰度图像,参数为L则将RGB图像转化为灰度图像 im_grey = im_grey.convert('L') try: im_grey.save("carGrey.jpg") except IOError: print("Cannot convert") im_grey.show() im_grey=np.array(im_grey) conv_a= np.array([[1,0,-1],[0,0,0],[-1,0,1]]) # 3*3卷积核0101-41010——0 -1-1-1-18-1-1-1-1——1 10-1000-101——2 def conv(im_array, conv_x): # 传入图像矩阵和卷积核 im_copy = im_array.copy() height, width = im_copy.shape # 图像的高度和宽度 for i in range(0, height-2): for j in range(0,width-2): tmp = (im_array[(i):(i+3),(j):(j+3)]*conv_x).sum() if tmp > 255: tmp = 255 elif tmp < 0: tmp = 0 im_copy[i][j] = tmp return im_copy im_conv = conv(im_grey, conv_a) new_im = Image.fromarray(im_conv) new_im.show() new_im.save("carConv2.jpg")