这里写目录标题
- 平滑(低通)空间滤波器
- 盒式滤波器核
平滑(低通)空间滤波器
平滑(也称平均)空间滤波器用于降低灰度的急剧过渡
- 在图像重取样之前平滑图像以减少混淆
- 用于减少图像中无关细节
- 平滑因灰度级数量不足导致的图像中的伪轮廓
- 平滑核与一幅图像的卷积会模糊图像
盒式滤波器核
盒式核是最简单的可分离低通滤波器,其系数的值相同(通常为1)
m×nm\times{n}m×n的盒式滤波器为1的一个m×nm\times{n}m×n的阵列,其前面有一个归一化的常数,通过是1除以系数值之和(通过是1/mn1/mn1/mn)
def box_filter(image, kernel):""":param image: input image:param kernel: input kernel:return: image after convolution"""img_h = image.shape[0]img_w = image.shape[1]m = kernel.shape[0]n = kernel.shape[1]# paddingpadding_h = int((m -1)/2)padding_w = int((n -1)/2)image_pad = np.zeros((image.shape[0]+padding_h*2, image.shape[1]+padding_w*2), np.uint8)image_pad[padding_h:padding_h+img_h, padding_w:padding_w+img_w] = imageimage_convol = image.copy()for i in range(padding_h, img_h + padding_h):for j in range(padding_w, img_w + padding_w):temp = np.sum(image_pad[i-padding_h:i+padding_h+1, j-padding_w:j+padding_w+1] * kernel)image_convol[i - padding_h][j - padding_w] = temp # 1/(m * n) * tempreturn image_convol
# 盒式滤波器核
img = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH03/Fig0333(a)(test_pattern_blurring_orig).tif', 0)kernel_size = [3, 11, 21]fig = plt.figure(figsize=(10, 10))
for i in range(len(kernel_size) + 1):ax = fig.add_subplot(2, 2, i+1)if i == 0:ax.imshow(img, cmap='gray', vmin=0, vmax=255), ax.set_xticks([]), ax.set_yticks([])ax.set_title('Original')else:kernel = np.ones([kernel_size[i-1], kernel_size[i-1]])kernel = kernel / kernel.sizeimg_dst = box_filter(img, kernel)ax.imshow(img_dst, cmap='gray', vmin=0, vmax=255), ax.set_xticks([]), ax.set_yticks([])ax.set_title(f'kernel size {kernel_size[i-1]}')
plt.tight_layout()
plt.show()
# 盒式滤波器核 可分离核的效果
img = cv2.imread('DIP_Figures/DIP3E_Original_Images_CH03/Fig0333(a)(test_pattern_blurring_orig).tif', 0)kernel_size = [3, 11, 21]fig = plt.figure(figsize=(10, 10))
for i in range(len(kernel_size) + 1):ax = fig.add_subplot(2, 2, i+1)if i == 0:ax.imshow(img, cmap='gray', vmin=0, vmax=255), ax.set_xticks([]), ax.set_yticks([])ax.set_title('Original')else:kernel = np.ones([kernel_size[i-1], kernel_size[i-1]])kernel = kernel / kernel.sizeimg_dst = separate_kernel_conv2D(img, kernel)img_dst = normalize(img_dst) * 255ax.imshow(img_dst, cmap='gray', vmin=0, vmax=255), ax.set_xticks([]), ax.set_yticks([])ax.set_title(f'kernel size {kernel_size[i-1]}')
plt.tight_layout()
plt.show()