双边高斯滤波python代码
时间: 2023-09-21 19:10:37 浏览: 105
双边滤波代码
4星 · 用户满意度95%
以下是一个简单的双边高斯滤波的Python实现,使用OpenCV库:
```python
import cv2
import numpy as np
def bilateral_filter(image, d, sigma_color, sigma_space):
# 创建一个空白的目标图像
filtered_image = np.zeros_like(image)
# 计算卷积核的尺寸
kernel_size = 2 * d + 1
# 计算空间权重
space_weights = cv2.getGaussianKernel(kernel_size, sigma_space)
# 遍历每个像素
for i in range(image.shape[0]):
for j in range(image.shape[1]):
# 计算颜色权重
color_weights = np.zeros((kernel_size, kernel_size))
center_pixel = image[i, j]
for m in range(kernel_size):
for n in range(kernel_size):
neighbor_pixel = image[i - d + m, j - d + n]
color_dist = np.sum((center_pixel - neighbor_pixel) ** 2)
color_weights[m, n] = np.exp(-color_dist / (2 * sigma_color ** 2))
# 计算像素点的权重
weights = color_weights * space_weights
weights = weights / np.sum(weights)
# 计算像素点的值
filtered_image[i, j] = np.sum(weights * image[i - d:i + d + 1, j - d:j + d + 1])
return filtered_image
```
这个函数接受一个输入图像,并使用指定的参数d,sigma_color和sigma_space来执行双边滤波。它返回一个过滤后的图像。
阅读全文