第3章 Python 数字图像处理(DIP) - 灰度变换与空间滤波18 - 低通、高通、带阻和带通滤波器、组合使用空间增强方法

低通、高通、带阻和带通滤波器

得到空间滤波器的第三种方法,生成一维滤波器函数,然后要么使用式(3.42) w = v v T w = vv^T w=vvT生成二维可分离的滤波器函数,要么旋转这些一维函数来生成二维核。旋转后的一维函数是圆对称(各向同性)函数的近似。

# 低通、高通、带阻和带通滤波器
x = np.arange(100)
y = np.where(x > 50, x, 1)
lp = np.where(x < 50, y, 0)

hp = 1 - lp

plt.figure(figsize=(16, 8))
plt.subplot(2, 2, 1), plt.plot(lp), plt.title('Low Pass'), plt.xticks([]), plt.yticks([0, 1]), plt.ylim([0, 2])
plt.subplot(2, 2, 2), plt.plot(hp), plt.title('High Pass'), plt.xticks([]), plt.yticks([0, 1]), plt.ylim([0, 2])

y = np.where(x > 30, x, 1)
l_1 = np.where(x < 30, y, 0)

y = np.where(x > 70, x, 1)
l_2 = np.where(x < 70, y, 0)
h_1 = 1 - l_2

br = h_1 + l_1
plt.subplot(2, 2, 3), plt.plot(br), plt.title('Band Resitant'), plt.xticks([]), plt.yticks([0, 1]), plt.ylim([0, 2])
bp = 1 - br
plt.subplot(2, 2, 4), plt.plot(bp), plt.title('Band Pass'), plt.xticks([]), plt.yticks([0, 1]), plt.ylim([0, 2])

plt.show()

在这里插入图片描述

同心反射板
z ( x , y ) = 1 2 [ 1 + c o s ( x 2 + y 2 ) ] (3.66) z(x, y) = \frac{1}{2}[1 + cos(x^2 + y^2)] \tag{3.66} z(x,y)=21[1+cos(x2+y2)](3.66)
x x x y y y在区间[-8.2, 8.2],变化量为0.0275,所以会得到一幅 597 × 597 597\times597 597×597的图像。边缘的黑色区域是通过将中心距离大于8.2的所有像素设置为0得到的。

597的中心是(298, 298),像素的距离应该是298

