python中使用numpy函數實現圖像卷積,具體方法如下:
import numpy as np #導入numpy模塊
img=np.array([[1,1,1,0,0],
[0,1,1,1,0],
[0,0,1,1,1],
[0,0,1,1,0],
[0,1,1,0,0]])
fil=np.array([[1,0,1],
[0,1,0],
[1,0,1]])
def conv(image, weight):
height, width = image.shape
h, w = weight.shape
# 經滑動卷積操作后得到的新的圖像的尺寸
new_h = height -h + 1
new_w = width -w + 1
new_image = np.zeros((new_h, new_w), dtype=np.float)
# 進行卷積操作,實則是對應的窗口覆蓋下的矩陣對應元素值相乘,卷積操作
for i in range(new_w):
for j in range(new_h):
new_image[i, j] = np.sum(image[i:i+h, j:j+w] * weight)
# 去掉矩陣乘法后的小于0的和大于255的原值,重置為0和255
new_image = new_image.clip(0, 255)
new_image = np.rint(new_image).astype('uint8')
return new_image
imaconvo=conv(img,fil)
print(imaconvo)