學習《深度學習——入門與實踐》一書,代碼實現
卷積的目的在於將某些特徵從圖像中提取出來,正如視覺系統辨識具有方向性地物體邊緣一樣。
由於過濾後的新矩陣包含了原矩陣的特徵,故又被稱爲特徵圖,而卷積核由於具有過濾特定特徵的作用,又被稱爲濾波器。
不同的卷積核可以過濾出不同的特徵。
圖像邊緣的像素點通過該卷積核將得到加強,而非邊緣的像素點通過卷積核將被過濾掉,這也是卷積核被稱爲濾波器的原因。
#-*- 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")