文章摘要:python图像卷积用什么函数 python 图像卷积
python中使用numpy函数实现图像卷积,具体方法如下: import numpy as np #导入nu […]
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)