天天看點

Python+opencv 高斯濾波

import cv2
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import random

# 設定畫圖支援中文
font = {'family': 'SimHei', 'size': 6}
matplotlib.rc('font', **font)


def add_gaussian_noise(image, sigma=20):
    img = image.astype(np.int16)  # 此步是為了避免像素點小于0,大于255的情況
    img_size = img.shape
    if len(img_size) == 3:
        x, y, z = img.shape
    else:
        x, y = img.shape
        z = 0
    mu = 0
    for i in range(x):
        for j in range(y):
            if img_size == 3:
                for k in range(z):
                    img[i, j, k] = img[i, j, k] + random.gauss(mu=mu, sigma=sigma)
            else:
                img[i, j] = img[i, j] + random.gauss(mu=mu, sigma=sigma)
    img[img > 255] = 255
    img[img < 0] = 0
    img = img.astype(np.uint8)
    return img


# 圖像路徑
img_path = 'lenna.bmp'

# 按三通道圖像格式讀入
source = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
if len(source.shape) > 2:  # 彩圖顯示到plt上需要将BGR轉為RGB
    source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)
source_noise = add_gaussian_noise(source)  # 給原圖添加高斯噪聲
source_noise_gaussian_filter = cv2.GaussianBlur(source_noise, (5, 5), 0)
source_noise_average_filtering_5x5 = cv2.blur(source_noise, ksize=(5, 5))

imgs = [source,
        source_noise,
        source_noise_gaussian_filter,
        source_noise_average_filtering_5x5]
titles = ['原圖',
          '噪聲圖',
          '噪聲圖高斯濾波',
          '噪聲圖均值濾波']

for idx in range(len(imgs)):
    plt.subplot(1, 4, idx + 1)  # 1行4列,将圖像放置在第idx+1位置上(從左往右,從上到下計數)
    plt.imshow(imgs[idx], cmap='gray')
    plt.title(titles[idx])
    plt.axis('off')

# 儲存圖像,bbox_inches='tight'去除邊緣空白,dpi設定圖像清晰度
plt.savefig('高斯濾波.png', bbox_inches='tight', dpi=300)
plt.show()
           
Python+opencv 高斯濾波