高斯滤波算法python代码
时间: 2023-10-03 20:11:15 浏览: 120
以下是一个基于Python的高斯滤波算法代码示例:
```python
import cv2
import numpy as np
def gaussian_filter(image, kernel_size, sigma):
# define kernel
kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size // 2
for i in range(kernel_size):
for j in range(kernel_size):
x = i - center
y = j - center
kernel[i, j] = np.exp(-(x**2 + y**2)/(2*sigma**2))
kernel /= (2*np.pi*sigma**2)
kernel_sum = np.sum(kernel)
# apply filter
height, width = image.shape[:2]
filtered = np.zeros_like(image)
padded = np.pad(image, ((center, center), (center, center), (0, 0)), mode='constant')
for i in range(center, height+center):
for j in range(center, width+center):
filtered[i-center, j-center] = np.sum(padded[i-center:i+center+1, j-center:j+center+1] * kernel) / kernel_sum
return filtered
# read image
image = cv2.imread('lena.jpg')
# apply filter
filtered = gaussian_filter(image, 5, 1)
# show result
cv2.imshow('Original', image)
cv2.imshow('Filtered', filtered)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先定义了一个高斯核,并通过定义的高斯函数计算出每个像素的权重。然后,我们将这个核与输入图像进行卷积,并将结果返回为过滤图像。最后,我们使用OpenCV库的imshow函数显示原始图像和过滤后的图像。
阅读全文