高斯滤波实现代码Python
时间: 2023-11-05 20:04:01 浏览: 72
以下是实现高斯滤波的Python代码:
```python
import cv2
import numpy as np
# 定义高斯核函数
def gaussian_kernel(size, sigma):
kernel = np.zeros((size, size))
center = size // 2
for i in range(size):
for j in range(size):
x = i - center
y = j - center
kernel[i, j] = np.exp(-(x ** 2 + y ** 2) / (2 * sigma ** 2))
kernel = kernel / np.sum(kernel)
return kernel
# 定义高斯滤波函数
def gaussian_filter(image, kernel):
h, w = image.shape
k_size = kernel.shape[0]
pad = k_size // 2
image_pad = np.pad(image, (pad, pad), 'edge')
image_filter = np.zeros((h, w))
for i in range(h):
for j in range(w):
image_filter[i, j] = np.sum(image_pad[i:i+k_size, j:j+k_size] * kernel)
return image_filter
# 读取图像
img = cv2.imread('lena.jpg', 0)
# 定义高斯核大小和标准差
k_size = 5
sigma = 1
# 生成高斯核
kernel = gaussian_kernel(k_size, sigma)
# 进行高斯滤波
img_filter = gaussian_filter(img, kernel)
# 显示原图和处理后的图像
cv2.imshow('original', img)
cv2.imshow('gaussian filter', img_filter)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
运行以上代码后,可以得到高斯滤波后的图像,并显示出来。其中,高斯核大小和标准差可以根据实际需求进行调整。
阅读全文