导向滤波(Guided Filter)是一种基于局部线性模型的滤波方法,用于图像处理中的去噪、图像增强和边缘保留等任务。它结合了引导图像(guide image)和输入图像来实现对输入图像的滤波操作。
在 Python 中,可以使用 OpenCV 库来实现导向滤波。以下是一个简单的示例代码:
import cv2
import numpy as np
def guided_filter(I, P, radius, eps):
mean_I = cv2.boxFilter(I, cv2.CV_64F, (radius, radius))
mean_P = cv2.boxFilter(P, cv2.CV_64F, (radius, radius))
mean_IP = cv2.boxFilter(I * P, cv2.CV_64F, (radius, radius))
cov_IP = mean_IP - mean_I * mean_P
mean_II = cv2.boxFilter(I * I, cv2.CV_64F, (radius, radius))
var_I = mean_II - mean_I * mean_I
a = cov_IP / (var_I + eps)
b = mean_P - a * mean_I
mean_a = cv2.boxFilter(a, cv2.CV_64F, (radius, radius))
mean_b = cv2.boxFilter(b, cv2.CV_64F, (radius, radius))
Q = mean_a * I + mean_b
return Q
# 读取图像
input_image = cv2.imread('input_image.jpg', 0)
guide_image = cv2.imread('guide_image.jpg', 0)
# 将图像转换为浮点数
input_image = np.float32(input_image) / 255.0
guide_image = np.float32(guide_image) / 255.0
# 调用导向滤波函数
radius = 5
eps = 0.01
output_image = guided_filter(guide_image, input_image, radius, eps)
# 显示结果
cv2.imshow('Input Image', input_image)
cv2.imshow('Guide Image', guide_image)
cv2.imshow('Filtered Image', output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()