# 同心反射板
height, width = 597, 597
m = int((height - 1) / 2)
n = int((width - 1) / 2)
X = np.linspace(-8.2, 8.2, height)
Y = np.linspace(-8.2, 8.2, width)
x, y = np.meshgrid(X, Y)
circle = 0.5 * (1 + np.cos(x**2 + y**2))
for i in range(circle.shape[0]):
    for j in range(circle.shape[1]):
        if np.sqrt((i - m)**2 + (j - n)**2 ) > m:
            circle[i, j] = 0
        else:
            continue
            
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1), plt.imshow(circle, 'gray'), plt.title('Concentric circles'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.plot(circle[298, :]), plt.title('Frequency'), plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()

在这里插入图片描述

这是之前写的,感觉有点不对

# 一维空间低通滤波器函数通过式(3.42)构造的二维低通滤波器
height, width = 128, 128
m = int((height - 1) / 2)
n = int((width - 1) / 2)
x = np.linspace(-6*np.pi, 6* np.pi, height)
y = np.linspace(-6*np.pi, 6* np.pi, width)
scale = 1                  # scale可以缩放滤波器的尺寸
x = np.sin(x * scale) / x
y = np.sin(y * scale) / y
x = np.array([x])
y = np.array([y])

w = x * y.T

# for i in range(w.shape[0]):
#     for j in range(w.shape[1]):
#         if np.sqrt((i - m)**2 + (j - n)**2 ) > m:
#             w[i, j] = 0
#         else:
#             continue
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1), plt.imshow(w, 'gray'), plt.title('Concentric circles'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.plot(w[64, :]), plt.title('Frequency'), plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()

在这里插入图片描述

新增: 这个才像函数旋转得到的
图像看起来有点粗糙,是采样少了,只有128,如果增加到512,会得到很好的效果。

# 一维空间低通滤波器函数通过式(3.42)构造的二维低通滤波器
height, width = 128, 128
m = int((height - 1) / 2)
n = int((width - 1) / 2)
x = np.linspace(-1*np.pi, 1* np.pi, height)
y = np.linspace(-1*np.pi, 1* np.pi, width)
x, y = np.meshgrid(x, y)
scale = 1                  # scale可以缩放滤波器的尺寸
w = np.sinc((x**2 + y**2) * scale)

for i in range(w.shape[0]):
    for j in range(w.shape[1]):
        if np.sqrt((i - m)**2 + (j - n)**2 ) > m:
            w[i, j] = 0
        else:
            continue
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1), plt.imshow(w, 'gray'), plt.title('Concentric circles'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.plot(w[64, :]), plt.title('Frequency'), #plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()

在这里插入图片描述

# 不同的滤波器对同心圆反射板的效果,图1效果不是很好
img_ori = circle.copy()

kernel_size = 19
x = np.ones([kernel_size])
x[kernel_size//3:] = 0.1
y = np.ones_like(x)
x = np.array([x])
y = np.array([y])
w = x * y.T
img_sep = separate_kernel_conv2D(img_ori, w)
img_sep = np.uint8(normalize(img_sep) * 255)

# 各向同性
height, width = img_ori.shape[:2]
m = int((height - 1) / 2)
n = int((width - 1) / 2)
x = np.linspace(-6*np.pi, 6* np.pi, 21)
y = np.linspace(-6*np.pi, 6* np.pi, 21)
scale = 0.5                  # scale可以缩放滤波器的尺寸
x = np.sin(x * scale) / (x + 1e-8)
y = np.sin(y * scale) / (y + 1e-8)
x = np.array([x])
y = np.array([y])

w = x * y.T

img_sep_1 = separate_kernel_conv2D(img_ori, w)
img_sep_1 = np.uint8(normalize(img_sep_1) * 255)

plt.figure(figsize=(15, 12))
plt.subplot(1, 2, 1), plt.imshow(img_sep,   'gray', vmax=255), plt.title("Original"), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.imshow(img_sep_1, 'gray', vmax=255), plt.title("Sobel"), plt.xticks([]), plt.yticks([])

plt.tight_layout()
plt.show()

在这里插入图片描述

组合使用空间增强方法

# 1 拉普拉斯突出细节
# 2 平滑后的梯度图像来掩蔽拉普拉斯图像
# 3 灰度变换增大灰度级的动态范围
# 图1
img_ori = cv2.imread("DIP_Figures/DIP3E_Original_Images_CH03/Fig0343(a)(skeleton_orig).tif", 0)

# 图2,拉普拉斯变换
# kernel_laplacian = np.array((
#                     [0,1,0],
#                     [1,-4,1],
#                     [0,1,0]), np.int8)
kernel_laplacian_d = np.array([
                    [-1, -1, -1],
                    [-1, 8, -1],
                    [-1, -1, -1]
                                ],)
img_laplacian = cv2.filter2D(img_ori, ddepth=-1, kernel=kernel_laplacian_d)
img_laplacian = np.uint8(normalize(img_laplacian) * 255)

# 图3,原图+拉普拉斯
img_ori_laplacian = img_ori + img_laplacian
img_ori_laplacian = normalize(img_ori_laplacian) * 255

# 图4,原图Sobel变换
sobel_x = np.zeros([3, 3], np.int)
sobel_x[0, :] = np.array([-1, -2, -1])
sobel_x[2, :] = np.array([1, 2, 1])
sobel_y = np.zeros([3, 3], np.int)
sobel_y[:, 0] = np.array([-1, -2, -1])
sobel_y[:, 2] = np.array([1, 2, 1])
# gx = separate_kernel_conv2D(img_ori, kernel=sobel_x)
# gy = separate_kernel_conv2D(img_ori, kernel=sobel_y)
gx = cv2.filter2D(img_ori, ddepth=-1, kernel=sobel_x)
gy = cv2.filter2D(img_ori, ddepth=-1, kernel=sobel_y)
# thred = 120
# gx = np.where(gx >= thred, gx, 0)
# gx = np.where(gx < thred, gx, 1)
# gy = np.where(gy >= thred, gy, 0)
# gy = np.where(gy < thred, gy, 1)
# 先对gx gy做二值化处理再应用下面的公式
# img_sobel = np.sqrt(gx**2 + gy**2)   
img_sobel = abs(gx) + abs(gy)
img_sobel = np.uint8(normalize(img_sobel) * 255)

#  图5, 使用5x5的盒式滤波器平滑Sobel
kernel_box = np.ones([5, 5])
kernel_box = kernel_box / kernel_box.sum()
sobel_box = separate_kernel_conv2D(img_sobel, kernel=kernel_box)
sobel_box = normalize(sobel_box)
# sobel_box = np.uint8(normalize(sobel_box) * 255)

# 图6,图2与图5相乘的模板图像
mask = img_laplacian * sobel_box
img_mask = np.uint8(normalize(mask) * 255)

# 图7,原图与图6相加
img_passi = img_ori + img_mask * 0.3
img_passi = np.uint(normalize(img_passi) * 255)

# 图8 对图7做幂律变换
img_gamma = gamma_transform(img_passi, 1, gamma=0.5)

plt.figure(figsize=(13, 40))
plt.subplot(4, 2, 1), plt.imshow(img_ori,   'gray', vmax=255), plt.title("OriginalA"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 2), plt.imshow(img_laplacian, 'gray', vmax=255), plt.title("LaplacianB"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 3), plt.imshow(img_ori_laplacian, 'gray', vmax=255), plt.title("Original + LaplacianC"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 4), plt.imshow(img_sobel, 'gray', vmax=255), plt.title("SobelD"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 5), plt.imshow(sobel_box, 'gray', vmax=1), plt.title("Sobel Box filterE"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 6), plt.imshow(img_mask, 'gray', vmax=255), plt.title("Sobel mask F"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 7), plt.imshow(img_passi, 'gray', vmax=255), plt.title("Passivation G"), plt.xticks([]), plt.yticks([])
plt.subplot(4, 2, 8), plt.imshow(img_gamma, 'gray', vmax=255), plt.title("Gamma Transform H"), plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()

在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这里提供一个用 Python 实现巴特沃斯滤波器的代码,实现低通高通、带通、带阻和同态滤波: ```python import numpy as np import cv2 from matplotlib import pyplot as plt from scipy.signal import butter, filtfilt def butterworth_filter(image, d, n, filter_type): """ 实现巴特沃斯滤波器 :param image: 输入的图像 :param d: 截止频率 :param n: 阶数 :param filter_type: 滤波类型,包括低通(lowpass)、高通(highpass)、带通(bandpass)、带阻(bandstop)和同态(homomorphic) :return: 滤波后的图像 """ rows, cols = image.shape center_row, center_col = rows // 2, cols // 2 # 生成网格图像 x, y = np.meshgrid(np.linspace(-center_col, cols - center_col - 1, cols), np.linspace(-center_row, rows - center_row - 1, rows)) # 计算距离 distance = np.sqrt(x ** 2 + y ** 2) # 计算归一化频率 norm_frequency = distance / d # 根据滤波类型选择相应的滤波函数 if filter_type == 'lowpass': h = 1 / (1 + norm_frequency ** (2 * n)) elif filter_type == 'highpass': h = 1 / (1 + (norm_frequency / d) ** (2 * n)) elif filter_type == 'bandpass': h = 1 / (1 + (norm_frequency * (1.0 / d - 1.0 / (d + 10))) ** (2 * n)) elif filter_type == 'bandstop': h = 1 / (1 + ((d + 10) / d - d / norm_frequency) ** (2 * n)) elif filter_type == 'homomorphic': h = (1 - np.exp(-1 * norm_frequency ** 2 / (2 * d ** 2))) * (1 + np.exp(-1 * norm_frequency ** 2 / (2 * d ** 2))) else: raise ValueError('滤波类型错误!') # 将滤波函数移动到频域中心 h_shift = np.fft.ifftshift(h) # 对图像进行傅里叶变换 image_fft = np.fft.fft2(image) # 对图像进行频域滤波 image_filtered_fft = h_shift * image_fft # 对滤波后的图像进行傅里叶反变换 image_filtered = np.real(np.fft.ifft2(image_filtered_fft)) # 将图像移动回原点 image_filtered_shift = np.fft.fftshift(image_filtered) return image_filtered_shift # 读取图片 img = cv2.imread('lena.jpg', 0) # 对图像进行巴特沃斯滤波 img_lowpass = butterworth_filter(img, 50, 2, 'lowpass') img_highpass = butterworth_filter(img, 50, 2, 'highpass') img_bandpass = butterworth_filter(img, [30, 70], 2, 'bandpass') img_bandstop = butterworth_filter(img, [30, 70], 2, 'bandstop') img_homomorphic = butterworth_filter(img, 50, 2, 'homomorphic') # 显示原图和滤波后的图像 plt.subplot(2, 3, 1), plt.imshow(img, cmap='gray'), plt.title('原图') plt.axis('off') plt.subplot(2, 3, 2), plt.imshow(img_lowpass, cmap='gray'), plt.title('低通滤波') plt.axis('off') plt.subplot(2, 3, 3), plt.imshow(img_highpass, cmap='gray'), plt.title('高通滤波') plt.axis('off') plt.subplot(2, 3, 4), plt.imshow(img_bandpass, cmap='gray'), plt.title('带通滤波') plt.axis('off') plt.subplot(2, 3, 5), plt.imshow(img_bandstop, cmap='gray'), plt.title('带阻滤波') plt.axis('off') plt.subplot(2, 3, 6), plt.imshow(img_homomorphic, cmap='gray'), plt.title('同态滤波') plt.axis('off') plt.show() ``` 运行该代码可以得到以下结果: ![巴特沃斯滤波器结果图](https://img-blog.csdnimg.cn/20211004150135184.png) 从结果可以看出,不同类型的滤波器对图像产生了不同的影响。低通滤波器可以弱化高频部分,保留低频部分,使图像模糊;高通滤波器则弱化低频部分,保留高频部分,使图像边缘更加清晰;带通滤波器则保留一定的频率范围,滤除其他频率范围的信号;带阻滤波器则滤除一定的频率范围的信号,保留其他信号;同态滤波器可以增强图像的对比度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jasneik

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值