图像滤波

43 阅读2分钟

在学习AI视觉算法入门与调优中,记录一下常用函数和思路。

什么是滤波

图像滤波是图像处理中最常见的一种操作,它主要是可以改变图像中的某些特征,或者去除图像中的噪声

滤波操作的是通过一定的数学算法来完成的,最常见的滤波方式包括均值滤波、中值滤波和高斯滤波。

参考,百度百科

原图如下:

截图 2024-01-18 17-29-59.png

代码如下:

from typing import List

import cv2
from cv2 import typing as cv2ty
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.axes import Axes

# 新增加的两行, 支持显示中文
import matplotlib

matplotlib.rc("font", family="AR PL KaitiM GB")  # 中文字体支持

"""
# 查询当前系统所有字体
from matplotlib.font_manager import FontManager
import subprocess

mpl_fonts = set(f.name for f in FontManager().ttflist)

print('all font list get from matplotlib.font_manager:')
for f in sorted(mpl_fonts):
    print('\t' + f)

输出:

all font list get from matplotlib.font_manager:
    AR PL KaitiM Big5
    AR PL KaitiM GB
    AR PL Mingti2L Big5
    AR PL SungtiL GB
    ...
    ori1Uni
    padmaa
    padmaa-Bold.1.1
"""

# 读取图像
image = cv2.imread("flower.png")


# 添加椒盐噪声
def add_salt_and_pepper_noise(
    image: cv2ty.MatLike, salt_prob: float, pepper_prob: float
):
    noisy_image = image.copy()
    total_pixels = image.size

    # 添加椒盐噪声
    num_salt = np.ceil(salt_prob * total_pixels)
    salt_coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape]
    noisy_image[salt_coords[0], salt_coords[1], :] = 255

    num_pepper = np.ceil(pepper_prob * total_pixels)
    pepper_coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape]
    noisy_image[pepper_coords[0], pepper_coords[1], :] = 0

    return noisy_image


# 生成椒盐噪声
salt_and_pepper_image = add_salt_and_pepper_noise(
    image, salt_prob=0.02, pepper_prob=0.02
)

# 定义均值滤波器的大小
kernel_size = (8, 8)

# 应用均值滤波
filtered_image = cv2.blur(salt_and_pepper_image, kernel_size)

# 使用Matplotlib显示原始图像、椒盐噪声图像和滤波后的图像
fig, axes = plt.subplots(1, 3, figsize=(15, 5))

axes: List[Axes] = axes

axes[0].imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
axes[0].set_title("(原图)\nOriginal Image")
axes[0].axis("off")

axes[1].imshow(cv2.cvtColor(salt_and_pepper_image, cv2.COLOR_BGR2RGB))
axes[1].set_title("(有椒盐噪声的图像)\nImage with Salt and Pepper Noise")
axes[1].axis("off")

axes[2].imshow(cv2.cvtColor(filtered_image, cv2.COLOR_BGR2RGB))
axes[2].set_title("(滤波后的图像)\nFiltered Image")
axes[2].axis("off")

# 保存为图像
fig.savefig("flower_with_filtered.png")
plt.show()

滤波后图像如下:

flower_with_filtered.png

遇到的问题

当我想在matplotlib中显示中文时,默认字体方案不支持显示中文,故而查找到matplatlib中支持的所有字体列表,并输出,这里选择了一个支持显示中文的字体: "AR PL KaitiM GB", 中文随即可正常显示。

参考: zhuanlan.zhihu.com/p/104081310

最后

Great! 又掌握一个知识点!